From 10f381bc950e2d64c6e3db3d5ead0538ee450c2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Fri, 29 Jan 2021 21:16:18 +0100 Subject: [PATCH 01/22] Restrict fixes to be compatible with PHP 7.2 --- phpcs.xml.dist | 2 ++ 1 file changed, 2 insertions(+) diff --git a/phpcs.xml.dist b/phpcs.xml.dist index 68bcaa5f4b0..f9bade19bea 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -9,6 +9,8 @@ + + lib tests tools From 5b55b8c6cf658fced443d2d171a0cc313fb89e1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Fri, 29 Jan 2021 21:18:51 +0100 Subject: [PATCH 02/22] Disable rules that would result in BC-breaks --- phpcs.xml.dist | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/phpcs.xml.dist b/phpcs.xml.dist index f9bade19bea..f59a3243899 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -18,6 +18,7 @@ */tests/Doctrine/Tests/Proxies/__CG__/* + @@ -26,6 +27,14 @@ + + */lib/* + + + + */lib/* + + */tests/* From 68bc00b6c672349925c247951f13c7c90eb801e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Fri, 29 Jan 2021 21:21:58 +0100 Subject: [PATCH 03/22] Automatically fix CS --- lib/Doctrine/ORM/AbstractQuery.php | 180 ++-- lib/Doctrine/ORM/Cache.php | 30 +- .../ORM/Cache/AssociationCacheEntry.php | 7 +- lib/Doctrine/ORM/Cache/CacheConfiguration.php | 38 +- lib/Doctrine/ORM/Cache/CacheEntry.php | 4 - lib/Doctrine/ORM/Cache/CacheException.php | 12 +- lib/Doctrine/ORM/Cache/CacheFactory.php | 50 +- lib/Doctrine/ORM/Cache/CacheKey.php | 3 - .../ORM/Cache/CollectionCacheEntry.php | 3 - lib/Doctrine/ORM/Cache/CollectionCacheKey.php | 16 +- lib/Doctrine/ORM/Cache/CollectionHydrator.php | 22 +- lib/Doctrine/ORM/Cache/ConcurrentRegion.php | 15 +- lib/Doctrine/ORM/Cache/DefaultCache.php | 90 +- .../ORM/Cache/DefaultCacheFactory.php | 67 +- .../ORM/Cache/DefaultCollectionHydrator.php | 38 +- .../ORM/Cache/DefaultEntityHydrator.php | 62 +- lib/Doctrine/ORM/Cache/DefaultQueryCache.php | 136 ++-- lib/Doctrine/ORM/Cache/EntityCacheEntry.php | 11 +- lib/Doctrine/ORM/Cache/EntityCacheKey.php | 8 +- lib/Doctrine/ORM/Cache/EntityHydrator.php | 19 +- lib/Doctrine/ORM/Cache/Lock.php | 20 +- lib/Doctrine/ORM/Cache/LockException.php | 4 - .../ORM/Cache/Logging/CacheLogger.php | 45 +- .../ORM/Cache/Logging/CacheLoggerChain.php | 16 +- .../Cache/Logging/StatisticsCacheLogger.php | 23 +- lib/Doctrine/ORM/Cache/MultiGetRegion.php | 3 - .../ORM/Cache/Persister/CachedPersister.php | 8 +- .../AbstractCollectionPersister.php | 129 ++- .../Collection/CachedCollectionPersister.php | 19 +- ...rictReadWriteCachedCollectionPersister.php | 10 +- .../ReadOnlyCachedCollectionPersister.php | 12 +- .../ReadWriteCachedCollectionPersister.php | 24 +- .../Entity/AbstractEntityPersister.php | 147 ++-- .../Entity/CachedEntityPersister.php | 11 +- ...onStrictReadWriteCachedEntityPersister.php | 16 +- .../Entity/ReadOnlyCachedEntityPersister.php | 5 +- .../Entity/ReadWriteCachedEntityPersister.php | 22 +- lib/Doctrine/ORM/Cache/QueryCache.php | 19 +- lib/Doctrine/ORM/Cache/QueryCacheEntry.php | 5 +- lib/Doctrine/ORM/Cache/QueryCacheKey.php | 16 +- .../ORM/Cache/QueryCacheValidator.php | 8 +- lib/Doctrine/ORM/Cache/Region.php | 29 +- .../Cache/Region/DefaultMultiGetRegion.php | 10 +- .../ORM/Cache/Region/DefaultRegion.php | 36 +- .../ORM/Cache/Region/FileLockRegion.php | 79 +- .../ORM/Cache/Region/UpdateTimestampCache.php | 7 +- .../ORM/Cache/RegionsConfiguration.php | 63 +- .../ORM/Cache/TimestampCacheEntry.php | 5 +- lib/Doctrine/ORM/Cache/TimestampCacheKey.php | 3 - .../Cache/TimestampQueryCacheValidator.php | 20 +- lib/Doctrine/ORM/Cache/TimestampRegion.php | 7 +- lib/Doctrine/ORM/Configuration.php | 197 ++--- .../ORM/Decorator/EntityManagerDecorator.php | 13 +- lib/Doctrine/ORM/EntityManager.php | 186 ++--- lib/Doctrine/ORM/EntityManagerInterface.php | 57 +- lib/Doctrine/ORM/EntityNotFoundException.php | 7 +- lib/Doctrine/ORM/EntityRepository.php | 69 +- lib/Doctrine/ORM/Event/LifecycleEventArgs.php | 7 +- lib/Doctrine/ORM/Event/ListenersInvoker.php | 44 +- .../ORM/Event/LoadClassMetadataEventArgs.php | 14 +- .../OnClassMetadataNotFoundEventArgs.php | 23 +- lib/Doctrine/ORM/Event/OnClearEventArgs.php | 26 +- lib/Doctrine/ORM/Event/OnFlushEventArgs.php | 18 +- lib/Doctrine/ORM/Event/PostFlushEventArgs.php | 17 +- lib/Doctrine/ORM/Event/PreFlushEventArgs.php | 17 +- lib/Doctrine/ORM/Event/PreUpdateEventArgs.php | 29 +- lib/Doctrine/ORM/Events.php | 54 +- lib/Doctrine/ORM/Id/AbstractIdGenerator.php | 3 +- lib/Doctrine/ORM/Id/AssignedGenerator.php | 13 +- .../ORM/Id/BigIntegerIdentityGenerator.php | 4 +- lib/Doctrine/ORM/Id/IdentityGenerator.php | 3 +- lib/Doctrine/ORM/Id/SequenceGenerator.php | 33 +- lib/Doctrine/ORM/Id/TableGenerator.php | 48 +- lib/Doctrine/ORM/Id/UuidGenerator.php | 6 +- .../ORM/Internal/CommitOrderCalculator.php | 38 +- .../Internal/Hydration/AbstractHydrator.php | 68 +- .../ORM/Internal/Hydration/ArrayHydrator.php | 91 +-- .../Internal/Hydration/HydrationException.php | 34 +- .../ORM/Internal/Hydration/IterableResult.php | 31 +- .../ORM/Internal/Hydration/ObjectHydrator.php | 164 ++-- .../ORM/Internal/Hydration/ScalarHydrator.php | 9 +- .../Hydration/SimpleObjectHydrator.php | 27 +- .../Hydration/SingleScalarHydrator.php | 16 +- .../ORM/Internal/HydrationCompleteHandler.php | 22 +- lib/Doctrine/ORM/LazyCriteriaCollection.php | 27 +- lib/Doctrine/ORM/Mapping/Annotation.php | 1 + .../ORM/Mapping/AnsiQuoteStrategy.php | 6 +- .../ORM/Mapping/AssociationOverride.php | 9 +- .../ORM/Mapping/AssociationOverrides.php | 6 +- .../ORM/Mapping/AttributeOverride.php | 8 +- .../ORM/Mapping/AttributeOverrides.php | 4 +- .../Mapping/Builder/AssociationBuilder.php | 46 +- .../Mapping/Builder/ClassMetadataBuilder.php | 36 +- .../ORM/Mapping/Builder/EmbeddedBuilder.php | 16 +- .../Mapping/Builder/EntityListenerBuilder.php | 31 +- .../ORM/Mapping/Builder/FieldBuilder.php | 34 +- .../Builder/ManyToManyAssociationBuilder.php | 17 +- .../Builder/OneToManyAssociationBuilder.php | 5 +- lib/Doctrine/ORM/Mapping/Cache.php | 9 +- .../ORM/Mapping/ChangeTrackingPolicy.php | 2 +- lib/Doctrine/ORM/Mapping/ClassMetadata.php | 1 + .../ORM/Mapping/ClassMetadataFactory.php | 190 ++--- .../ORM/Mapping/ClassMetadataInfo.php | 576 ++++++------- lib/Doctrine/ORM/Mapping/Column.php | 33 +- lib/Doctrine/ORM/Mapping/ColumnResult.php | 4 +- .../ORM/Mapping/CustomIdGenerator.php | 5 +- .../Mapping/DefaultEntityListenerResolver.php | 18 +- .../ORM/Mapping/DefaultNamingStrategy.php | 10 +- .../ORM/Mapping/DefaultQuoteStrategy.php | 27 +- .../ORM/Mapping/DiscriminatorColumn.php | 17 +- lib/Doctrine/ORM/Mapping/DiscriminatorMap.php | 5 +- .../ORM/Mapping/Driver/AnnotationDriver.php | 178 ++-- .../ORM/Mapping/Driver/DatabaseDriver.php | 121 ++- .../Mapping/Driver/DoctrineAnnotations.php | 101 +-- .../ORM/Mapping/Driver/DriverChain.php | 1 + lib/Doctrine/ORM/Mapping/Driver/PHPDriver.php | 1 + .../Mapping/Driver/SimplifiedXmlDriver.php | 7 +- .../Mapping/Driver/SimplifiedYamlDriver.php | 7 +- .../ORM/Mapping/Driver/StaticPHPDriver.php | 1 + lib/Doctrine/ORM/Mapping/Driver/XmlDriver.php | 134 +-- .../ORM/Mapping/Driver/YamlDriver.php | 129 +-- lib/Doctrine/ORM/Mapping/Embeddable.php | 1 + lib/Doctrine/ORM/Mapping/Embedded.php | 5 +- lib/Doctrine/ORM/Mapping/Entity.php | 9 +- .../ORM/Mapping/EntityListenerResolver.php | 3 - lib/Doctrine/ORM/Mapping/EntityListeners.php | 3 - lib/Doctrine/ORM/Mapping/EntityResult.php | 4 +- lib/Doctrine/ORM/Mapping/FieldResult.php | 4 +- lib/Doctrine/ORM/Mapping/GeneratedValue.php | 2 +- .../ORM/Mapping/HasLifecycleCallbacks.php | 1 + lib/Doctrine/ORM/Mapping/Id.php | 1 + lib/Doctrine/ORM/Mapping/Index.php | 17 +- lib/Doctrine/ORM/Mapping/InheritanceType.php | 2 +- lib/Doctrine/ORM/Mapping/JoinColumn.php | 25 +- lib/Doctrine/ORM/Mapping/JoinColumns.php | 5 +- lib/Doctrine/ORM/Mapping/JoinTable.php | 17 +- lib/Doctrine/ORM/Mapping/ManyToMany.php | 26 +- lib/Doctrine/ORM/Mapping/ManyToOne.php | 14 +- lib/Doctrine/ORM/Mapping/MappedSuperclass.php | 5 +- lib/Doctrine/ORM/Mapping/MappingException.php | 118 +-- .../ORM/Mapping/NamedNativeQueries.php | 4 +- lib/Doctrine/ORM/Mapping/NamedNativeQuery.php | 8 +- lib/Doctrine/ORM/Mapping/NamedQueries.php | 5 +- lib/Doctrine/ORM/Mapping/NamedQuery.php | 9 +- lib/Doctrine/ORM/Mapping/NamingStrategy.php | 11 +- lib/Doctrine/ORM/Mapping/OneToMany.php | 22 +- lib/Doctrine/ORM/Mapping/OneToOne.php | 22 +- lib/Doctrine/ORM/Mapping/OrderBy.php | 5 +- lib/Doctrine/ORM/Mapping/PostLoad.php | 1 + lib/Doctrine/ORM/Mapping/PostPersist.php | 1 + lib/Doctrine/ORM/Mapping/PostRemove.php | 1 + lib/Doctrine/ORM/Mapping/PostUpdate.php | 1 + lib/Doctrine/ORM/Mapping/PreFlush.php | 1 + lib/Doctrine/ORM/Mapping/PrePersist.php | 1 + lib/Doctrine/ORM/Mapping/PreRemove.php | 1 + lib/Doctrine/ORM/Mapping/PreUpdate.php | 1 + lib/Doctrine/ORM/Mapping/QuoteStrategy.php | 39 +- .../Reflection/ReflectionPropertiesGetter.php | 35 +- .../Mapping/ReflectionEmbeddedProperty.php | 31 +- .../ORM/Mapping/SequenceGenerator.php | 13 +- .../ORM/Mapping/SqlResultSetMapping.php | 4 +- .../ORM/Mapping/SqlResultSetMappings.php | 4 +- lib/Doctrine/ORM/Mapping/Table.php | 21 +- .../ORM/Mapping/UnderscoreNamingStrategy.php | 22 +- lib/Doctrine/ORM/Mapping/UniqueConstraint.php | 13 +- lib/Doctrine/ORM/Mapping/Version.php | 1 + lib/Doctrine/ORM/NativeQuery.php | 22 +- lib/Doctrine/ORM/NoResultException.php | 7 +- lib/Doctrine/ORM/NonUniqueResultException.php | 8 +- lib/Doctrine/ORM/ORMException.php | 61 +- .../ORM/ORMInvalidArgumentException.php | 97 ++- lib/Doctrine/ORM/OptimisticLockException.php | 23 +- lib/Doctrine/ORM/PersistentCollection.php | 114 +-- .../AbstractCollectionPersister.php | 35 +- .../Collection/CollectionPersister.php | 33 +- .../Collection/ManyToManyPersister.php | 142 ++-- .../Collection/OneToManyPersister.php | 41 +- .../AbstractEntityInheritancePersister.php | 20 +- .../Entity/BasicEntityPersister.php | 424 +++++----- .../Entity/CachedPersisterContext.php | 11 +- .../ORM/Persisters/Entity/EntityPersister.php | 66 +- .../Entity/JoinedSubclassPersister.php | 141 ++-- .../Entity/SingleTablePersister.php | 14 +- .../ORM/Persisters/PersisterException.php | 12 +- .../ORM/Persisters/SqlExpressionVisitor.php | 50 +- .../ORM/Persisters/SqlValueVisitor.php | 26 +- lib/Doctrine/ORM/PessimisticLockException.php | 7 +- lib/Doctrine/ORM/Proxy/Autoloader.php | 1 + lib/Doctrine/ORM/Proxy/Proxy.php | 4 +- lib/Doctrine/ORM/Proxy/ProxyFactory.php | 52 +- lib/Doctrine/ORM/Query.php | 155 ++-- lib/Doctrine/ORM/Query/AST/ASTException.php | 5 +- .../ORM/Query/AST/AggregateExpression.php | 17 +- .../ORM/Query/AST/ArithmeticExpression.php | 13 +- .../ORM/Query/AST/ArithmeticFactor.php | 15 +- lib/Doctrine/ORM/Query/AST/ArithmeticTerm.php | 9 +- .../ORM/Query/AST/BetweenExpression.php | 25 +- .../ORM/Query/AST/CoalesceExpression.php | 13 +- .../Query/AST/CollectionMemberExpression.php | 16 +- .../ORM/Query/AST/ComparisonExpression.php | 21 +- .../ORM/Query/AST/ConditionalExpression.php | 9 +- .../ORM/Query/AST/ConditionalFactor.php | 13 +- .../ORM/Query/AST/ConditionalPrimary.php | 13 +- .../ORM/Query/AST/ConditionalTerm.php | 10 +- lib/Doctrine/ORM/Query/AST/DeleteClause.php | 13 +- .../ORM/Query/AST/DeleteStatement.php | 13 +- .../EmptyCollectionComparisonExpression.php | 13 +- .../ORM/Query/AST/ExistsExpression.php | 13 +- lib/Doctrine/ORM/Query/AST/FromClause.php | 10 +- .../ORM/Query/AST/Functions/AbsFunction.php | 18 +- .../ORM/Query/AST/Functions/AvgFunction.php | 16 +- .../Query/AST/Functions/BitAndFunction.php | 10 +- .../ORM/Query/AST/Functions/BitOrFunction.php | 10 +- .../Query/AST/Functions/ConcatFunction.php | 20 +- .../ORM/Query/AST/Functions/CountFunction.php | 18 +- .../AST/Functions/CurrentDateFunction.php | 13 +- .../AST/Functions/CurrentTimeFunction.php | 13 +- .../Functions/CurrentTimestampFunction.php | 13 +- .../Query/AST/Functions/DateAddFunction.php | 19 +- .../Query/AST/Functions/DateDiffFunction.php | 6 +- .../Query/AST/Functions/DateSubFunction.php | 15 +- .../ORM/Query/AST/Functions/FunctionNode.php | 23 +- .../Query/AST/Functions/IdentityFunction.php | 42 +- .../Query/AST/Functions/LengthFunction.php | 15 +- .../Query/AST/Functions/LocateFunction.php | 21 +- .../ORM/Query/AST/Functions/LowerFunction.php | 13 +- .../ORM/Query/AST/Functions/MaxFunction.php | 16 +- .../ORM/Query/AST/Functions/MinFunction.php | 16 +- .../ORM/Query/AST/Functions/ModFunction.php | 22 +- .../ORM/Query/AST/Functions/SizeFunction.php | 67 +- .../ORM/Query/AST/Functions/SqrtFunction.php | 18 +- .../Query/AST/Functions/SubstringFunction.php | 22 +- .../ORM/Query/AST/Functions/SumFunction.php | 16 +- .../ORM/Query/AST/Functions/TrimFunction.php | 42 +- .../ORM/Query/AST/Functions/UpperFunction.php | 13 +- .../ORM/Query/AST/GeneralCaseExpression.php | 17 +- lib/Doctrine/ORM/Query/AST/GroupByClause.php | 9 +- lib/Doctrine/ORM/Query/AST/HavingClause.php | 9 +- .../AST/IdentificationVariableDeclaration.php | 21 +- lib/Doctrine/ORM/Query/AST/InExpression.php | 22 +- lib/Doctrine/ORM/Query/AST/IndexBy.php | 9 +- lib/Doctrine/ORM/Query/AST/InputParameter.php | 27 +- .../ORM/Query/AST/InstanceOfExpression.php | 17 +- lib/Doctrine/ORM/Query/AST/Join.php | 25 +- .../Query/AST/JoinAssociationDeclaration.php | 15 +- .../AST/JoinAssociationPathExpression.php | 13 +- .../ORM/Query/AST/JoinClassPathExpression.php | 14 +- .../ORM/Query/AST/JoinVariableDeclaration.php | 18 +- lib/Doctrine/ORM/Query/AST/LikeExpression.php | 26 +- lib/Doctrine/ORM/Query/AST/Literal.php | 17 +- .../ORM/Query/AST/NewObjectExpression.php | 11 +- lib/Doctrine/ORM/Query/AST/Node.php | 32 +- .../Query/AST/NullComparisonExpression.php | 13 +- .../ORM/Query/AST/NullIfExpression.php | 15 +- lib/Doctrine/ORM/Query/AST/OrderByClause.php | 9 +- lib/Doctrine/ORM/Query/AST/OrderByItem.php | 20 +- .../ORM/Query/AST/ParenthesisExpression.php | 10 +- .../ORM/Query/AST/PartialObjectExpression.php | 11 +- lib/Doctrine/ORM/Query/AST/PathExpression.php | 32 +- .../ORM/Query/AST/QuantifiedExpression.php | 22 +- .../Query/AST/RangeVariableDeclaration.php | 23 +- lib/Doctrine/ORM/Query/AST/SelectClause.php | 15 +- .../ORM/Query/AST/SelectExpression.php | 23 +- .../ORM/Query/AST/SelectStatement.php | 31 +- .../Query/AST/SimpleArithmeticExpression.php | 9 +- .../ORM/Query/AST/SimpleCaseExpression.php | 23 +- .../ORM/Query/AST/SimpleSelectClause.php | 15 +- .../ORM/Query/AST/SimpleSelectExpression.php | 13 +- .../ORM/Query/AST/SimpleWhenClause.php | 15 +- lib/Doctrine/ORM/Query/AST/Subselect.php | 31 +- .../ORM/Query/AST/SubselectFromClause.php | 9 +- ...electIdentificationVariableDeclaration.php | 13 +- .../ORM/Query/AST/TypedExpression.php | 4 +- lib/Doctrine/ORM/Query/AST/UpdateClause.php | 19 +- lib/Doctrine/ORM/Query/AST/UpdateItem.php | 15 +- .../ORM/Query/AST/UpdateStatement.php | 13 +- lib/Doctrine/ORM/Query/AST/WhenClause.php | 17 +- lib/Doctrine/ORM/Query/AST/WhereClause.php | 9 +- .../ORM/Query/Exec/AbstractSqlExecutor.php | 20 +- .../Query/Exec/MultiTableDeleteExecutor.php | 49 +- .../Query/Exec/MultiTableUpdateExecutor.php | 69 +- .../ORM/Query/Exec/SingleSelectExecutor.php | 8 +- .../Exec/SingleTableDeleteUpdateExecutor.php | 11 +- lib/Doctrine/ORM/Query/Expr.php | 34 +- lib/Doctrine/ORM/Query/Expr/Andx.php | 15 +- lib/Doctrine/ORM/Query/Expr/Base.php | 47 +- lib/Doctrine/ORM/Query/Expr/Comparison.php | 31 +- lib/Doctrine/ORM/Query/Expr/Composite.php | 9 +- lib/Doctrine/ORM/Query/Expr/From.php | 17 +- lib/Doctrine/ORM/Query/Expr/Func.php | 21 +- lib/Doctrine/ORM/Query/Expr/GroupBy.php | 15 +- lib/Doctrine/ORM/Query/Expr/Join.php | 53 +- lib/Doctrine/ORM/Query/Expr/Literal.php | 15 +- lib/Doctrine/ORM/Query/Expr/Math.php | 17 +- lib/Doctrine/ORM/Query/Expr/OrderBy.php | 34 +- lib/Doctrine/ORM/Query/Expr/Orx.php | 15 +- lib/Doctrine/ORM/Query/Expr/Select.php | 17 +- lib/Doctrine/ORM/Query/Filter/SQLFilter.php | 27 +- lib/Doctrine/ORM/Query/FilterCollection.php | 68 +- lib/Doctrine/ORM/Query/Lexer.php | 240 +++--- lib/Doctrine/ORM/Query/Parameter.php | 7 +- .../ORM/Query/ParameterTypeInferer.php | 17 +- lib/Doctrine/ORM/Query/Parser.php | 602 ++++++++------ lib/Doctrine/ORM/Query/ParserResult.php | 26 +- lib/Doctrine/ORM/Query/Printer.php | 8 +- lib/Doctrine/ORM/Query/QueryException.php | 66 +- .../ORM/Query/QueryExpressionVisitor.php | 62 +- lib/Doctrine/ORM/Query/ResultSetMapping.php | 36 +- .../ORM/Query/ResultSetMappingBuilder.php | 121 ++- lib/Doctrine/ORM/Query/SqlWalker.php | 413 +++++----- lib/Doctrine/ORM/Query/TreeWalker.php | 20 +- lib/Doctrine/ORM/Query/TreeWalkerAdapter.php | 21 +- lib/Doctrine/ORM/Query/TreeWalkerChain.php | 19 +- .../ORM/Query/TreeWalkerChainIterator.php | 35 +- lib/Doctrine/ORM/QueryBuilder.php | 194 +++-- .../Repository/DefaultRepositoryFactory.php | 10 +- .../ORM/Repository/RepositoryFactory.php | 8 +- .../Tools/AttachEntityListenersListener.php | 18 +- .../ClearCache/CollectionRegionCommand.php | 32 +- .../ClearCache/EntityRegionCommand.php | 24 +- .../Command/ClearCache/MetadataCommand.php | 24 +- .../Command/ClearCache/QueryCommand.php | 25 +- .../Command/ClearCache/QueryRegionCommand.php | 18 +- .../Command/ClearCache/ResultCommand.php | 24 +- .../Command/ConvertDoctrine1SchemaCommand.php | 77 +- .../Console/Command/ConvertMappingCommand.php | 30 +- .../EnsureProductionSettingsCommand.php | 7 +- .../Command/GenerateEntitiesCommand.php | 27 +- .../Command/GenerateProxiesCommand.php | 28 +- .../Command/GenerateRepositoriesCommand.php | 26 +- .../ORM/Tools/Console/Command/InfoCommand.php | 24 +- .../Command/MappingDescribeCommand.php | 71 +- .../Tools/Console/Command/RunDqlCommand.php | 39 +- .../Command/SchemaTool/AbstractCommand.php | 18 +- .../Command/SchemaTool/CreateCommand.php | 10 +- .../Command/SchemaTool/DropCommand.php | 14 +- .../Command/SchemaTool/UpdateCommand.php | 21 +- .../Console/Command/ValidateSchemaCommand.php | 15 +- .../ORM/Tools/Console/ConsoleRunner.php | 30 +- .../Console/Helper/EntityManagerHelper.php | 11 +- .../ORM/Tools/Console/MetadataFilter.php | 37 +- .../ORM/Tools/ConvertDoctrine1Schema.php | 127 +-- .../ORM/Tools/DebugUnitOfWorkListener.php | 83 +- .../DisconnectedClassMetadataFactory.php | 7 +- lib/Doctrine/ORM/Tools/EntityGenerator.php | 504 ++++++------ .../ORM/Tools/EntityRepositoryGenerator.php | 43 +- .../Tools/Event/GenerateSchemaEventArgs.php | 18 +- .../Event/GenerateSchemaTableEventArgs.php | 28 +- .../Tools/Export/ClassMetadataExporter.php | 18 +- .../Tools/Export/Driver/AbstractExporter.php | 50 +- .../Export/Driver/AnnotationExporter.php | 26 +- .../ORM/Tools/Export/Driver/PhpExporter.php | 56 +- .../ORM/Tools/Export/Driver/XmlExporter.php | 61 +- .../ORM/Tools/Export/Driver/YamlExporter.php | 47 +- .../ORM/Tools/Export/ExportException.php | 3 +- .../Tools/Pagination/CountOutputWalker.php | 60 +- .../ORM/Tools/Pagination/CountWalker.php | 42 +- .../Pagination/LimitSubqueryOutputWalker.php | 188 ++--- .../Tools/Pagination/LimitSubqueryWalker.php | 49 +- .../ORM/Tools/Pagination/Paginator.php | 50 +- .../Pagination/RowNumberOverFunction.php | 22 +- .../ORM/Tools/Pagination/WhereInWalker.php | 58 +- .../ORM/Tools/ResolveTargetEntityListener.php | 39 +- lib/Doctrine/ORM/Tools/SchemaTool.php | 218 ++--- lib/Doctrine/ORM/Tools/SchemaValidator.php | 168 ++-- lib/Doctrine/ORM/Tools/Setup.php | 74 +- lib/Doctrine/ORM/Tools/ToolEvents.php | 9 +- lib/Doctrine/ORM/Tools/ToolsException.php | 7 +- .../ORM/TransactionRequiredException.php | 7 +- .../ORM/UnexpectedResultException.php | 4 +- lib/Doctrine/ORM/UnitOfWork.php | 623 +++++++------- .../HierarchyDiscriminatorResolver.php | 9 +- .../ORM/Utility/IdentifierFlattener.php | 20 +- lib/Doctrine/ORM/Utility/PersisterHelper.php | 27 +- lib/Doctrine/ORM/Version.php | 17 +- .../UnitOfWorkComputeChangesBench.php | 30 +- .../Performance/EntityManagerFactory.php | 5 +- ...etchJoinArrayHydrationPerformanceBench.php | 27 +- ...oinFullObjectHydrationPerformanceBench.php | 27 +- ...PartialObjectHydrationPerformanceBench.php | 27 +- .../Hydration/SimpleHydrationBench.php | 14 +- .../SimpleInsertPerformanceBench.php | 22 +- ...pleQueryArrayHydrationPerformanceBench.php | 24 +- ...eryFullObjectHydrationPerformanceBench.php | 28 +- ...PartialObjectHydrationPerformanceBench.php | 23 +- ...leQueryScalarHydrationPerformanceBench.php | 24 +- ...leInheritanceHydrationPerformanceBench.php | 28 +- ...TableInheritanceInsertPerformanceBench.php | 30 +- .../ProxyInitializationTimeBench.php | 29 +- .../ProxyInstantiationTimeBench.php | 13 +- .../Performance/Mock/NonLoadingPersister.php | 7 +- .../Mock/NonProxyLoadingEntityManager.php | 8 +- .../Mock/NonProxyLoadingUnitOfWork.php | 7 +- .../QueryBoundParameterProcessingBench.php | 7 +- .../Doctrine/Tests/DbalFunctionalTestCase.php | 22 +- tests/Doctrine/Tests/DbalTestCase.php | 2 + .../Tests/DbalTypes/CustomIdObject.php | 16 +- .../Tests/DbalTypes/CustomIdObjectType.php | 8 +- .../DbalTypes/NegativeToPositiveType.php | 6 +- tests/Doctrine/Tests/DbalTypes/Rot13Type.php | 4 + .../Tests/DbalTypes/UpperCaseStringType.php | 6 +- tests/Doctrine/Tests/DoctrineTestCase.php | 2 + .../EventListener/CacheMetadataListener.php | 34 +- tests/Doctrine/Tests/IterableTester.php | 5 +- .../Mapping/UnderscoreNamingStrategyTest.php | 3 +- tests/Doctrine/Tests/Mocks/CacheEntryMock.php | 6 +- tests/Doctrine/Tests/Mocks/CacheKeyMock.php | 4 +- .../Doctrine/Tests/Mocks/CacheRegionMock.php | 14 +- .../Tests/Mocks/ClassMetadataMock.php | 2 + .../Tests/Mocks/ConcurrentRegionMock.php | 44 +- tests/Doctrine/Tests/Mocks/ConnectionMock.php | 93 +-- .../Tests/Mocks/DatabasePlatformMock.php | 37 +- .../Tests/Mocks/DriverConnectionMock.php | 20 +- tests/Doctrine/Tests/Mocks/DriverMock.php | 34 +- .../Tests/Mocks/EntityManagerMock.php | 41 +- .../Tests/Mocks/EntityPersisterMock.php | 81 +- .../Tests/Mocks/HydratorMockStatement.php | 33 +- .../Tests/Mocks/MetadataDriverMock.php | 2 + tests/Doctrine/Tests/Mocks/MockTreeWalker.php | 2 + .../Tests/Mocks/SchemaManagerMock.php | 5 +- tests/Doctrine/Tests/Mocks/SequenceMock.php | 11 +- .../Tests/Mocks/StatementArrayMock.php | 18 +- tests/Doctrine/Tests/Mocks/StatementMock.php | 14 +- tests/Doctrine/Tests/Mocks/TaskMock.php | 25 +- .../Tests/Mocks/TimestampRegionMock.php | 6 +- tests/Doctrine/Tests/Mocks/UnitOfWorkMock.php | 24 +- .../Doctrine/Tests/Models/CMS/CmsAddress.php | 163 ++-- .../Tests/Models/CMS/CmsAddressDTO.php | 8 +- .../Tests/Models/CMS/CmsAddressListener.php | 32 +- .../Doctrine/Tests/Models/CMS/CmsArticle.php | 24 +- .../Doctrine/Tests/Models/CMS/CmsComment.php | 18 +- tests/Doctrine/Tests/Models/CMS/CmsEmail.php | 25 +- .../Doctrine/Tests/Models/CMS/CmsEmployee.php | 17 +- tests/Doctrine/Tests/Models/CMS/CmsGroup.php | 24 +- .../Tests/Models/CMS/CmsPhonenumber.php | 12 +- tests/Doctrine/Tests/Models/CMS/CmsTag.php | 23 +- tests/Doctrine/Tests/Models/CMS/CmsUser.php | 392 ++++----- .../Doctrine/Tests/Models/CMS/CmsUserDTO.php | 10 +- tests/Doctrine/Tests/Models/Cache/Action.php | 12 +- tests/Doctrine/Tests/Models/Cache/Address.php | 6 +- .../Tests/Models/Cache/Attraction.php | 16 +- .../Models/Cache/AttractionContactInfo.php | 8 +- .../Tests/Models/Cache/AttractionInfo.php | 6 +- .../Models/Cache/AttractionLocationInfo.php | 8 +- tests/Doctrine/Tests/Models/Cache/Bar.php | 2 + tests/Doctrine/Tests/Models/Cache/Beach.php | 2 + tests/Doctrine/Tests/Models/Cache/City.php | 41 +- tests/Doctrine/Tests/Models/Cache/Client.php | 6 +- .../Tests/Models/Cache/ComplexAction.php | 28 +- tests/Doctrine/Tests/Models/Cache/Country.php | 10 +- tests/Doctrine/Tests/Models/Cache/Flight.php | 20 +- tests/Doctrine/Tests/Models/Cache/Login.php | 11 +- tests/Doctrine/Tests/Models/Cache/Person.php | 10 +- .../Tests/Models/Cache/Restaurant.php | 2 + tests/Doctrine/Tests/Models/Cache/State.php | 24 +- tests/Doctrine/Tests/Models/Cache/Token.php | 42 +- tests/Doctrine/Tests/Models/Cache/Travel.php | 45 +- .../Doctrine/Tests/Models/Cache/Traveler.php | 45 +- .../Tests/Models/Cache/TravelerProfile.php | 12 +- .../Models/Cache/TravelerProfileInfo.php | 12 +- .../Tests/Models/Company/CompanyAuction.php | 11 +- .../Tests/Models/Company/CompanyCar.php | 15 +- .../Tests/Models/Company/CompanyContract.php | 73 +- .../Company/CompanyContractListener.php | 20 +- .../Tests/Models/Company/CompanyEmployee.php | 40 +- .../Tests/Models/Company/CompanyEvent.php | 33 +- .../Models/Company/CompanyFixContract.php | 14 +- .../Models/Company/CompanyFlexContract.php | 30 +- .../Company/CompanyFlexUltraContract.php | 37 +- .../CompanyFlexUltraContractListener.php | 8 +- .../Tests/Models/Company/CompanyManager.php | 22 +- .../Models/Company/CompanyOrganization.php | 26 +- .../Tests/Models/Company/CompanyPerson.php | 96 +-- .../Tests/Models/Company/CompanyRaffle.php | 11 +- .../JoinedChildClass.php | 3 + .../JoinedDerivedChildClass.php | 3 + .../JoinedDerivedIdentityClass.php | 3 + .../JoinedDerivedRootClass.php | 3 + .../JoinedRootClass.php | 3 + .../SingleChildClass.php | 3 + .../SingleRootClass.php | 3 + .../CustomType/CustomIdObjectTypeChild.php | 11 +- .../CustomType/CustomIdObjectTypeParent.php | 12 +- .../Models/CustomType/CustomTypeChild.php | 6 +- .../Models/CustomType/CustomTypeParent.php | 24 +- .../Models/CustomType/CustomTypeUpperCase.php | 10 +- .../Models/DDC117/DDC117ApproveChanges.php | 10 +- .../Tests/Models/DDC117/DDC117Article.php | 35 +- .../Models/DDC117/DDC117ArticleDetails.php | 8 +- .../Tests/Models/DDC117/DDC117Editor.php | 20 +- .../Tests/Models/DDC117/DDC117Link.php | 2 + .../Tests/Models/DDC117/DDC117Reference.php | 20 +- .../Tests/Models/DDC117/DDC117Translation.php | 30 +- .../DDC1476EntityWithDefaultFieldType.php | 33 +- .../Tests/Models/DDC1590/DDC1590Entity.php | 22 +- .../Tests/Models/DDC1590/DDC1590User.php | 9 +- .../Tests/Models/DDC1872/DDC1872Bar.php | 6 +- .../DDC1872ExampleEntityWithOverride.php | 4 +- .../DDC1872ExampleEntityWithoutOverride.php | 2 + .../Models/DDC1872/DDC1872ExampleTrait.php | 9 +- .../Tests/Models/DDC2372/DDC2372Address.php | 6 +- .../Tests/Models/DDC2372/DDC2372Admin.php | 2 + .../Tests/Models/DDC2372/DDC2372User.php | 4 +- .../DDC2372/Traits/DDC2372AddressTrait.php | 4 +- .../Models/DDC2504/DDC2504ChildClass.php | 2 + .../Models/DDC2504/DDC2504OtherClass.php | 9 +- .../Tests/Models/DDC2504/DDC2504RootClass.php | 5 +- .../Models/DDC2825/ExplicitSchemaAndTable.php | 2 + .../DDC2825/SchemaAndTableInTableName.php | 2 + .../DDC3231/DDC3231EntityRepository.php | 6 +- .../Tests/Models/DDC3231/DDC3231User1.php | 7 +- .../DDC3231/DDC3231User1NoNamespace.php | 7 +- .../Tests/Models/DDC3231/DDC3231User2.php | 7 +- .../DDC3231/DDC3231User2NoNamespace.php | 7 +- .../Tests/Models/DDC3293/DDC3293Address.php | 2 + .../Tests/Models/DDC3293/DDC3293User.php | 10 +- .../Models/DDC3293/DDC3293UserPrefixed.php | 10 +- .../Tests/Models/DDC3346/DDC3346Article.php | 3 +- .../Tests/Models/DDC3346/DDC3346Author.php | 10 +- .../Tests/Models/DDC3579/DDC3579Admin.php | 9 +- .../Tests/Models/DDC3579/DDC3579Group.php | 32 +- .../Tests/Models/DDC3579/DDC3579User.php | 73 +- .../Tests/Models/DDC3597/DDC3597Image.php | 19 +- .../Tests/Models/DDC3597/DDC3597Media.php | 47 +- .../Tests/Models/DDC3597/DDC3597Root.php | 45 +- .../DDC3597/Embeddable/DDC3597Dimension.php | 37 +- .../Tests/Models/DDC3699/DDC3699Child.php | 2 + .../Tests/Models/DDC3699/DDC3699Parent.php | 2 + .../Models/DDC3699/DDC3699RelationMany.php | 2 + .../Models/DDC3699/DDC3699RelationOne.php | 2 + .../Tests/Models/DDC3711/DDC3711EntityA.php | 32 +- .../Tests/Models/DDC3711/DDC3711EntityB.php | 47 +- .../Tests/Models/DDC3899/DDC3899Contract.php | 2 + .../Models/DDC3899/DDC3899FixContract.php | 2 + .../Models/DDC3899/DDC3899FlexContract.php | 2 + .../Tests/Models/DDC3899/DDC3899User.php | 2 + .../Tests/Models/DDC4006/DDC4006User.php | 6 +- .../Tests/Models/DDC4006/DDC4006UserId.php | 2 + .../Models/DDC5934/DDC5934BaseContract.php | 7 +- .../Tests/Models/DDC5934/DDC5934Contract.php | 6 +- .../Tests/Models/DDC5934/DDC5934Member.php | 6 +- .../Tests/Models/DDC6412/DDC6412File.php | 9 +- .../Models/DDC753/DDC753CustomRepository.php | 9 +- .../Models/DDC753/DDC753DefaultRepository.php | 8 +- .../DDC753EntityWithCustomRepository.php | 4 +- ...DC753EntityWithDefaultCustomRepository.php | 4 +- .../DDC753EntityWithInvalidRepository.php | 4 +- .../Models/DDC753/DDC753InvalidRepository.php | 3 +- .../Models/DDC869/DDC869ChequePayment.php | 12 +- .../Models/DDC869/DDC869CreditCardPayment.php | 12 +- .../Tests/Models/DDC869/DDC869Payment.php | 23 +- .../Models/DDC869/DDC869PaymentRepository.php | 7 +- .../Tests/Models/DDC889/DDC889Class.php | 19 +- .../Tests/Models/DDC889/DDC889Entity.php | 8 +- .../Tests/Models/DDC889/DDC889SuperClass.php | 13 +- .../Tests/Models/DDC964/DDC964Address.php | 81 +- .../Tests/Models/DDC964/DDC964Admin.php | 42 +- .../Tests/Models/DDC964/DDC964Group.php | 32 +- .../Tests/Models/DDC964/DDC964Guest.php | 20 +- .../Tests/Models/DDC964/DDC964User.php | 124 ++- .../DirectoryTree/AbstractContentItem.php | 24 +- .../Tests/Models/DirectoryTree/Directory.php | 8 +- .../Tests/Models/DirectoryTree/File.php | 8 +- .../Tests/Models/ECommerce/ECommerceCart.php | 35 +- .../Models/ECommerce/ECommerceCategory.php | 34 +- .../Models/ECommerce/ECommerceCustomer.php | 36 +- .../Models/ECommerce/ECommerceFeature.php | 27 +- .../Models/ECommerce/ECommerceProduct.php | 47 +- .../Models/ECommerce/ECommerceShipping.php | 9 +- .../Tests/Models/Forum/ForumAdministrator.php | 6 +- .../Tests/Models/Forum/ForumAvatar.php | 2 + .../Tests/Models/Forum/ForumBoard.php | 7 +- .../Tests/Models/Forum/ForumCategory.php | 17 +- .../Tests/Models/Forum/ForumEntry.php | 10 +- .../Doctrine/Tests/Models/Forum/ForumUser.php | 26 +- .../Tests/Models/GH7141/GH7141Article.php | 2 + .../Tests/Models/GH7316/GH7316Article.php | 2 + .../Tests/Models/Generic/BooleanModel.php | 6 +- .../Tests/Models/Generic/DateTimeModel.php | 14 +- .../Tests/Models/Generic/DecimalModel.php | 10 +- .../Models/Generic/NonAlphaColumnsEntity.php | 11 +- .../Models/Generic/SerializationModel.php | 10 +- .../Doctrine/Tests/Models/GeoNames/Admin1.php | 6 +- .../Models/GeoNames/Admin1AlternateName.php | 7 +- tests/Doctrine/Tests/Models/GeoNames/City.php | 7 +- .../Tests/Models/GeoNames/Country.php | 6 +- .../Models/Global/GlobalNamespaceModel.php | 13 +- .../EntityWithArrayDefaultArrayValueM2M.php | 2 + .../Tests/Models/Hydration/SimpleEntity.php | 2 + .../Models/Issue5989/Issue5989Employee.php | 3 +- .../Models/Issue5989/Issue5989Manager.php | 3 +- .../Models/Issue5989/Issue5989Person.php | 2 + .../AnotherChildClass.php | 2 + .../JoinedInheritanceType/ChildClass.php | 2 + .../JoinedInheritanceType/RootClass.php | 2 + .../Tests/Models/Legacy/LegacyArticle.php | 14 +- .../Tests/Models/Legacy/LegacyCar.php | 16 +- .../Tests/Models/Legacy/LegacyUser.php | 45 +- .../Models/Legacy/LegacyUserReference.php | 20 +- .../Models/ManyToManyPersister/ChildClass.php | 7 +- .../ManyToManyPersister/OtherParentClass.php | 5 +- .../ManyToManyPersister/ParentClass.php | 10 +- .../CompositeToOneKeyState.php | 2 + .../Models/MixedToOneIdentity/Country.php | 2 + .../Tests/Models/Navigation/NavCountry.php | 21 +- .../Tests/Models/Navigation/NavPhotos.php | 20 +- .../Models/Navigation/NavPointOfInterest.php | 36 +- .../Tests/Models/Navigation/NavTour.php | 13 +- .../Tests/Models/Navigation/NavUser.php | 7 +- .../Models/NonPublicSchemaJoins/User.php | 4 +- .../Models/NullDefault/NullDefaultColumn.php | 2 + .../OneToOneInverseSideLoad/InverseSide.php | 6 +- .../OneToOneInverseSideLoad/OwningSide.php | 2 - .../OneToOneSingleTableInheritance/Cat.php | 3 +- .../LitterBox.php | 2 + .../OneToOneSingleTableInheritance/Pet.php | 2 + .../Models/OrnementalOrphanRemoval/Person.php | 2 + .../OrnementalOrphanRemoval/PhoneNumber.php | 2 + .../Tests/Models/Pagination/Company.php | 22 +- .../Tests/Models/Pagination/Department.php | 14 +- .../Doctrine/Tests/Models/Pagination/Logo.php | 17 +- .../Doctrine/Tests/Models/Pagination/User.php | 9 +- .../Tests/Models/Pagination/User1.php | 9 +- tests/Doctrine/Tests/Models/Quote/Address.php | 13 +- tests/Doctrine/Tests/Models/Quote/City.php | 6 +- .../Tests/Models/Quote/FullAddress.php | 3 +- tests/Doctrine/Tests/Models/Quote/Group.php | 18 +- .../Tests/Models/Quote/NumericEntity.php | 12 +- tests/Doctrine/Tests/Models/Quote/Phone.php | 4 +- tests/Doctrine/Tests/Models/Quote/User.php | 18 +- .../Models/Reflection/AbstractEmbeddable.php | 2 + .../Reflection/ArrayObjectExtendingClass.php | 2 + .../Reflection/ClassWithMixedProperties.php | 2 + .../Models/Reflection/ConcreteEmbeddable.php | 2 + .../Tests/Models/Reflection/ParentClass.php | 2 + .../Tests/Models/Routing/RoutingLeg.php | 10 +- .../Tests/Models/Routing/RoutingLocation.php | 6 +- .../Tests/Models/Routing/RoutingRoute.php | 2 + .../Models/Routing/RoutingRouteBooking.php | 6 +- .../Tests/Models/StockExchange/Bond.php | 4 +- .../Tests/Models/StockExchange/Market.php | 6 +- .../Tests/Models/StockExchange/Stock.php | 8 +- tests/Doctrine/Tests/Models/Taxi/Car.php | 22 +- tests/Doctrine/Tests/Models/Taxi/Driver.php | 18 +- tests/Doctrine/Tests/Models/Taxi/PaidRide.php | 10 +- tests/Doctrine/Tests/Models/Taxi/Ride.php | 4 +- tests/Doctrine/Tests/Models/Tweet/Tweet.php | 12 +- tests/Doctrine/Tests/Models/Tweet/User.php | 18 +- .../Doctrine/Tests/Models/Tweet/UserList.php | 10 +- .../ValueConversionType/AuxiliaryEntity.php | 2 + .../InversedManyToManyCompositeIdEntity.php | 6 +- ...dManyToManyCompositeIdForeignKeyEntity.php | 6 +- .../InversedManyToManyEntity.php | 6 +- .../InversedManyToManyExtraLazyEntity.php | 2 + .../InversedOneToManyCompositeIdEntity.php | 10 +- ...edOneToManyCompositeIdForeignKeyEntity.php | 10 +- .../InversedOneToManyEntity.php | 10 +- .../InversedOneToManyExtraLazyEntity.php | 2 + .../InversedOneToOneCompositeIdEntity.php | 10 +- ...sedOneToOneCompositeIdForeignKeyEntity.php | 10 +- .../InversedOneToOneEntity.php | 10 +- .../OwningManyToManyCompositeIdEntity.php | 2 + ...gManyToManyCompositeIdForeignKeyEntity.php | 2 + .../OwningManyToManyEntity.php | 2 + .../OwningManyToManyExtraLazyEntity.php | 2 + .../OwningManyToOneCompositeIdEntity.php | 2 + .../OwningManyToOneEntity.php | 2 + .../OwningManyToOneExtraLazyEntity.php | 2 + .../OwningOneToOneCompositeIdEntity.php | 2 + ...ingOneToOneCompositeIdForeignKeyEntity.php | 2 + .../OwningOneToOneEntity.php | 2 + .../Tests/Models/ValueObjects/Name.php | 2 + .../Tests/Models/ValueObjects/Person.php | 2 + .../Models/VersionedManyToOne/Article.php | 10 +- .../Models/VersionedManyToOne/Category.php | 2 + .../VersionedOneToOne/FirstRelatedEntity.php | 8 +- .../VersionedOneToOne/SecondRelatedEntity.php | 8 +- .../Tests/ORM/Cache/AbstractRegionTest.php | 32 +- .../Tests/ORM/Cache/CacheConfigTest.php | 22 +- .../Doctrine/Tests/ORM/Cache/CacheKeyTest.php | 46 +- .../Tests/ORM/Cache/CacheLoggerChainTest.php | 26 +- .../ORM/Cache/DefaultCacheFactoryTest.php | 75 +- .../Tests/ORM/Cache/DefaultCacheTest.php | 111 ++- .../Cache/DefaultCollectionHydratorTest.php | 38 +- .../ORM/Cache/DefaultEntityHydratorTest.php | 127 +-- .../Tests/ORM/Cache/DefaultQueryCacheTest.php | 289 ++++--- .../Tests/ORM/Cache/DefaultRegionTest.php | 31 +- .../Tests/ORM/Cache/FileLockRegionTest.php | 131 +-- .../Tests/ORM/Cache/MultiGetRegionTest.php | 17 +- .../AbstractCollectionPersisterTest.php | 116 ++- ...ReadWriteCachedCollectionPersisterTest.php | 5 +- .../ReadOnlyCachedCollectionPersisterTest.php | 4 +- ...ReadWriteCachedCollectionPersisterTest.php | 106 +-- .../Entity/AbstractEntityPersisterTest.php | 148 ++-- ...rictReadWriteCachedEntityPersisterTest.php | 45 +- .../ReadOnlyCachedEntityPersisterTest.php | 10 +- .../ReadWriteCachedEntityPersisterTest.php | 88 +- .../ORM/Cache/StatisticsCacheLoggerTest.php | 26 +- .../Tests/ORM/CommitOrderCalculatorTest.php | 30 +- .../Doctrine/Tests/ORM/ConfigurationTest.php | 145 ++-- .../Decorator/EntityManagerDecoratorTest.php | 30 +- .../Tests/ORM/Entity/ConstructorTest.php | 9 +- .../Doctrine/Tests/ORM/EntityManagerTest.php | 107 +-- .../Tests/ORM/EntityNotFoundExceptionTest.php | 4 +- .../OnClassMetadataNotFoundEventArgsTest.php | 10 +- .../AbstractManyToManyAssociationTestCase.php | 15 +- .../Functional/AdvancedAssociationTest.php | 564 ++++++------- .../ORM/Functional/AdvancedDqlQueryTest.php | 53 +- .../ORM/Functional/BasicFunctionalTest.php | 732 +++++++++-------- .../ORM/Functional/CascadeRemoveOrderTest.php | 19 +- .../Functional/ClassTableInheritanceTest.php | 93 ++- .../Functional/ClassTableInheritanceTest2.php | 80 +- .../Tests/ORM/Functional/ClearEventTest.php | 10 +- .../Functional/CompositePrimaryKeyTest.php | 54 +- ...ompositePrimaryKeyWithAssociationsTest.php | 20 +- .../ORM/Functional/CustomFunctionsTest.php | 32 +- .../ORM/Functional/CustomIdObjectTypeTest.php | 12 +- .../ORM/Functional/DatabaseDriverTest.php | 101 +-- .../ORM/Functional/DatabaseDriverTestCase.php | 30 +- .../ORM/Functional/DefaultValuesTest.php | 68 +- .../ORM/Functional/DetachedEntityTest.php | 100 +-- .../ORM/Functional/EntityListenersTest.php | 53 +- .../EntityRepositoryCriteriaTest.php | 81 +- .../ORM/Functional/EntityRepositoryTest.php | 324 ++++---- .../Functional/ExtraLazyCollectionTest.php | 99 +-- .../Tests/ORM/Functional/FlushEventTest.php | 43 +- .../Tests/ORM/Functional/GH5988Test.php | 8 +- .../ORM/Functional/HydrationCacheTest.php | 39 +- .../Tests/ORM/Functional/IdentityMapTest.php | 105 ++- .../ORM/Functional/IndexByAssociationTest.php | 80 +- .../JoinedTableCompositeKeyTest.php | 18 +- .../ORM/Functional/LifecycleCallbackTest.php | 203 +++-- .../Functional/Locking/GearmanLockTest.php | 85 +- .../Functional/Locking/LockAgentWorker.php | 52 +- .../Tests/ORM/Functional/Locking/LockTest.php | 84 +- .../ORM/Functional/Locking/OptimisticTest.php | 74 +- .../ManyToManyBasicAssociationTest.php | 165 ++-- ...ManyToManyBidirectionalAssociationTest.php | 44 +- .../ORM/Functional/ManyToManyEventTest.php | 45 +- ...nyToManySelfReferentialAssociationTest.php | 66 +- ...anyToManyUnidirectionalAssociationTest.php | 41 +- .../Functional/ManyToOneOrphanRemovalTest.php | 30 +- .../ORM/Functional/MappedSuperclassTest.php | 10 +- .../Functional/MergeCompositeToOneKeyTest.php | 21 +- .../Tests/ORM/Functional/MergeProxiesTest.php | 39 +- .../Functional/MergeSharedEntitiesTest.php | 38 +- .../MergeVersionedManyToOneTest.php | 6 +- .../Tests/ORM/Functional/NativeQueryTest.php | 285 +++---- .../Tests/ORM/Functional/NewOperatorTest.php | 287 ++++--- .../Tests/ORM/Functional/NotifyPolicyTest.php | 71 +- .../OneToManyBidirectionalAssociationTest.php | 55 +- .../Functional/OneToManyOrphanRemovalTest.php | 26 +- ...neToManySelfReferentialAssociationTest.php | 42 +- ...OneToManyUnidirectionalAssociationTest.php | 61 +- .../OneToOneBidirectionalAssociationTest.php | 54 +- .../Functional/OneToOneEagerLoadingTest.php | 94 ++- ...eToOneInverseSideLoadAfterDqlQueryTest.php | 8 +- .../Functional/OneToOneOrphanRemovalTest.php | 30 +- ...OneToOneSelfReferentialAssociationTest.php | 84 +- .../OneToOneSingleTableInheritanceTest.php | 11 +- .../OneToOneUnidirectionalAssociationTest.php | 43 +- .../ORM/Functional/OrderedCollectionTest.php | 62 +- ...edJoinedTableInheritanceCollectionTest.php | 46 +- .../Tests/ORM/Functional/PaginationTest.php | 377 ++++----- .../PersistentCollectionCriteriaTest.php | 24 +- .../Functional/PersistentCollectionTest.php | 41 +- .../ORM/Functional/PersistentObjectTest.php | 23 +- .../ORM/Functional/PostFlushEventTest.php | 50 +- .../ORM/Functional/PostLoadEventTest.php | 81 +- .../Functional/ProxiesLikeEntitiesTest.php | 46 +- .../Tests/ORM/Functional/QueryCacheTest.php | 44 +- .../ORM/Functional/QueryDqlFunctionTest.php | 126 +-- .../ORM/Functional/QueryIterableTest.php | 6 +- .../Tests/ORM/Functional/QueryTest.php | 451 +++++----- .../Tests/ORM/Functional/ReadOnlyTest.php | 29 +- .../ORM/Functional/ReferenceProxyTest.php | 122 +-- .../Tests/ORM/Functional/ResultCacheTest.php | 87 +- .../Tests/ORM/Functional/SQLFilterTest.php | 451 +++++----- .../SchemaTool/CompanySchemaTest.php | 21 +- .../ORM/Functional/SchemaTool/DBAL483Test.php | 26 +- .../ORM/Functional/SchemaTool/DDC214Test.php | 37 +- .../SchemaTool/MySqlSchemaToolTest.php | 62 +- .../SchemaTool/PostgreSqlSchemaToolTest.php | 121 +-- .../ORM/Functional/SchemaValidatorTest.php | 24 +- .../SecondLevelCacheAbstractTest.php | 103 ++- ...econdLevelCacheCompositePrimaryKeyTest.php | 53 +- ...ompositePrimaryKeyWithAssociationsTest.php | 29 +- .../SecondLevelCacheConcurrentTest.php | 43 +- .../SecondLevelCacheCriteriaTest.php | 9 +- ...econdLevelCacheExtraLazyCollectionTest.php | 18 +- ...condLevelCacheJoinTableInheritanceTest.php | 21 +- .../SecondLevelCacheManyToManyTest.php | 25 +- .../SecondLevelCacheManyToOneTest.php | 20 +- .../SecondLevelCacheOneToManyTest.php | 32 +- .../SecondLevelCacheOneToOneTest.php | 14 +- .../SecondLevelCacheQueryCacheTest.php | 151 ++-- .../SecondLevelCacheRepositoryTest.php | 19 +- ...ndLevelCacheSingleTableInheritanceTest.php | 31 +- .../ORM/Functional/SecondLevelCacheTest.php | 81 +- .../SequenceEmulatedIdentityStrategyTest.php | 23 +- .../ORM/Functional/SequenceGeneratorTest.php | 14 +- .../SingleTableCompositeKeyTest.php | 17 +- .../Functional/SingleTableInheritanceTest.php | 105 +-- .../StandardEntityPersisterTest.php | 21 +- .../ORM/Functional/Ticket/DDC1040Test.php | 48 +- .../ORM/Functional/Ticket/DDC1041Test.php | 6 +- .../ORM/Functional/Ticket/DDC1043Test.php | 18 +- .../ORM/Functional/Ticket/DDC1080Test.php | 108 +-- .../ORM/Functional/Ticket/DDC1113Test.php | 28 +- .../ORM/Functional/Ticket/DDC1129Test.php | 25 +- .../ORM/Functional/Ticket/DDC1151Test.php | 34 +- .../ORM/Functional/Ticket/DDC1163Test.php | 54 +- .../ORM/Functional/Ticket/DDC117Test.php | 173 ++-- .../ORM/Functional/Ticket/DDC1181Test.php | 21 +- .../ORM/Functional/Ticket/DDC1193Test.php | 38 +- .../ORM/Functional/Ticket/DDC1209Test.php | 26 +- .../ORM/Functional/Ticket/DDC1225Test.php | 30 +- .../ORM/Functional/Ticket/DDC1228Test.php | 50 +- .../ORM/Functional/Ticket/DDC1238Test.php | 33 +- .../ORM/Functional/Ticket/DDC1250Test.php | 41 +- .../ORM/Functional/Ticket/DDC1276Test.php | 26 +- .../ORM/Functional/Ticket/DDC1300Test.php | 37 +- .../ORM/Functional/Ticket/DDC1301Test.php | 106 +-- .../ORM/Functional/Ticket/DDC1306Test.php | 33 +- .../ORM/Functional/Ticket/DDC1335Test.php | 86 +- .../ORM/Functional/Ticket/DDC1360Test.php | 21 +- .../ORM/Functional/Ticket/DDC1383Test.php | 115 +-- .../ORM/Functional/Ticket/DDC1392Test.php | 28 +- .../ORM/Functional/Ticket/DDC1400Test.php | 58 +- .../ORM/Functional/Ticket/DDC1404Test.php | 65 +- .../ORM/Functional/Ticket/DDC142Test.php | 33 +- .../ORM/Functional/Ticket/DDC1430Test.php | 126 +-- .../ORM/Functional/Ticket/DDC1436Test.php | 24 +- .../ORM/Functional/Ticket/DDC144Test.php | 14 +- .../ORM/Functional/Ticket/DDC1452Test.php | 71 +- .../ORM/Functional/Ticket/DDC1454Test.php | 16 +- .../ORM/Functional/Ticket/DDC1458Test.php | 32 +- .../ORM/Functional/Ticket/DDC1461Test.php | 33 +- .../ORM/Functional/Ticket/DDC1509Test.php | 51 +- .../ORM/Functional/Ticket/DDC1514Test.php | 48 +- .../ORM/Functional/Ticket/DDC1515Test.php | 27 +- .../ORM/Functional/Ticket/DDC1526Test.php | 34 +- .../ORM/Functional/Ticket/DDC1545Test.php | 41 +- .../ORM/Functional/Ticket/DDC1548Test.php | 26 +- .../ORM/Functional/Ticket/DDC1594Test.php | 21 +- .../ORM/Functional/Ticket/DDC1595Test.php | 27 +- .../ORM/Functional/Ticket/DDC163Test.php | 21 +- .../ORM/Functional/Ticket/DDC1643Test.php | 54 +- .../ORM/Functional/Ticket/DDC1654Test.php | 45 +- .../ORM/Functional/Ticket/DDC1655Test.php | 49 +- .../ORM/Functional/Ticket/DDC1666Test.php | 23 +- .../ORM/Functional/Ticket/DDC1685Test.php | 32 +- .../ORM/Functional/Ticket/DDC168Test.php | 33 +- .../ORM/Functional/Ticket/DDC1690Test.php | 76 +- .../ORM/Functional/Ticket/DDC1695Test.php | 33 +- .../ORM/Functional/Ticket/DDC1707Test.php | 20 +- .../ORM/Functional/Ticket/DDC1719Test.php | 37 +- .../ORM/Functional/Ticket/DDC1734Test.php | 28 +- .../ORM/Functional/Ticket/DDC1757Test.php | 27 +- .../ORM/Functional/Ticket/DDC1778Test.php | 27 +- .../ORM/Functional/Ticket/DDC1787Test.php | 26 +- .../ORM/Functional/Ticket/DDC1843Test.php | 37 +- .../ORM/Functional/Ticket/DDC1884Test.php | 29 +- .../ORM/Functional/Ticket/DDC1885Test.php | 55 +- .../ORM/Functional/Ticket/DDC1918Test.php | 28 +- .../ORM/Functional/Ticket/DDC1925Test.php | 55 +- .../ORM/Functional/Ticket/DDC192Test.php | 17 +- .../ORM/Functional/Ticket/DDC1995Test.php | 31 +- .../ORM/Functional/Ticket/DDC1998Test.php | 32 +- .../ORM/Functional/Ticket/DDC199Test.php | 40 +- .../ORM/Functional/Ticket/DDC2012Test.php | 37 +- .../ORM/Functional/Ticket/DDC2074Test.php | 7 +- .../ORM/Functional/Ticket/DDC2084Test.php | 27 +- .../ORM/Functional/Ticket/DDC2090Test.php | 45 +- .../ORM/Functional/Ticket/DDC2106Test.php | 17 +- .../ORM/Functional/Ticket/DDC211Test.php | 76 +- .../ORM/Functional/Ticket/DDC2138Test.php | 97 +-- .../ORM/Functional/Ticket/DDC2175Test.php | 28 +- .../ORM/Functional/Ticket/DDC2182Test.php | 22 +- .../ORM/Functional/Ticket/DDC2214Test.php | 28 +- .../ORM/Functional/Ticket/DDC2224Test.php | 25 +- .../ORM/Functional/Ticket/DDC2230Test.php | 30 +- .../ORM/Functional/Ticket/DDC2231Test.php | 23 +- .../ORM/Functional/Ticket/DDC2252Test.php | 48 +- .../ORM/Functional/Ticket/DDC2256Test.php | 33 +- .../ORM/Functional/Ticket/DDC2306Test.php | 45 +- .../ORM/Functional/Ticket/DDC2346Test.php | 42 +- .../ORM/Functional/Ticket/DDC2350Test.php | 20 +- .../ORM/Functional/Ticket/DDC2359Test.php | 17 +- .../ORM/Functional/Ticket/DDC237Test.php | 40 +- .../ORM/Functional/Ticket/DDC2387Test.php | 11 +- .../ORM/Functional/Ticket/DDC2409Test.php | 27 +- .../ORM/Functional/Ticket/DDC2415Test.php | 37 +- .../ORM/Functional/Ticket/DDC2494Test.php | 33 +- .../ORM/Functional/Ticket/DDC2519Test.php | 39 +- .../ORM/Functional/Ticket/DDC2575Test.php | 51 +- .../ORM/Functional/Ticket/DDC2579Test.php | 30 +- .../ORM/Functional/Ticket/DDC258Test.php | 68 +- .../ORM/Functional/Ticket/DDC2602Test.php | 85 +- .../ORM/Functional/Ticket/DDC2645Test.php | 15 +- .../ORM/Functional/Ticket/DDC2655Test.php | 9 +- .../ORM/Functional/Ticket/DDC2660Test.php | 45 +- .../ORM/Functional/Ticket/DDC2692Test.php | 35 +- .../ORM/Functional/Ticket/DDC2759Test.php | 26 +- .../ORM/Functional/Ticket/DDC2775Test.php | 44 +- .../ORM/Functional/Ticket/DDC2780Test.php | 21 +- .../ORM/Functional/Ticket/DDC2790Test.php | 39 +- .../ORM/Functional/Ticket/DDC279Test.php | 35 +- .../ORM/Functional/Ticket/DDC2825Test.php | 31 +- .../ORM/Functional/Ticket/DDC2862Test.php | 66 +- .../ORM/Functional/Ticket/DDC2895Test.php | 50 +- .../ORM/Functional/Ticket/DDC2931Test.php | 22 +- .../ORM/Functional/Ticket/DDC2943Test.php | 28 +- .../ORM/Functional/Ticket/DDC2984Test.php | 77 +- .../ORM/Functional/Ticket/DDC2996Test.php | 46 +- .../ORM/Functional/Ticket/DDC3033Test.php | 35 +- .../ORM/Functional/Ticket/DDC3042Test.php | 10 +- .../ORM/Functional/Ticket/DDC3068Test.php | 21 +- .../ORM/Functional/Ticket/DDC309Test.php | 10 +- .../ORM/Functional/Ticket/DDC3103Test.php | 10 +- .../ORM/Functional/Ticket/DDC3123Test.php | 15 +- .../ORM/Functional/Ticket/DDC3160Test.php | 25 +- .../ORM/Functional/Ticket/DDC3170Test.php | 15 +- .../ORM/Functional/Ticket/DDC3192Test.php | 34 +- .../ORM/Functional/Ticket/DDC3223Test.php | 18 +- .../ORM/Functional/Ticket/DDC3300Test.php | 9 +- .../ORM/Functional/Ticket/DDC3303Test.php | 7 +- .../ORM/Functional/Ticket/DDC331Test.php | 14 +- .../ORM/Functional/Ticket/DDC3330Test.php | 45 +- .../ORM/Functional/Ticket/DDC3346Test.php | 23 +- .../ORM/Functional/Ticket/DDC345Test.php | 42 +- .../ORM/Functional/Ticket/DDC353Test.php | 39 +- .../ORM/Functional/Ticket/DDC3582Test.php | 24 +- .../ORM/Functional/Ticket/DDC3597Test.php | 10 +- .../ORM/Functional/Ticket/DDC3634Test.php | 38 +- .../ORM/Functional/Ticket/DDC3644Test.php | 44 +- .../ORM/Functional/Ticket/DDC3699Test.php | 30 +- .../ORM/Functional/Ticket/DDC3711Test.php | 15 +- .../ORM/Functional/Ticket/DDC3719Test.php | 15 +- .../ORM/Functional/Ticket/DDC371Test.php | 34 +- .../ORM/Functional/Ticket/DDC3785Test.php | 26 +- .../ORM/Functional/Ticket/DDC381Test.php | 28 +- .../ORM/Functional/Ticket/DDC3967Test.php | 14 +- .../ORM/Functional/Ticket/DDC4003Test.php | 13 +- .../ORM/Functional/Ticket/DDC4024Test.php | 9 +- .../ORM/Functional/Ticket/DDC422Test.php | 39 +- .../ORM/Functional/Ticket/DDC425Test.php | 19 +- .../ORM/Functional/Ticket/DDC440Test.php | 58 +- .../ORM/Functional/Ticket/DDC444Test.php | 32 +- .../ORM/Functional/Ticket/DDC448Test.php | 16 +- .../ORM/Functional/Ticket/DDC493Test.php | 29 +- .../ORM/Functional/Ticket/DDC501Test.php | 43 +- .../ORM/Functional/Ticket/DDC512Test.php | 27 +- .../ORM/Functional/Ticket/DDC513Test.php | 25 +- .../ORM/Functional/Ticket/DDC518Test.php | 27 +- .../ORM/Functional/Ticket/DDC522Test.php | 34 +- .../ORM/Functional/Ticket/DDC531Test.php | 24 +- .../ORM/Functional/Ticket/DDC5684Test.php | 15 +- .../ORM/Functional/Ticket/DDC588Test.php | 14 +- .../ORM/Functional/Ticket/DDC599Test.php | 46 +- .../ORM/Functional/Ticket/DDC618Test.php | 104 +-- .../ORM/Functional/Ticket/DDC6303Test.php | 22 +- .../ORM/Functional/Ticket/DDC633Test.php | 47 +- .../ORM/Functional/Ticket/DDC6460Test.php | 23 +- .../ORM/Functional/Ticket/DDC656Test.php | 43 +- .../ORM/Functional/Ticket/DDC657Test.php | 67 +- .../ORM/Functional/Ticket/DDC698Test.php | 105 ++- .../ORM/Functional/Ticket/DDC719Test.php | 158 ++-- .../ORM/Functional/Ticket/DDC729Test.php | 68 +- .../ORM/Functional/Ticket/DDC735Test.php | 39 +- .../ORM/Functional/Ticket/DDC736Test.php | 50 +- .../ORM/Functional/Ticket/DDC742Test.php | 41 +- .../ORM/Functional/Ticket/DDC748Test.php | 45 +- .../ORM/Functional/Ticket/DDC758Test.php | 125 +-- .../ORM/Functional/Ticket/DDC767Test.php | 41 +- .../ORM/Functional/Ticket/DDC7969Test.php | 6 +- .../ORM/Functional/Ticket/DDC809Test.php | 21 +- .../ORM/Functional/Ticket/DDC812Test.php | 26 +- .../ORM/Functional/Ticket/DDC832Test.php | 53 +- .../ORM/Functional/Ticket/DDC837Test.php | 94 +-- .../ORM/Functional/Ticket/DDC849Test.php | 35 +- .../ORM/Functional/Ticket/DDC881Test.php | 78 +- .../ORM/Functional/Ticket/DDC933Test.php | 28 +- .../ORM/Functional/Ticket/DDC949Test.php | 20 +- .../ORM/Functional/Ticket/DDC960Test.php | 26 +- .../ORM/Functional/Ticket/DDC992Test.php | 63 +- .../ORM/Functional/Ticket/GH2947Test.php | 10 +- .../ORM/Functional/Ticket/GH5562Test.php | 28 +- .../ORM/Functional/Ticket/GH5762Test.php | 44 +- .../ORM/Functional/Ticket/GH5804Test.php | 14 +- .../ORM/Functional/Ticket/GH5887Test.php | 74 +- .../ORM/Functional/Ticket/GH6029Test.php | 17 +- .../ORM/Functional/Ticket/GH6141Test.php | 67 +- .../ORM/Functional/Ticket/GH6217Test.php | 15 +- .../ORM/Functional/Ticket/GH6362Test.php | 29 +- .../ORM/Functional/Ticket/GH6402Test.php | 24 +- .../ORM/Functional/Ticket/GH6464Test.php | 9 +- .../ORM/Functional/Ticket/GH6531Test.php | 17 +- .../ORM/Functional/Ticket/GH6682Test.php | 4 +- .../ORM/Functional/Ticket/GH6699Test.php | 8 +- .../ORM/Functional/Ticket/GH6740Test.php | 32 +- .../ORM/Functional/Ticket/GH6937Test.php | 13 +- .../ORM/Functional/Ticket/GH7012Test.php | 10 +- .../ORM/Functional/Ticket/GH7062Test.php | 31 +- .../ORM/Functional/Ticket/GH7067Test.php | 25 +- .../ORM/Functional/Ticket/GH7068Test.php | 12 +- .../ORM/Functional/Ticket/GH7079Test.php | 13 +- .../ORM/Functional/Ticket/GH7259Test.php | 31 +- .../ORM/Functional/Ticket/GH7286Test.php | 15 +- .../ORM/Functional/Ticket/GH7366Test.php | 11 +- .../Ticket/GH7496WithToIterableTest.php | 4 +- .../ORM/Functional/Ticket/GH7505Test.php | 13 +- .../ORM/Functional/Ticket/GH7629Test.php | 7 +- .../ORM/Functional/Ticket/GH7684Test.php | 2 +- .../ORM/Functional/Ticket/GH7735Test.php | 21 +- .../ORM/Functional/Ticket/GH7737Test.php | 4 +- .../ORM/Functional/Ticket/GH7761Test.php | 15 +- .../ORM/Functional/Ticket/GH7767Test.php | 11 +- .../ORM/Functional/Ticket/GH7820Test.php | 23 +- .../ORM/Functional/Ticket/GH7829Test.php | 6 +- .../ORM/Functional/Ticket/GH7836Test.php | 13 +- .../ORM/Functional/Ticket/GH7864Test.php | 7 +- .../ORM/Functional/Ticket/GH7869Test.php | 2 +- .../ORM/Functional/Ticket/GH7875Test.php | 19 +- .../ORM/Functional/Ticket/GH7941Test.php | 5 +- .../ORM/Functional/Ticket/GH8055Test.php | 7 +- .../ORM/Functional/Ticket/GH8061Test.php | 13 +- .../ORM/Functional/Ticket/Issue5989Test.php | 17 +- .../ORM/Functional/Ticket/Ticket2481Test.php | 18 +- .../Ticket4646InstanceOfAbstractTest.php | 8 +- .../Ticket4646InstanceOfMultiLevelTest.php | 8 +- .../Ticket4646InstanceOfParametricTest.php | 6 +- .../Ticket/Ticket4646InstanceOfTest.php | 8 +- ...46InstanceOfWithMultipleParametersTest.php | 8 +- .../Tests/ORM/Functional/Ticket/Ticket69.php | 262 +++--- .../Tests/ORM/Functional/TypeTest.php | 87 +- .../Tests/ORM/Functional/TypeValueSqlTest.php | 45 +- .../ORM/Functional/UUIDGeneratorTest.php | 17 +- .../Functional/UnitOfWorkLifecycleTest.php | 38 +- .../ManyToManyCompositeIdForeignKeyTest.php | 28 +- .../ManyToManyCompositeIdTest.php | 22 +- .../ManyToManyExtraLazyTest.php | 30 +- .../ValueConversionType/ManyToManyTest.php | 22 +- .../OneToManyCompositeIdForeignKeyTest.php | 28 +- .../OneToManyCompositeIdTest.php | 24 +- .../OneToManyExtraLazyTest.php | 22 +- .../ValueConversionType/OneToManyTest.php | 22 +- .../OneToOneCompositeIdForeignKeyTest.php | 30 +- .../OneToOneCompositeIdTest.php | 26 +- .../ValueConversionType/OneToOneTest.php | 24 +- .../Tests/ORM/Functional/ValueObjectsTest.php | 29 +- .../ORM/Functional/VersionedOneToOneTest.php | 18 +- .../ORM/Hydration/AbstractHydratorTest.php | 27 +- .../Tests/ORM/Hydration/ArrayHydratorTest.php | 223 ++--- .../ORM/Hydration/CustomHydratorTest.php | 6 +- .../Tests/ORM/Hydration/HydrationTestCase.php | 10 +- .../ORM/Hydration/ObjectHydratorTest.php | 303 ++++--- .../ORM/Hydration/ResultSetMappingTest.php | 179 ++-- .../ORM/Hydration/ScalarHydratorTest.php | 27 +- .../Hydration/SimpleObjectHydratorTest.php | 69 +- .../Hydration/SingleScalarHydratorTest.php | 29 +- .../Tests/ORM/Id/AssignedGeneratorTest.php | 28 +- .../Tests/ORM/Id/SequenceGeneratorTest.php | 28 +- .../Internal/HydrationCompleteHandlerTest.php | 68 +- .../Tests/ORM/LazyCriteriaCollectionTest.php | 36 +- .../ORM/Mapping/AbstractMappingDriverTest.php | 728 ++++++++--------- .../ORM/Mapping/AnnotationDriverTest.php | 34 +- .../ORM/Mapping/AnsiQuoteStrategyTest.php | 99 +-- .../Mapping/BasicInheritanceMappingTest.php | 73 +- .../ORM/Mapping/ClassMetadataBuilderTest.php | 742 +++++++++-------- .../ORM/Mapping/ClassMetadataFactoryTest.php | 169 ++-- .../Mapping/ClassMetadataLoadEventTest.php | 18 +- .../Tests/ORM/Mapping/ClassMetadataTest.php | 576 ++++++------- .../ORM/Mapping/DefaultQuoteStrategyTest.php | 10 +- .../Mapping/EntityListenerResolverTest.php | 37 +- .../Tests/ORM/Mapping/FieldBuilderTest.php | 4 +- .../JoinColumnClassNamingStrategy.php | 4 + .../Tests/ORM/Mapping/NamingStrategyTest.php | 35 +- .../ORM/Mapping/PHPMappingDriverTest.php | 8 +- .../Tests/ORM/Mapping/QuoteStrategyTest.php | 129 ++- .../ReflectionPropertiesGetterTest.php | 25 +- .../ReflectionEmbeddedPropertyTest.php | 33 +- .../Mapping/StaticPHPMappingDriverTest.php | 10 +- .../Mapping/Symfony/AbstractDriverTest.php | 45 +- .../ORM/Mapping/Symfony/XmlDriverTest.php | 10 +- .../ORM/Mapping/Symfony/YamlDriverTest.php | 6 +- .../ORM/Mapping/XmlMappingDriverTest.php | 67 +- .../ORM/Mapping/YamlMappingDriverTest.php | 16 +- .../Doctrine.Tests.Models.CMS.CmsAddress.php | 108 ++- .../php/Doctrine.Tests.Models.CMS.CmsUser.php | 292 ++++--- .../php/Doctrine.Tests.Models.Cache.City.php | 58 +- ...e.Tests.Models.Company.CompanyContract.php | 43 +- ...ests.Models.Company.CompanyFixContract.php | 8 +- ...sts.Models.Company.CompanyFlexContract.php | 14 +- ...odels.Company.CompanyFlexUltraContract.php | 30 +- ...ine.Tests.Models.Company.CompanyPerson.php | 52 +- ...1476.DDC1476EntityWithDefaultFieldType.php | 10 +- ....Models.DDC2825.ExplicitSchemaAndTable.php | 12 +- ...dels.DDC2825.SchemaAndTableInTableName.php | 12 +- ...rine.Tests.Models.DDC3579.DDC3579Admin.php | 7 +- ...trine.Tests.Models.DDC3579.DDC3579User.php | 28 +- ...sts.Models.DDC5934.DDC5934BaseContract.php | 10 +- ...e.Tests.Models.DDC5934.DDC5934Contract.php | 2 + ...ests.Models.DDC869.DDC869ChequePayment.php | 7 +- ....Models.DDC869.DDC869CreditCardPayment.php | 7 +- ...rine.Tests.Models.DDC869.DDC869Payment.php | 14 +- ...ctrine.Tests.Models.DDC889.DDC889Class.php | 10 +- ...trine.Tests.Models.DDC889.DDC889Entity.php | 2 +- ...e.Tests.Models.DDC889.DDC889SuperClass.php | 6 +- ...ctrine.Tests.Models.DDC964.DDC964Admin.php | 40 +- ...ctrine.Tests.Models.DDC964.DDC964Guest.php | 17 +- ...octrine.Tests.Models.DDC964.DDC964User.php | 68 +- .../php/Doctrine.Tests.ORM.Mapping.Animal.php | 36 +- .../Doctrine.Tests.ORM.Mapping.Comment.php | 24 +- ...ctrine.Tests.ORM.Mapping.DDC1170Entity.php | 12 +- ...octrine.Tests.ORM.Mapping.DDC807Entity.php | 10 +- .../php/Doctrine.Tests.ORM.Mapping.PHPSLC.php | 10 +- .../php/Doctrine.Tests.ORM.Mapping.User.php | 175 ++-- .../ORM/ORMInvalidArgumentExceptionTest.php | 46 +- .../ORM/Performance/SecondLevelCacheTest.php | 71 +- .../Tests/ORM/PersistentCollectionTest.php | 96 +-- ...tyPersisterCompositeTypeParametersTest.php | 31 +- ...sicEntityPersisterCompositeTypeSqlTest.php | 28 +- .../BasicEntityPersisterTypeValueSqlTest.php | 54 +- .../JoinedSubclassPersisterTest.php | 20 +- .../Persisters/ManyToManyPersisterTest.php | 9 +- .../Tests/ORM/Proxy/ProxyFactoryTest.php | 63 +- .../ORM/Query/CustomTreeWalkersJoinTest.php | 27 +- .../Tests/ORM/Query/CustomTreeWalkersTest.php | 70 +- .../ORM/Query/DeleteSqlGenerationTest.php | 125 ++- tests/Doctrine/Tests/ORM/Query/ExprTest.php | 140 ++-- .../Tests/ORM/Query/FilterCollectionTest.php | 21 +- .../ORM/Query/LanguageRecognitionTest.php | 269 +++--- tests/Doctrine/Tests/ORM/Query/LexerTest.php | 62 +- .../ORM/Query/ParameterTypeInfererTest.php | 25 +- .../Tests/ORM/Query/ParserResultTest.php | 12 +- tests/Doctrine/Tests/ORM/Query/ParserTest.php | 26 +- .../ORM/Query/QueryExpressionVisitorTest.php | 39 +- tests/Doctrine/Tests/ORM/Query/QueryTest.php | 128 +-- .../ORM/Query/SelectSqlGenerationTest.php | 769 +++++++++--------- .../Tests/ORM/Query/SqlWalkerTest.php | 25 +- .../ORM/Query/UpdateSqlGenerationTest.php | 62 +- tests/Doctrine/Tests/ORM/QueryBuilderTest.php | 245 +++--- .../DefaultRepositoryFactoryTest.php | 60 +- .../AttachEntityListenersListenerTest.php | 39 +- .../ClearCacheCollectionRegionCommandTest.php | 20 +- .../ClearCacheEntityRegionCommandTest.php | 20 +- .../ClearCacheQueryRegionCommandTest.php | 20 +- .../ConvertDoctrine1SchemaCommandTest.php | 10 +- .../GenerateRepositoriesCommandTest.php | 67 +- .../Tools/Console/Command/InfoCommandTest.php | 30 +- .../Command/MappingDescribeCommandTest.php | 24 +- .../Console/Command/RunDqlCommandTest.php | 24 +- .../ORM/Tools/Console/ConsoleRunnerTest.php | 7 +- .../ORM/Tools/Console/MetadataFilterTest.php | 23 +- .../ORM/Tools/ConvertDoctrine1SchemaTest.php | 42 +- .../Tests/ORM/Tools/EntityGeneratorTest.php | 690 ++++++++-------- .../Tools/EntityRepositoryGeneratorTest.php | 99 ++- .../AbstractClassMetadataExporterTest.php | 162 ++-- .../AnnotationClassMetadataExporterTest.php | 7 +- .../Export/PhpClassMetadataExporterTest.php | 7 +- .../Export/XmlClassMetadataExporterTest.php | 44 +- .../Export/YamlClassMetadataExporterTest.php | 11 +- .../Doctrine.Tests.ORM.Tools.Export.User.php | 19 +- .../Doctrine.Tests.ORM.Tools.Export.User.php | 196 +++-- .../Pagination/CountOutputWalkerTest.php | 40 +- .../ORM/Tools/Pagination/CountWalkerTest.php | 58 +- .../LimitSubqueryOutputWalkerTest.php | 123 +-- .../Pagination/LimitSubqueryWalkerTest.php | 33 +- .../Tools/Pagination/PaginationTestCase.php | 51 +- .../ORM/Tools/Pagination/PaginatorTest.php | 25 +- .../Tools/Pagination/WhereInWalkerTest.php | 79 +- .../Tools/ResolveTargetEntityListenerTest.php | 46 +- .../Tests/ORM/Tools/SchemaToolTest.php | 93 +-- .../Tests/ORM/Tools/SchemaValidatorTest.php | 152 +++- tests/Doctrine/Tests/ORM/Tools/SetupTest.php | 47 +- tests/Doctrine/Tests/ORM/UnitOfWorkTest.php | 225 +++-- .../HierarchyDiscriminatorResolverTest.php | 29 +- .../ORM/Utility/IdentifierFlattenerTest.php | 33 +- .../Doctrine/Tests/OrmFunctionalTestCase.php | 207 ++--- .../Doctrine/Tests/OrmPerformanceTestCase.php | 51 +- tests/Doctrine/Tests/OrmTestCase.php | 81 +- tests/Doctrine/Tests/TestInit.php | 25 +- tests/Doctrine/Tests/TestUtil.php | 32 +- tests/Doctrine/Tests/VerifyDeprecations.php | 19 +- tools/sandbox/Entities/Address.php | 6 +- tools/sandbox/Entities/User.php | 6 +- tools/sandbox/bootstrap.php | 27 +- tools/sandbox/doctrine.php | 67 +- tools/sandbox/index.php | 11 +- 1190 files changed, 23536 insertions(+), 24931 deletions(-) diff --git a/lib/Doctrine/ORM/AbstractQuery.php b/lib/Doctrine/ORM/AbstractQuery.php index a0731faa4ed..c16eb1f9cd0 100644 --- a/lib/Doctrine/ORM/AbstractQuery.php +++ b/lib/Doctrine/ORM/AbstractQuery.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - * @author Konsta Vesterinen */ abstract class AbstractQuery { @@ -62,27 +64,27 @@ abstract class AbstractQuery /** * Hydrates an object graph. This is the default behavior. */ - const HYDRATE_OBJECT = 1; + public const HYDRATE_OBJECT = 1; /** * Hydrates an array graph. */ - const HYDRATE_ARRAY = 2; + public const HYDRATE_ARRAY = 2; /** * Hydrates a flat, rectangular result set with scalar values. */ - const HYDRATE_SCALAR = 3; + public const HYDRATE_SCALAR = 3; /** * Hydrates a single scalar value. */ - const HYDRATE_SINGLE_SCALAR = 4; + public const HYDRATE_SINGLE_SCALAR = 4; /** * Very simple object hydrator (optimized for performance). */ - const HYDRATE_SIMPLEOBJECT = 5; + public const HYDRATE_SIMPLEOBJECT = 5; /** * The parameter map of this query. @@ -95,7 +97,7 @@ abstract class AbstractQuery /** * The user-specified ResultSetMapping to use. * - * @var \Doctrine\ORM\Query\ResultSetMapping + * @var ResultSetMapping */ protected $_resultSetMapping; @@ -120,33 +122,27 @@ abstract class AbstractQuery */ protected $_hydrationMode = self::HYDRATE_OBJECT; - /** - * @var \Doctrine\DBAL\Cache\QueryCacheProfile - */ + /** @var QueryCacheProfile */ protected $_queryCacheProfile; /** * Whether or not expire the result cache. * - * @var boolean + * @var bool */ protected $_expireResultCache = false; - /** - * @var \Doctrine\DBAL\Cache\QueryCacheProfile - */ + /** @var QueryCacheProfile */ protected $_hydrationCacheProfile; /** * Whether to use second level cache, if available. * - * @var boolean + * @var bool */ protected $cacheable = false; - /** - * @var boolean - */ + /** @var bool */ protected $hasCache = false; /** @@ -159,31 +155,25 @@ abstract class AbstractQuery /** * Second level query cache mode. * - * @var integer|null + * @var int|null */ protected $cacheMode; - /** - * @var \Doctrine\ORM\Cache\Logging\CacheLogger|null - */ + /** @var CacheLogger|null */ protected $cacheLogger; - /** - * @var integer - */ + /** @var int */ protected $lifetime = 0; /** * Initializes a new instance of a class derived from AbstractQuery. - * - * @param \Doctrine\ORM\EntityManagerInterface $em */ public function __construct(EntityManagerInterface $em) { - $this->_em = $em; - $this->parameters = new ArrayCollection(); - $this->_hints = $em->getConfiguration()->getDefaultQueryHints(); - $this->hasCache = $this->_em->getConfiguration()->isSecondLevelCacheEnabled(); + $this->_em = $em; + $this->parameters = new ArrayCollection(); + $this->_hints = $em->getConfiguration()->getDefaultQueryHints(); + $this->hasCache = $this->_em->getConfiguration()->isSecondLevelCacheEnabled(); if ($this->hasCache) { $this->cacheLogger = $em->getConfiguration() @@ -195,19 +185,19 @@ public function __construct(EntityManagerInterface $em) /** * Enable/disable second level query (result) caching for this query. * - * @param boolean $cacheable + * @param bool $cacheable * * @return static This query instance. */ public function setCacheable($cacheable) { - $this->cacheable = (boolean) $cacheable; + $this->cacheable = (bool) $cacheable; return $this; } /** - * @return boolean TRUE if the query results are enable for second level cache, FALSE otherwise. + * @return bool TRUE if the query results are enable for second level cache, FALSE otherwise. */ public function isCacheable() { @@ -227,17 +217,17 @@ public function setCacheRegion($cacheRegion) } /** - * Obtain the name of the second level query cache region in which query results will be stored - * - * @return string|null The cache region name; NULL indicates the default region. - */ + * Obtain the name of the second level query cache region in which query results will be stored + * + * @return string|null The cache region name; NULL indicates the default region. + */ public function getCacheRegion() { return $this->cacheRegion; } /** - * @return boolean TRUE if the query cache and second level cache are enabled, FALSE otherwise. + * @return bool TRUE if the query cache and second level cache are enabled, FALSE otherwise. */ protected function isCacheEnabled() { @@ -245,7 +235,7 @@ protected function isCacheEnabled() } /** - * @return integer + * @return int */ public function getLifetime() { @@ -255,19 +245,19 @@ public function getLifetime() /** * Sets the life-time for this query into second level cache. * - * @param integer $lifetime + * @param int $lifetime * * @return static This query instance. */ public function setLifetime($lifetime) { - $this->lifetime = (integer) $lifetime; + $this->lifetime = (int) $lifetime; return $this; } /** - * @return integer + * @return int */ public function getCacheMode() { @@ -275,13 +265,13 @@ public function getCacheMode() } /** - * @param integer $cacheMode + * @param int $cacheMode * * @return static This query instance. */ public function setCacheMode($cacheMode) { - $this->cacheMode = (integer) $cacheMode; + $this->cacheMode = (int) $cacheMode; return $this; } @@ -298,7 +288,7 @@ abstract public function getSQL(); /** * Retrieves the associated EntityManager of this Query instance. * - * @return \Doctrine\ORM\EntityManager + * @return EntityManager */ public function getEntityManager() { @@ -341,7 +331,7 @@ public function getParameter($key) $key = Query\Parameter::normalizeName($key); $filteredParameters = $this->parameters->filter( - function (Query\Parameter $parameter) use ($key) : bool { + static function (Query\Parameter $parameter) use ($key): bool { $parameterName = $parameter->getName(); return $key === $parameterName; @@ -412,7 +402,7 @@ public function setParameter($key, $value, $type = null) * * @return mixed[]|string|int|float|bool * - * @throws \Doctrine\ORM\ORMInvalidArgumentException + * @throws ORMInvalidArgumentException * * @psalm-return array|scalar */ @@ -496,8 +486,6 @@ private function processArrayParameterValue(array $value): array /** * Sets the ResultSetMapping that should be used for hydration. * - * @param \Doctrine\ORM\Query\ResultSetMapping $rsm - * * @return static This query instance. */ public function setResultSetMapping(Query\ResultSetMapping $rsm) @@ -511,7 +499,7 @@ public function setResultSetMapping(Query\ResultSetMapping $rsm) /** * Gets the ResultSetMapping used for hydration. * - * @return \Doctrine\ORM\Query\ResultSetMapping + * @return ResultSetMapping */ protected function getResultSetMapping() { @@ -521,17 +509,15 @@ protected function getResultSetMapping() /** * Allows to translate entity namespaces to full qualified names. * - * @param Query\ResultSetMapping $rsm - * * @return void */ private function translateNamespaces(Query\ResultSetMapping $rsm) { - $translate = function ($alias) : string { + $translate = function ($alias): string { return $this->_em->getClassMetadata($alias)->getName(); }; - $rsm->aliasMap = array_map($translate, $rsm->aliasMap); + $rsm->aliasMap = array_map($translate, $rsm->aliasMap); $rsm->declaringClasses = array_map($translate, $rsm->declaringClasses); } @@ -547,21 +533,19 @@ private function translateNamespaces(Query\ResultSetMapping $rsm) * some form of caching with UnitOfWork registration you should use * {@see AbstractQuery::setResultCacheProfile()}. * + * @return static This query instance. + * * @example * $lifetime = 100; * $resultKey = "abc"; * $query->setHydrationCacheProfile(new QueryCacheProfile()); * $query->setHydrationCacheProfile(new QueryCacheProfile($lifetime, $resultKey)); - * - * @param \Doctrine\DBAL\Cache\QueryCacheProfile $profile - * - * @return static This query instance. */ - public function setHydrationCacheProfile(QueryCacheProfile $profile = null) + public function setHydrationCacheProfile(?QueryCacheProfile $profile = null) { if ($profile !== null && ! $profile->getResultCacheDriver()) { $resultCacheDriver = $this->_em->getConfiguration()->getHydrationCacheImpl(); - $profile = $profile->setResultCacheDriver($resultCacheDriver); + $profile = $profile->setResultCacheDriver($resultCacheDriver); } $this->_hydrationCacheProfile = $profile; @@ -570,7 +554,7 @@ public function setHydrationCacheProfile(QueryCacheProfile $profile = null) } /** - * @return \Doctrine\DBAL\Cache\QueryCacheProfile + * @return QueryCacheProfile */ public function getHydrationCacheProfile() { @@ -583,15 +567,13 @@ public function getHydrationCacheProfile() * If no result cache driver is set in the QueryCacheProfile, the default * result cache driver is used from the configuration. * - * @param \Doctrine\DBAL\Cache\QueryCacheProfile $profile - * * @return static This query instance. */ - public function setResultCacheProfile(QueryCacheProfile $profile = null) + public function setResultCacheProfile(?QueryCacheProfile $profile = null) { if ($profile !== null && ! $profile->getResultCacheDriver()) { $resultCacheDriver = $this->_em->getConfiguration()->getResultCacheImpl(); - $profile = $profile->setResultCacheDriver($resultCacheDriver); + $profile = $profile->setResultCacheDriver($resultCacheDriver); } $this->_queryCacheProfile = $profile; @@ -665,7 +647,7 @@ public function useResultCache($useCache, $lifetime = null, $resultCacheId = nul * * @return static This query instance. */ - public function enableResultCache(?int $lifetime = null, ?string $resultCacheId = null) : self + public function enableResultCache(?int $lifetime = null, ?string $resultCacheId = null): self { $this->setResultCacheLifetime($lifetime); $this->setResultCacheId($resultCacheId); @@ -678,7 +660,7 @@ public function enableResultCache(?int $lifetime = null, ?string $resultCacheId * * @return static This query instance. */ - public function disableResultCache() : self + public function disableResultCache(): self { $this->_queryCacheProfile = null; @@ -694,7 +676,7 @@ public function disableResultCache() : self */ public function setResultCacheLifetime($lifetime) { - $lifetime = ($lifetime !== null) ? (int) $lifetime : 0; + $lifetime = $lifetime !== null ? (int) $lifetime : 0; $this->_queryCacheProfile = $this->_queryCacheProfile ? $this->_queryCacheProfile->setLifetime($lifetime) @@ -708,7 +690,7 @@ public function setResultCacheLifetime($lifetime) * * @deprecated * - * @return integer + * @return int */ public function getResultCacheLifetime() { @@ -718,7 +700,7 @@ public function getResultCacheLifetime() /** * Defines if the result cache is active or not. * - * @param boolean $expire Whether or not to force resultset cache expiration. + * @param bool $expire Whether or not to force resultset cache expiration. * * @return static This query instance. */ @@ -732,7 +714,7 @@ public function expireResultCache($expire = true) /** * Retrieves if the resultset cache is active or not. * - * @return boolean + * @return bool */ public function getExpireResultCache() { @@ -849,17 +831,16 @@ public function getOneOrNullResult($hydrationMode = null) return null; } - if ($this->_hydrationMode !== self::HYDRATE_SINGLE_SCALAR && ! $result) { return null; } - if ( ! is_array($result)) { + if (! is_array($result)) { return $result; } if (count($result) > 1) { - throw new NonUniqueResultException; + throw new NonUniqueResultException(); } return array_shift($result); @@ -885,15 +866,15 @@ public function getSingleResult($hydrationMode = null) $result = $this->execute(null, $hydrationMode); if ($this->_hydrationMode !== self::HYDRATE_SINGLE_SCALAR && ! $result) { - throw new NoResultException; + throw new NoResultException(); } - if ( ! is_array($result)) { + if (! is_array($result)) { return $result; } if (count($result) > 1) { - throw new NonUniqueResultException; + throw new NonUniqueResultException(); } return array_shift($result); @@ -938,7 +919,7 @@ public function setHint($name, $value) */ public function getHint($name) { - return isset($this->_hints[$name]) ? $this->_hints[$name] : false; + return $this->_hints[$name] ?? false; } /** @@ -972,7 +953,7 @@ public function getHints() * @param ArrayCollection|array|null $parameters The query parameters. * @param string|int|null $hydrationMode The hydration mode to use. * - * @return \Doctrine\ORM\Internal\Hydration\IterableResult + * @return IterableResult */ public function iterate($parameters = null, $hydrationMode = null) { @@ -985,7 +966,7 @@ public function iterate($parameters = null, $hydrationMode = null) $this->setHydrationMode($hydrationMode); } - if ( ! empty($parameters)) { + if (! empty($parameters)) { $this->setParameters($parameters); } @@ -1004,13 +985,14 @@ public function iterate($parameters = null, $hydrationMode = null) * * @return iterable */ - public function toIterable(iterable $parameters = [], $hydrationMode = null) : iterable + public function toIterable(iterable $parameters = [], $hydrationMode = null): iterable { if ($hydrationMode !== null) { $this->setHydrationMode($hydrationMode); } - if (($this->isCountable($parameters) && count($parameters) !== 0) + if ( + ($this->isCountable($parameters) && count($parameters) !== 0) || ($parameters instanceof Traversable && iterator_count($parameters) !== 0) ) { $this->setParameters($parameters); @@ -1025,7 +1007,7 @@ public function toIterable(iterable $parameters = [], $hydrationMode = null) : i /** * Executes the query. * - * @param ArrayCollection|array|null $parameters Query parameters. + * @param ArrayCollection|array|null $parameters Query parameters. * @param string|int|null $hydrationMode Processing mode to be used during the hydration process. * * @return mixed @@ -1053,11 +1035,11 @@ private function executeIgnoreQueryCache($parameters = null, $hydrationMode = nu $this->setHydrationMode($hydrationMode); } - if ( ! empty($parameters)) { + if (! empty($parameters)) { $this->setParameters($parameters); } - $setCacheEntry = static function () : void { + $setCacheEntry = static function (): void { }; if ($this->_hydrationCacheProfile !== null) { @@ -1071,11 +1053,11 @@ private function executeIgnoreQueryCache($parameters = null, $hydrationMode = nu return $result[$realCacheKey]; } - if ( ! $result) { + if (! $result) { $result = []; } - $setCacheEntry = static function ($data) use ($cache, $result, $cacheKey, $realCacheKey, $queryCacheProfile) : void { + $setCacheEntry = static function ($data) use ($cache, $result, $cacheKey, $realCacheKey, $queryCacheProfile): void { $result[$realCacheKey] = $data; $cache->save($cacheKey, $result, $queryCacheProfile->getLifetime()); @@ -1117,7 +1099,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) { @@ -1142,7 +1124,7 @@ private function executeUsingQueryCache($parameters = null, $hydrationMode = nul } /** - * @return \Doctrine\ORM\Cache\TimestampCacheKey|null + * @return TimestampCacheKey|null */ private function getTimestampKey() { @@ -1215,7 +1197,7 @@ public function getResultCacheId() /** * Executes the query and returns a the resulting Statement object. * - * @return \Doctrine\DBAL\Driver\Statement The executed database statement that holds the results. + * @return Statement The executed database statement that holds the results. */ abstract protected function _doExecute(); @@ -1241,7 +1223,7 @@ protected function getHash() { $query = $this->getSQL(); $hints = $this->getHints(); - $params = array_map(function(Parameter $parameter) { + $params = array_map(function (Parameter $parameter) { // Small optimization // Does not invoke processParameterValue for scalar values if (is_scalar($value = $parameter->getValue())) { @@ -1257,7 +1239,7 @@ protected function getHash() } /** @param iterable $subject */ - private function isCountable(iterable $subject) : bool + private function isCountable(iterable $subject): bool { return $subject instanceof Countable || is_array($subject); } diff --git a/lib/Doctrine/ORM/Cache.php b/lib/Doctrine/ORM/Cache.php index 3da7c05ef4e..23c2d6ebebd 100644 --- a/lib/Doctrine/ORM/Cache.php +++ b/lib/Doctrine/ORM/Cache.php @@ -20,44 +20,44 @@ namespace Doctrine\ORM; +use Doctrine\ORM\Cache\QueryCache; +use Doctrine\ORM\Cache\Region; + /** * Provides an API for querying/managing the second level cache regions. - * - * @since 2.5 - * @author Fabio B. Silva */ interface Cache { - const DEFAULT_QUERY_REGION_NAME = 'query_cache_region'; + public const DEFAULT_QUERY_REGION_NAME = 'query_cache_region'; - const DEFAULT_TIMESTAMP_REGION_NAME = 'timestamp_cache_region'; + public const DEFAULT_TIMESTAMP_REGION_NAME = 'timestamp_cache_region'; /** * May read items from the cache, but will not add items. */ - const MODE_GET = 1; + public const MODE_GET = 1; /** * Will never read items from the cache, * but will add items to the cache as it reads them from the database. */ - const MODE_PUT = 2; + public const MODE_PUT = 2; /** * May read items from the cache, and add items to the cache. */ - const MODE_NORMAL = 3; + public const MODE_NORMAL = 3; /** * The query will never read items from the cache, * but will refresh items to the cache as it reads them from the database. */ - const MODE_REFRESH = 4; + public const MODE_REFRESH = 4; /** * @param string $className The entity class. * - * @return \Doctrine\ORM\Cache\Region|null + * @return Region|null */ public function getEntityCacheRegion($className); @@ -65,7 +65,7 @@ public function getEntityCacheRegion($className); * @param string $className The entity class. * @param string $association The field name that represents the association. * - * @return \Doctrine\ORM\Cache\Region|null + * @return Region|null */ public function getCollectionCacheRegion($className, $association); @@ -75,7 +75,7 @@ public function getCollectionCacheRegion($className, $association); * @param string $className The entity class. * @param mixed $identifier The entity identifier * - * @return boolean true if the underlying cache contains corresponding data; false otherwise. + * @return bool true if the underlying cache contains corresponding data; false otherwise. */ public function containsEntity($className, $identifier); @@ -112,7 +112,7 @@ public function evictEntityRegions(); * @param string $association The field name that represents the association. * @param mixed $ownerIdentifier The identifier of the owning entity. * - * @return boolean true if the underlying cache contains corresponding data; false otherwise. + * @return bool true if the underlying cache contains corresponding data; false otherwise. */ public function containsCollection($className, $association, $ownerIdentifier); @@ -149,7 +149,7 @@ public function evictCollectionRegions(); * * @param string $regionName The cache name given to the query. * - * @return boolean true if the underlying cache contains corresponding data; false otherwise. + * @return bool true if the underlying cache contains corresponding data; false otherwise. */ public function containsQuery($regionName); @@ -172,7 +172,7 @@ public function evictQueryRegions(); * * @param string|null $regionName Query cache region name, or default query cache if the region name is NULL. * - * @return \Doctrine\ORM\Cache\QueryCache The Query Cache associated with the region name. + * @return QueryCache The Query Cache associated with the region name. */ public function getQueryCache($regionName = null); } diff --git a/lib/Doctrine/ORM/Cache/AssociationCacheEntry.php b/lib/Doctrine/ORM/Cache/AssociationCacheEntry.php index dae5e602da7..e3db6e0af48 100644 --- a/lib/Doctrine/ORM/Cache/AssociationCacheEntry.php +++ b/lib/Doctrine/ORM/Cache/AssociationCacheEntry.php @@ -22,9 +22,6 @@ /** * Association cache entry - * - * @since 2.5 - * @author Fabio B. Silva */ class AssociationCacheEntry implements CacheEntry { @@ -48,8 +45,8 @@ class AssociationCacheEntry implements CacheEntry */ public function __construct($class, array $identifier) { - $this->class = $class; - $this->identifier = $identifier; + $this->class = $class; + $this->identifier = $identifier; } /** diff --git a/lib/Doctrine/ORM/Cache/CacheConfiguration.php b/lib/Doctrine/ORM/Cache/CacheConfiguration.php index eb3ec428df3..d826fea335c 100644 --- a/lib/Doctrine/ORM/Cache/CacheConfiguration.php +++ b/lib/Doctrine/ORM/Cache/CacheConfiguration.php @@ -24,34 +24,23 @@ /** * Configuration container for second-level cache. - * - * @since 2.5 - * @author Fabio B. Silva */ class CacheConfiguration { - /** - * @var \Doctrine\ORM\Cache\CacheFactory|null - */ + /** @var CacheFactory|null */ private $cacheFactory; - /** - * @var \Doctrine\ORM\Cache\RegionsConfiguration|null - */ + /** @var RegionsConfiguration|null */ private $regionsConfig; - /** - * @var \Doctrine\ORM\Cache\Logging\CacheLogger|null - */ + /** @var CacheLogger|null */ private $cacheLogger; - /** - * @var \Doctrine\ORM\Cache\QueryCacheValidator|null - */ + /** @var QueryCacheValidator|null */ private $queryValidator; /** - * @return \Doctrine\ORM\Cache\CacheFactory|null + * @return CacheFactory|null */ public function getCacheFactory() { @@ -59,8 +48,6 @@ public function getCacheFactory() } /** - * @param \Doctrine\ORM\Cache\CacheFactory $factory - * * @return void */ public function setCacheFactory(CacheFactory $factory) @@ -69,23 +56,20 @@ public function setCacheFactory(CacheFactory $factory) } /** - * @return \Doctrine\ORM\Cache\Logging\CacheLogger|null + * @return CacheLogger|null */ public function getCacheLogger() { return $this->cacheLogger; } - /** - * @param \Doctrine\ORM\Cache\Logging\CacheLogger $logger - */ public function setCacheLogger(CacheLogger $logger) { $this->cacheLogger = $logger; } /** - * @return \Doctrine\ORM\Cache\RegionsConfiguration + * @return RegionsConfiguration */ public function getRegionsConfiguration() { @@ -96,16 +80,13 @@ public function getRegionsConfiguration() return $this->regionsConfig; } - /** - * @param \Doctrine\ORM\Cache\RegionsConfiguration $regionsConfig - */ public function setRegionsConfiguration(RegionsConfiguration $regionsConfig) { $this->regionsConfig = $regionsConfig; } /** - * @return \Doctrine\ORM\Cache\QueryCacheValidator + * @return QueryCacheValidator */ public function getQueryValidator() { @@ -118,9 +99,6 @@ public function getQueryValidator() return $this->queryValidator; } - /** - * @param \Doctrine\ORM\Cache\QueryCacheValidator $validator - */ public function setQueryValidator(QueryCacheValidator $validator) { $this->queryValidator = $validator; diff --git a/lib/Doctrine/ORM/Cache/CacheEntry.php b/lib/Doctrine/ORM/Cache/CacheEntry.php index c34b0ff9b00..b6f4875526e 100644 --- a/lib/Doctrine/ORM/Cache/CacheEntry.php +++ b/lib/Doctrine/ORM/Cache/CacheEntry.php @@ -26,11 +26,7 @@ * IMPORTANT NOTE: * * Fields of classes that implement CacheEntry are public for performance reason. - * - * @since 2.5 - * @author Fabio B. Silva */ interface CacheEntry { - } diff --git a/lib/Doctrine/ORM/Cache/CacheException.php b/lib/Doctrine/ORM/Cache/CacheException.php index 315a8aac2ef..24e752667cf 100644 --- a/lib/Doctrine/ORM/Cache/CacheException.php +++ b/lib/Doctrine/ORM/Cache/CacheException.php @@ -1,4 +1,5 @@ */ class CacheException extends ORMException { @@ -33,7 +33,7 @@ class CacheException extends ORMException * @param string $sourceEntity * @param string $fieldName * - * @return \Doctrine\ORM\Cache\CacheException + * @return CacheException */ public static function updateReadOnlyCollection($sourceEntity, $fieldName) { @@ -43,7 +43,7 @@ public static function updateReadOnlyCollection($sourceEntity, $fieldName) /** * @param string $entityName * - * @return \Doctrine\ORM\Cache\CacheException + * @return CacheException */ public static function updateReadOnlyEntity($entityName) { @@ -53,7 +53,7 @@ public static function updateReadOnlyEntity($entityName) /** * @param string $entityName * - * @return \Doctrine\ORM\Cache\CacheException + * @return CacheException */ public static function nonCacheableEntity($entityName) { diff --git a/lib/Doctrine/ORM/Cache/CacheFactory.php b/lib/Doctrine/ORM/Cache/CacheFactory.php index b915100623a..259c82a2757 100644 --- a/lib/Doctrine/ORM/Cache/CacheFactory.php +++ b/lib/Doctrine/ORM/Cache/CacheFactory.php @@ -20,68 +20,68 @@ namespace Doctrine\ORM\Cache; -use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Cache; +use Doctrine\ORM\Cache\Persister\Collection\CachedCollectionPersister; +use Doctrine\ORM\Cache\Persister\Entity\CachedEntityPersister; use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Persisters\Collection\CollectionPersister; use Doctrine\ORM\Persisters\Entity\EntityPersister; /** * Contract for building second level cache regions components. - * - * @since 2.5 - * @author Fabio B. Silva */ interface CacheFactory { /** * Build an entity persister for the given entity metadata. * - * @param \Doctrine\ORM\EntityManagerInterface $em The entity manager. - * @param \Doctrine\ORM\Persisters\Entity\EntityPersister $persister The entity persister that will be cached. - * @param \Doctrine\ORM\Mapping\ClassMetadata $metadata The entity metadata. + * @param EntityManagerInterface $em The entity manager. + * @param EntityPersister $persister The entity persister that will be cached. + * @param ClassMetadata $metadata The entity metadata. * - * @return \Doctrine\ORM\Cache\Persister\Entity\CachedEntityPersister + * @return CachedEntityPersister */ 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 EntityManagerInterface $em The entity manager. + * @param CollectionPersister $persister The collection persister that will be cached. + * @param array $mapping The association mapping. * - * @return \Doctrine\ORM\Cache\Persister\Collection\CachedCollectionPersister + * @return CachedCollectionPersister */ public function buildCachedCollectionPersister(EntityManagerInterface $em, CollectionPersister $persister, array $mapping); /** * Build a query cache based on the given region name * - * @param \Doctrine\ORM\EntityManagerInterface $em The Entity manager. - * @param string $regionName The region name. + * @param EntityManagerInterface $em The Entity manager. + * @param string $regionName The region name. * - * @return \Doctrine\ORM\Cache\QueryCache The built query cache. + * @return QueryCache The built query cache. */ public function buildQueryCache(EntityManagerInterface $em, $regionName = null); /** * Build an entity hydrator * - * @param \Doctrine\ORM\EntityManagerInterface $em The Entity manager. - * @param \Doctrine\ORM\Mapping\ClassMetadata $metadata The entity metadata. + * @param EntityManagerInterface $em The Entity manager. + * @param ClassMetadata $metadata The entity metadata. * - * @return \Doctrine\ORM\Cache\EntityHydrator The built entity hydrator. + * @return EntityHydrator The built entity hydrator. */ public function buildEntityHydrator(EntityManagerInterface $em, ClassMetadata $metadata); /** * Build a collection hydrator * - * @param \Doctrine\ORM\EntityManagerInterface $em The Entity manager. - * @param array $mapping The association mapping. + * @param EntityManagerInterface $em The Entity manager. + * @param array $mapping The association mapping. * - * @return \Doctrine\ORM\Cache\CollectionHydrator The built collection hydrator. + * @return CollectionHydrator The built collection hydrator. */ public function buildCollectionHydrator(EntityManagerInterface $em, array $mapping); @@ -90,23 +90,21 @@ public function buildCollectionHydrator(EntityManagerInterface $em, array $mappi * * @param array $cache The cache configuration. * - * @return \Doctrine\ORM\Cache\Region The cache region. + * @return Region The cache region. */ public function getRegion(array $cache); /** * Build timestamp cache region * - * @return \Doctrine\ORM\Cache\TimestampRegion The timestamp region. + * @return TimestampRegion The timestamp region. */ public function getTimestampRegion(); /** * Build \Doctrine\ORM\Cache * - * @param EntityManagerInterface $entityManager - * - * @return \Doctrine\ORM\Cache + * @return Cache */ public function createCache(EntityManagerInterface $entityManager); } diff --git a/lib/Doctrine/ORM/Cache/CacheKey.php b/lib/Doctrine/ORM/Cache/CacheKey.php index 1641c9900dc..13a437623d0 100644 --- a/lib/Doctrine/ORM/Cache/CacheKey.php +++ b/lib/Doctrine/ORM/Cache/CacheKey.php @@ -23,9 +23,6 @@ /** * Defines entity / collection / query key to be stored in the cache region. * Allows multiple roles to be stored in the same cache region. - * - * @since 2.5 - * @author Fabio B. Silva */ abstract class CacheKey { diff --git a/lib/Doctrine/ORM/Cache/CollectionCacheEntry.php b/lib/Doctrine/ORM/Cache/CollectionCacheEntry.php index b3a1defe14c..38b49b897ec 100644 --- a/lib/Doctrine/ORM/Cache/CollectionCacheEntry.php +++ b/lib/Doctrine/ORM/Cache/CollectionCacheEntry.php @@ -22,9 +22,6 @@ /** * Collection cache entry - * - * @since 2.5 - * @author Fabio B. Silva */ class CollectionCacheEntry implements CacheEntry { diff --git a/lib/Doctrine/ORM/Cache/CollectionCacheKey.php b/lib/Doctrine/ORM/Cache/CollectionCacheKey.php index 6b631455000..bfeee8c31c1 100644 --- a/lib/Doctrine/ORM/Cache/CollectionCacheKey.php +++ b/lib/Doctrine/ORM/Cache/CollectionCacheKey.php @@ -20,11 +20,13 @@ namespace Doctrine\ORM\Cache; +use function implode; +use function ksort; +use function str_replace; +use function strtolower; + /** * Defines entity collection roles to be stored in the cache region. - * - * @since 2.5 - * @author Fabio B. Silva */ class CollectionCacheKey extends CacheKey { @@ -58,9 +60,9 @@ public function __construct($entityClass, $association, array $ownerIdentifier) { ksort($ownerIdentifier); - $this->ownerIdentifier = $ownerIdentifier; - $this->entityClass = (string) $entityClass; - $this->association = (string) $association; - $this->hash = str_replace('\\', '.', strtolower($entityClass)) . '_' . implode(' ', $ownerIdentifier) . '__' . $association; + $this->ownerIdentifier = $ownerIdentifier; + $this->entityClass = (string) $entityClass; + $this->association = (string) $association; + $this->hash = str_replace('\\', '.', strtolower($entityClass)) . '_' . implode(' ', $ownerIdentifier) . '__' . $association; } } diff --git a/lib/Doctrine/ORM/Cache/CollectionHydrator.php b/lib/Doctrine/ORM/Cache/CollectionHydrator.php index 04cdde16268..e4a901b9462 100644 --- a/lib/Doctrine/ORM/Cache/CollectionHydrator.php +++ b/lib/Doctrine/ORM/Cache/CollectionHydrator.php @@ -20,31 +20,29 @@ namespace Doctrine\ORM\Cache; -use Doctrine\ORM\PersistentCollection; +use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\PersistentCollection; /** * Hydrator cache entry for collections - * - * @since 2.5 - * @author Fabio B. Silva */ interface CollectionHydrator { /** - * @param \Doctrine\ORM\Mapping\ClassMetadata $metadata The entity metadata. - * @param \Doctrine\ORM\Cache\CollectionCacheKey $key The cached collection key. - * @param array|\Doctrine\Common\Collections\Collection $collection The collection. + * @param ClassMetadata $metadata The entity metadata. + * @param CollectionCacheKey $key The cached collection key. + * @param array|Collection $collection The collection. * - * @return \Doctrine\ORM\Cache\CollectionCacheEntry + * @return CollectionCacheEntry */ public function buildCacheEntry(ClassMetadata $metadata, CollectionCacheKey $key, $collection); /** - * @param \Doctrine\ORM\Mapping\ClassMetadata $metadata The owning entity metadata. - * @param \Doctrine\ORM\Cache\CollectionCacheKey $key The cached collection key. - * @param \Doctrine\ORM\Cache\CollectionCacheEntry $entry The cached collection entry. - * @param \Doctrine\ORM\PersistentCollection $collection The collection to load the cache into. + * @param ClassMetadata $metadata The owning entity metadata. + * @param CollectionCacheKey $key The cached collection key. + * @param CollectionCacheEntry $entry The cached collection entry. + * @param PersistentCollection $collection The collection to load the cache into. * * @return array */ diff --git a/lib/Doctrine/ORM/Cache/ConcurrentRegion.php b/lib/Doctrine/ORM/Cache/ConcurrentRegion.php index 12da6d615ad..b9724be967c 100644 --- a/lib/Doctrine/ORM/Cache/ConcurrentRegion.php +++ b/lib/Doctrine/ORM/Cache/ConcurrentRegion.php @@ -26,32 +26,29 @@ * * When a entry is locked another process should not be able to read or write the entry. * All evict operation should not consider locks, even though an entry is locked evict should be able to delete the entry and its lock. - * - * @since 2.5 - * @author Fabio B. Silva */ interface ConcurrentRegion extends Region { /** * Attempts to read lock the mapping for the given key. * - * @param \Doctrine\ORM\Cache\CacheKey $key The key of the item to lock. + * @param CacheKey $key The key of the item to lock. * - * @return \Doctrine\ORM\Cache\Lock A lock instance or NULL if the lock already exists. + * @return Lock A lock instance or NULL if the lock already exists. * - * @throws \Doctrine\ORM\Cache\LockException Indicates a problem accessing the region. + * @throws LockException Indicates a problem accessing the region. */ public function lock(CacheKey $key); /** * Attempts to read unlock the mapping for the given key. * - * @param \Doctrine\ORM\Cache\CacheKey $key The key of the item to unlock. - * @param \Doctrine\ORM\Cache\Lock $lock The lock previously obtained from {@link readLock} + * @param CacheKey $key The key of the item to unlock. + * @param Lock $lock The lock previously obtained from {@link readLock} * * @return void * - * @throws \Doctrine\ORM\Cache\LockException Indicates a problem accessing the region. + * @throws LockException Indicates a problem accessing the region. */ public function unlock(CacheKey $key, Lock $lock); } diff --git a/lib/Doctrine/ORM/Cache/DefaultCache.php b/lib/Doctrine/ORM/Cache/DefaultCache.php index 9c93ddd7e1e..f8b7b46a001 100644 --- a/lib/Doctrine/ORM/Cache/DefaultCache.php +++ b/lib/Doctrine/ORM/Cache/DefaultCache.php @@ -20,44 +20,35 @@ namespace Doctrine\ORM\Cache; -use Doctrine\ORM\Cache; use Doctrine\Common\Util\ClassUtils; -use Doctrine\ORM\Mapping\ClassMetadata; -use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\Cache; use Doctrine\ORM\Cache\Persister\CachedPersister; +use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\ORMInvalidArgumentException; +use Doctrine\ORM\UnitOfWork; + +use function is_array; +use function is_object; /** * Provides an API for querying/managing the second level cache regions. - * - * @since 2.5 - * @author Fabio B. Silva */ class DefaultCache implements Cache { - /** - * @var \Doctrine\ORM\EntityManagerInterface - */ + /** @var EntityManagerInterface */ private $em; - /** - * @var \Doctrine\ORM\UnitOfWork - */ + /** @var UnitOfWork */ private $uow; - /** - * @var \Doctrine\ORM\Cache\CacheFactory - */ + /** @var CacheFactory */ private $cacheFactory; - /** - * @var \Doctrine\ORM\Cache\QueryCache[] - */ + /** @var QueryCache[] */ private $queryCaches = []; - /** - * @var \Doctrine\ORM\Cache\QueryCache - */ + /** @var QueryCache */ private $defaultQueryCache; public function __construct(EntityManagerInterface $em) @@ -77,7 +68,7 @@ public function getEntityCacheRegion($className) $metadata = $this->em->getClassMetadata($className); $persister = $this->uow->getEntityPersister($metadata->rootEntityName); - if ( ! ($persister instanceof CachedPersister)) { + if (! ($persister instanceof CachedPersister)) { return null; } @@ -92,7 +83,7 @@ public function getCollectionCacheRegion($className, $association) $metadata = $this->em->getClassMetadata($className); $persister = $this->uow->getCollectionPersister($metadata->getAssociationMapping($association)); - if ( ! ($persister instanceof CachedPersister)) { + if (! ($persister instanceof CachedPersister)) { return null; } @@ -104,10 +95,10 @@ public function getCollectionCacheRegion($className, $association) */ public function containsEntity($className, $identifier) { - $metadata = $this->em->getClassMetadata($className); - $persister = $this->uow->getEntityPersister($metadata->rootEntityName); + $metadata = $this->em->getClassMetadata($className); + $persister = $this->uow->getEntityPersister($metadata->rootEntityName); - if ( ! ($persister instanceof CachedPersister)) { + if (! ($persister instanceof CachedPersister)) { return false; } @@ -122,7 +113,7 @@ public function evictEntity($className, $identifier) $metadata = $this->em->getClassMetadata($className); $persister = $this->uow->getEntityPersister($metadata->rootEntityName); - if ( ! ($persister instanceof CachedPersister)) { + if (! ($persister instanceof CachedPersister)) { return; } @@ -137,7 +128,7 @@ public function evictEntityRegion($className) $metadata = $this->em->getClassMetadata($className); $persister = $this->uow->getEntityPersister($metadata->rootEntityName); - if ( ! ($persister instanceof CachedPersister)) { + if (! ($persister instanceof CachedPersister)) { return; } @@ -154,7 +145,7 @@ public function evictEntityRegions() foreach ($metadatas as $metadata) { $persister = $this->uow->getEntityPersister($metadata->rootEntityName); - if ( ! ($persister instanceof CachedPersister)) { + if (! ($persister instanceof CachedPersister)) { continue; } @@ -170,7 +161,7 @@ public function containsCollection($className, $association, $ownerIdentifier) $metadata = $this->em->getClassMetadata($className); $persister = $this->uow->getCollectionPersister($metadata->getAssociationMapping($association)); - if ( ! ($persister instanceof CachedPersister)) { + if (! ($persister instanceof CachedPersister)) { return false; } @@ -185,7 +176,7 @@ public function evictCollection($className, $association, $ownerIdentifier) $metadata = $this->em->getClassMetadata($className); $persister = $this->uow->getCollectionPersister($metadata->getAssociationMapping($association)); - if ( ! ($persister instanceof CachedPersister)) { + if (! ($persister instanceof CachedPersister)) { return; } @@ -200,7 +191,7 @@ public function evictCollectionRegion($className, $association) $metadata = $this->em->getClassMetadata($className); $persister = $this->uow->getCollectionPersister($metadata->getAssociationMapping($association)); - if ( ! ($persister instanceof CachedPersister)) { + if (! ($persister instanceof CachedPersister)) { return; } @@ -215,16 +206,14 @@ public function evictCollectionRegions() $metadatas = $this->em->getMetadataFactory()->getAllMetadata(); foreach ($metadatas as $metadata) { - foreach ($metadata->associationMappings as $association) { - - if ( ! $association['type'] & ClassMetadata::TO_MANY) { + if (! $association['type'] & ClassMetadata::TO_MANY) { continue; } $persister = $this->uow->getCollectionPersister($association); - if ( ! ($persister instanceof CachedPersister)) { + if (! ($persister instanceof CachedPersister)) { continue; } @@ -279,7 +268,7 @@ public function getQueryCache($regionName = null) $this->defaultQueryCache = $this->cacheFactory->buildQueryCache($this->em); } - if ( ! isset($this->queryCaches[$regionName])) { + if (! isset($this->queryCaches[$regionName])) { $this->queryCaches[$regionName] = $this->cacheFactory->buildQueryCache($this->em, $regionName); } @@ -287,14 +276,14 @@ public function getQueryCache($regionName = null) } /** - * @param \Doctrine\ORM\Mapping\ClassMetadata $metadata The entity metadata. - * @param mixed $identifier The entity identifier. - * - * @return \Doctrine\ORM\Cache\EntityCacheKey - */ + * @param ClassMetadata $metadata The entity metadata. + * @param mixed $identifier The entity identifier. + * + * @return EntityCacheKey + */ private function buildEntityCacheKey(ClassMetadata $metadata, $identifier) { - if ( ! is_array($identifier)) { + if (! is_array($identifier)) { $identifier = $this->toIdentifierArray($metadata, $identifier); } @@ -302,15 +291,15 @@ private function buildEntityCacheKey(ClassMetadata $metadata, $identifier) } /** - * @param \Doctrine\ORM\Mapping\ClassMetadata $metadata The entity metadata. - * @param string $association The field name that represents the association. - * @param mixed $ownerIdentifier The identifier of the owning entity. + * @param ClassMetadata $metadata The entity metadata. + * @param string $association The field name that represents the association. + * @param mixed $ownerIdentifier The identifier of the owning entity. * - * @return \Doctrine\ORM\Cache\CollectionCacheKey + * @return CollectionCacheKey */ private function buildCollectionCacheKey(ClassMetadata $metadata, $association, $ownerIdentifier) { - if ( ! is_array($ownerIdentifier)) { + if (! is_array($ownerIdentifier)) { $ownerIdentifier = $this->toIdentifierArray($metadata, $ownerIdentifier); } @@ -318,8 +307,8 @@ private function buildCollectionCacheKey(ClassMetadata $metadata, $association, } /** - * @param \Doctrine\ORM\Mapping\ClassMetadata $metadata The entity metadata. - * @param mixed $identifier The entity identifier. + * @param ClassMetadata $metadata The entity metadata. + * @param mixed $identifier The entity identifier. * * @return array */ @@ -335,5 +324,4 @@ private function toIdentifierArray(ClassMetadata $metadata, $identifier) return [$metadata->identifier[0] => $identifier]; } - } diff --git a/lib/Doctrine/ORM/Cache/DefaultCacheFactory.php b/lib/Doctrine/ORM/Cache/DefaultCacheFactory.php index bfc6aa29ab1..45f3a88584d 100644 --- a/lib/Doctrine/ORM/Cache/DefaultCacheFactory.php +++ b/lib/Doctrine/ORM/Cache/DefaultCacheFactory.php @@ -38,42 +38,30 @@ use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Persisters\Collection\CollectionPersister; use Doctrine\ORM\Persisters\Entity\EntityPersister; +use InvalidArgumentException; +use LogicException; + +use function sprintf; + +use const DIRECTORY_SEPARATOR; -/** - * @since 2.5 - * @author Fabio B. Silva - */ class DefaultCacheFactory implements CacheFactory { - /** - * @var CacheAdapter - */ + /** @var CacheAdapter */ private $cache; - /** - * @var \Doctrine\ORM\Cache\RegionsConfiguration - */ + /** @var RegionsConfiguration */ private $regionsConfig; - /** - * @var \Doctrine\ORM\Cache\TimestampRegion|null - */ + /** @var TimestampRegion|null */ private $timestampRegion; - /** - * @var \Doctrine\ORM\Cache\Region[] - */ + /** @var Region[] */ private $regions = []; - /** - * @var string|null - */ + /** @var string|null */ private $fileLockRegionDirectory; - /** - * @param RegionsConfiguration $cacheConfig - * @param CacheAdapter $cache - */ public function __construct(RegionsConfiguration $cacheConfig, CacheAdapter $cache) { $this->cache = $cache; @@ -96,17 +84,11 @@ public function getFileLockRegionDirectory() return $this->fileLockRegionDirectory; } - /** - * @param \Doctrine\ORM\Cache\Region $region - */ public function setRegion(Region $region) { $this->regions[$region->getName()] = $region; } - /** - * @param \Doctrine\ORM\Cache\TimestampRegion $region - */ public function setTimestampRegion(TimestampRegion $region) { $this->timestampRegion = $region; @@ -117,8 +99,8 @@ public function setTimestampRegion(TimestampRegion $region) */ public function buildCachedEntityPersister(EntityManagerInterface $em, EntityPersister $persister, ClassMetadata $metadata) { - $region = $this->getRegion($metadata->cache); - $usage = $metadata->cache['usage']; + $region = $this->getRegion($metadata->cache); + $usage = $metadata->cache['usage']; if ($usage === ClassMetadata::CACHE_USAGE_READ_ONLY) { return new ReadOnlyCachedEntityPersister($persister, $region, $em, $metadata); @@ -132,7 +114,7 @@ public function buildCachedEntityPersister(EntityManagerInterface $em, EntityPer return new ReadWriteCachedEntityPersister($persister, $region, $em, $metadata); } - throw new \InvalidArgumentException(sprintf("Unrecognized access strategy type [%s]", $usage)); + throw new InvalidArgumentException(sprintf('Unrecognized access strategy type [%s]', $usage)); } /** @@ -140,8 +122,8 @@ public function buildCachedEntityPersister(EntityManagerInterface $em, EntityPer */ public function buildCachedCollectionPersister(EntityManagerInterface $em, CollectionPersister $persister, array $mapping) { - $usage = $mapping['cache']['usage']; - $region = $this->getRegion($mapping['cache']); + $usage = $mapping['cache']['usage']; + $region = $this->getRegion($mapping['cache']); if ($usage === ClassMetadata::CACHE_USAGE_READ_ONLY) { return new ReadOnlyCachedCollectionPersister($persister, $region, $em, $mapping); @@ -155,7 +137,7 @@ public function buildCachedCollectionPersister(EntityManagerInterface $em, Colle return new ReadWriteCachedCollectionPersister($persister, $region, $em, $mapping); } - throw new \InvalidArgumentException(sprintf("Unrecognized access strategy type [%s]", $usage)); + throw new InvalidArgumentException(sprintf('Unrecognized access strategy type [%s]', $usage)); } /** @@ -168,7 +150,7 @@ public function buildQueryCache(EntityManagerInterface $em, $regionName = null) $this->getRegion( [ 'region' => $regionName ?: Cache::DEFAULT_QUERY_REGION_NAME, - 'usage' => ClassMetadata::CACHE_USAGE_NONSTRICT_READ_WRITE + 'usage' => ClassMetadata::CACHE_USAGE_NONSTRICT_READ_WRITE, ] ) ); @@ -203,17 +185,16 @@ public function getRegion(array $cache) $cacheAdapter = $this->createRegionCache($name); $lifetime = $this->regionsConfig->getLifetime($cache['region']); - $region = ($cacheAdapter instanceof MultiGetCache) + $region = $cacheAdapter instanceof MultiGetCache ? new DefaultMultiGetRegion($name, $cacheAdapter, $lifetime) : new DefaultRegion($name, $cacheAdapter, $lifetime); if ($cache['usage'] === ClassMetadata::CACHE_USAGE_READ_WRITE) { - if ( - '' === $this->fileLockRegionDirectory || - null === $this->fileLockRegionDirectory + $this->fileLockRegionDirectory === '' || + $this->fileLockRegionDirectory === null ) { - throw new \LogicException( + throw new LogicException( '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, DefaultCacheFactory#setFileLockRegionDirectory(). ' ); @@ -235,13 +216,13 @@ private function createRegionCache($name) { $cacheAdapter = clone $this->cache; - if (!$cacheAdapter instanceof CacheProvider) { + if (! $cacheAdapter instanceof CacheProvider) { return $cacheAdapter; } $namespace = $cacheAdapter->getNamespace(); - if ('' !== $namespace) { + if ($namespace !== '') { $namespace .= ':'; } diff --git a/lib/Doctrine/ORM/Cache/DefaultCollectionHydrator.php b/lib/Doctrine/ORM/Cache/DefaultCollectionHydrator.php index f12ccf50a78..b7c39209598 100644 --- a/lib/Doctrine/ORM/Cache/DefaultCollectionHydrator.php +++ b/lib/Doctrine/ORM/Cache/DefaultCollectionHydrator.php @@ -20,36 +20,32 @@ namespace Doctrine\ORM\Cache; -use Doctrine\ORM\Query; -use Doctrine\ORM\PersistentCollection; -use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Cache\Persister\CachedPersister; use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\PersistentCollection; +use Doctrine\ORM\Query; +use Doctrine\ORM\UnitOfWork; + +use function array_walk; +use function assert; /** * Default hydrator cache for collections - * - * @since 2.5 - * @author Fabio B. Silva */ class DefaultCollectionHydrator implements CollectionHydrator { - /** - * @var \Doctrine\ORM\EntityManagerInterface - */ + /** @var EntityManagerInterface */ private $em; - /** - * @var \Doctrine\ORM\UnitOfWork - */ + /** @var UnitOfWork */ private $uow; - /** - * @var array - */ + /** @var array */ private static $hints = [Query::HINT_CACHE_ENABLED => true]; /** - * @param \Doctrine\ORM\EntityManagerInterface $em The entity manager. + * @param EntityManagerInterface $em The entity manager. */ public function __construct(EntityManagerInterface $em) { @@ -77,10 +73,10 @@ public function buildCacheEntry(ClassMetadata $metadata, CollectionCacheKey $key 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']); - $targetRegion = $targetPersister->getCacheRegion(); - $list = []; + assert($targetPersister instanceof CachedPersister); + $targetRegion = $targetPersister->getCacheRegion(); + $list = []; $entityEntries = $targetRegion->getMultiple($entry); @@ -88,12 +84,12 @@ public function loadCacheEntry(ClassMetadata $metadata, CollectionCacheKey $key, return null; } - /* @var $entityEntries \Doctrine\ORM\Cache\EntityCacheEntry[] */ + /** @var EntityCacheEntry[] $entityEntries */ foreach ($entityEntries as $index => $entityEntry) { $list[$index] = $this->uow->createEntity($entityEntry->class, $entityEntry->resolveAssociationEntries($this->em), self::$hints); } - array_walk($list, function($entity, $index) use ($collection) { + array_walk($list, static function ($entity, $index) use ($collection) { $collection->hydrateSet($index, $entity); }); diff --git a/lib/Doctrine/ORM/Cache/DefaultEntityHydrator.php b/lib/Doctrine/ORM/Cache/DefaultEntityHydrator.php index 62f76205ed3..78be12e3b01 100644 --- a/lib/Doctrine/ORM/Cache/DefaultEntityHydrator.php +++ b/lib/Doctrine/ORM/Cache/DefaultEntityHydrator.php @@ -21,49 +21,45 @@ namespace Doctrine\ORM\Cache; use Doctrine\Common\Util\ClassUtils; - -use Doctrine\ORM\Query; -use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Query; +use Doctrine\ORM\UnitOfWork; use Doctrine\ORM\Utility\IdentifierFlattener; +use function array_merge; +use function is_array; +use function is_object; +use function reset; + /** * Default hydrator cache for entities - * - * @since 2.5 - * @author Fabio B. Silva */ class DefaultEntityHydrator implements EntityHydrator { - /** - * @var \Doctrine\ORM\EntityManagerInterface - */ + /** @var EntityManagerInterface */ private $em; - /** - * @var \Doctrine\ORM\UnitOfWork - */ + /** @var UnitOfWork */ private $uow; /** * The IdentifierFlattener used for manipulating identifiers * - * @var \Doctrine\ORM\Utility\IdentifierFlattener + * @var IdentifierFlattener */ private $identifierFlattener; - /** - * @var array - */ + /** @var array */ private static $hints = [Query::HINT_CACHE_ENABLED => true]; /** - * @param \Doctrine\ORM\EntityManagerInterface $em The entity manager. + * @param EntityManagerInterface $em The entity manager. */ public function __construct(EntityManagerInterface $em) { - $this->em = $em; - $this->uow = $em->getUnitOfWork(); + $this->em = $em; + $this->uow = $em->getUnitOfWork(); $this->identifierFlattener = new IdentifierFlattener($em->getUnitOfWork(), $em->getMetadataFactory()); } @@ -80,19 +76,19 @@ public function buildCacheEntry(ClassMetadata $metadata, EntityCacheKey $key, $e } foreach ($metadata->associationMappings as $name => $assoc) { - if ( ! isset($data[$name])) { + if (! isset($data[$name])) { continue; } - if ( ! ($assoc['type'] & ClassMetadata::TO_ONE)) { + if (! ($assoc['type'] & ClassMetadata::TO_ONE)) { unset($data[$name]); continue; } - if ( ! isset($assoc['cache'])) { + if (! isset($assoc['cache'])) { $targetClassMetadata = $this->em->getClassMetadata($assoc['targetEntity']); - $owningAssociation = ( ! $assoc['isOwningSide']) + $owningAssociation = ! $assoc['isOwningSide'] ? $targetClassMetadata->associationMappings[$assoc['mappedBy']] : $assoc; $associationIds = $this->identifierFlattener->flattenIdentifier( @@ -113,7 +109,7 @@ public function buildCacheEntry(ClassMetadata $metadata, EntityCacheKey $key, $e $targetAssoc = $targetClassMetadata->associationMappings[$fieldName]; - foreach($assoc['targetToSourceKeyColumns'] as $referencedColumn => $localColumn) { + foreach ($assoc['targetToSourceKeyColumns'] as $referencedColumn => $localColumn) { if (isset($targetAssoc['sourceToTargetKeyColumns'][$referencedColumn])) { $data[$localColumn] = $fieldValue; } @@ -123,7 +119,7 @@ public function buildCacheEntry(ClassMetadata $metadata, EntityCacheKey $key, $e continue; } - if ( ! isset($assoc['id'])) { + if (! isset($assoc['id'])) { $targetClass = ClassUtils::getClass($data[$name]); $targetId = $this->uow->getEntityIdentifier($data[$name]); $data[$name] = new AssociationCacheEntry($targetClass, $targetId); @@ -138,7 +134,7 @@ public function buildCacheEntry(ClassMetadata $metadata, EntityCacheKey $key, $e // @TODO - fix it ! // handle UnitOfWork#createEntity hash generation - if ( ! is_array($targetId)) { + if (! is_array($targetId)) { $data[reset($assoc['joinColumnFieldNames'])] = $targetId; $targetEntity = $this->em->getClassMetadata($assoc['targetEntity']); @@ -160,20 +156,20 @@ public function loadCacheEntry(ClassMetadata $metadata, EntityCacheKey $key, Ent $hints = self::$hints; if ($entity !== null) { - $hints[Query::HINT_REFRESH] = true; - $hints[Query::HINT_REFRESH_ENTITY] = $entity; + $hints[Query::HINT_REFRESH] = true; + $hints[Query::HINT_REFRESH_ENTITY] = $entity; } foreach ($metadata->associationMappings as $name => $assoc) { - if ( ! isset($assoc['cache']) || ! isset($data[$name])) { + if (! isset($assoc['cache']) || ! isset($data[$name])) { continue; } - $assocClass = $data[$name]->class; - $assocId = $data[$name]->identifier; - $isEagerLoad = ($assoc['fetch'] === ClassMetadata::FETCH_EAGER || ($assoc['type'] === ClassMetadata::ONE_TO_ONE && ! $assoc['isOwningSide'])); + $assocClass = $data[$name]->class; + $assocId = $data[$name]->identifier; + $isEagerLoad = ($assoc['fetch'] === ClassMetadata::FETCH_EAGER || ($assoc['type'] === ClassMetadata::ONE_TO_ONE && ! $assoc['isOwningSide'])); - if ( ! $isEagerLoad) { + if (! $isEagerLoad) { $data[$name] = $this->em->getReference($assocClass, $assocId); continue; diff --git a/lib/Doctrine/ORM/Cache/DefaultQueryCache.php b/lib/Doctrine/ORM/Cache/DefaultQueryCache.php index b65e934a20c..1760c2a0076 100644 --- a/lib/Doctrine/ORM/Cache/DefaultQueryCache.php +++ b/lib/Doctrine/ORM/Cache/DefaultQueryCache.php @@ -21,68 +21,63 @@ namespace Doctrine\ORM\Cache; use Doctrine\Common\Collections\ArrayCollection; -use Doctrine\ORM\Cache\Persister\CachedPersister; +use Doctrine\Common\Proxy\Proxy; +use Doctrine\ORM\Cache; +use Doctrine\ORM\Cache\Logging\CacheLogger; use Doctrine\ORM\Cache\Persister\Entity\CachedEntityPersister; use Doctrine\ORM\EntityManagerInterface; -use Doctrine\ORM\Query\ResultSetMapping; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\PersistentCollection; -use Doctrine\Common\Proxy\Proxy; -use Doctrine\ORM\Cache; use Doctrine\ORM\Query; +use Doctrine\ORM\Query\ResultSetMapping; +use Doctrine\ORM\UnitOfWork; + +use function array_key_exists; +use function array_map; +use function array_shift; +use function array_unshift; use function assert; +use function count; +use function is_array; +use function key; +use function reset; /** * Default query cache implementation. - * - * @since 2.5 - * @author Fabio B. Silva */ class DefaultQueryCache implements QueryCache { - /** - * @var \Doctrine\ORM\EntityManagerInterface - */ + /** @var EntityManagerInterface */ private $em; - /** - * @var \Doctrine\ORM\UnitOfWork - */ + /** @var UnitOfWork */ private $uow; - /** - * @var \Doctrine\ORM\Cache\Region - */ + /** @var Region */ private $region; - /** - * @var \Doctrine\ORM\Cache\QueryCacheValidator - */ + /** @var QueryCacheValidator */ private $validator; - /** - * @var \Doctrine\ORM\Cache\Logging\CacheLogger - */ + /** @var CacheLogger */ protected $cacheLogger; - /** - * @var array - */ + /** @var array */ private static $hints = [Query::HINT_CACHE_ENABLED => true]; /** - * @param \Doctrine\ORM\EntityManagerInterface $em The entity manager. - * @param \Doctrine\ORM\Cache\Region $region The query region. + * @param EntityManagerInterface $em The entity manager. + * @param Region $region The query region. */ public function __construct(EntityManagerInterface $em, Region $region) { $cacheConfig = $em->getConfiguration()->getSecondLevelCacheConfiguration(); - $this->em = $em; - $this->region = $region; - $this->uow = $em->getUnitOfWork(); - $this->cacheLogger = $cacheConfig->getCacheLogger(); - $this->validator = $cacheConfig->getQueryValidator(); + $this->em = $em; + $this->region = $region; + $this->uow = $em->getUnitOfWork(); + $this->cacheLogger = $cacheConfig->getCacheLogger(); + $this->validator = $cacheConfig->getQueryValidator(); } /** @@ -90,17 +85,17 @@ public function __construct(EntityManagerInterface $em, Region $region) */ public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = []) { - if ( ! ($key->cacheMode & Cache::MODE_GET)) { + if (! ($key->cacheMode & Cache::MODE_GET)) { return null; } $cacheEntry = $this->region->get($key); - if ( ! $cacheEntry instanceof QueryCacheEntry) { + if (! $cacheEntry instanceof QueryCacheEntry) { return null; } - if ( ! $this->validator->isValid($key, $cacheEntry)) { + if (! $this->validator->isValid($key, $cacheEntry)) { $this->region->evict($key); return null; @@ -117,7 +112,7 @@ public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = [] $cm = $this->em->getClassMetadata($entityName); - $generateKeys = static function (array $entry) use ($cm) : EntityCacheKey { + $generateKeys = static function (array $entry) use ($cm): EntityCacheKey { return new EntityCacheKey($cm->rootEntityName, $entry['identifier']); }; @@ -140,8 +135,8 @@ public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = [] $this->cacheLogger->entityCacheHit($regionName, $cacheKeys->identifiers[$index]); } - if ( ! $hasRelation) { - $result[$index] = $this->uow->createEntity($entityEntry->class, $entityEntry->resolveAssociationEntries($this->em), self::$hints); + if (! $hasRelation) { + $result[$index] = $this->uow->createEntity($entityEntry->class, $entityEntry->resolveAssociationEntries($this->em), self::$hints); continue; } @@ -156,9 +151,7 @@ public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = [] $assocMetadata = $this->em->getClassMetadata($assoc['targetEntity']); if ($assoc['type'] & ClassMetadata::TO_ONE) { - if (($assocEntry = $assocRegion->get($assocKey = new EntityCacheKey($assocMetadata->rootEntityName, $assoc['identifier']))) === null) { - if ($this->cacheLogger !== null) { $this->cacheLogger->entityCacheMiss($assocRegion->getName(), $assocKey); } @@ -177,11 +170,11 @@ public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = [] continue; } - if ( ! isset($assoc['list']) || empty($assoc['list'])) { + if (! isset($assoc['list']) || empty($assoc['list'])) { continue; } - $generateKeys = function ($id) use ($assocMetadata): EntityCacheKey { + $generateKeys = static function ($id) use ($assocMetadata): EntityCacheKey { return new EntityCacheKey($assocMetadata->rootEntityName, $id); }; @@ -249,29 +242,29 @@ public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = [] public function put(QueryCacheKey $key, ResultSetMapping $rsm, $result, array $hints = []) { if ($rsm->scalarMappings) { - throw new CacheException("Second level cache does not support scalar results."); + throw new CacheException('Second level cache does not support scalar results.'); } if (count($rsm->entityMappings) > 1) { - throw new CacheException("Second level cache does not support multiple root entities."); + throw new CacheException('Second level cache does not support multiple root entities.'); } - if ( ! $rsm->isSelect) { - throw new CacheException("Second-level cache query supports only select statements."); + if (! $rsm->isSelect) { + throw new CacheException('Second-level cache query supports only select statements.'); } if (($hints[Query\SqlWalker::HINT_PARTIAL] ?? false) === true || ($hints[Query::HINT_FORCE_PARTIAL_LOAD] ?? false) === true) { - throw new CacheException("Second level cache does not support partial entities."); + throw new CacheException('Second level cache does not support partial entities.'); } - if ( ! ($key->cacheMode & Cache::MODE_PUT)) { + if (! ($key->cacheMode & Cache::MODE_PUT)) { return false; } - $data = []; - $entityName = reset($rsm->aliasMap); - $rootAlias = key($rsm->aliasMap); - $persister = $this->uow->getEntityPersister($entityName); + $data = []; + $entityName = reset($rsm->aliasMap); + $rootAlias = key($rsm->aliasMap); + $persister = $this->uow->getEntityPersister($entityName); if (! $persister instanceof CachedEntityPersister) { throw CacheException::nonCacheableEntity($entityName); @@ -288,7 +281,7 @@ public function put(QueryCacheKey $key, ResultSetMapping $rsm, $result, array $h if (($key->cacheMode & Cache::MODE_REFRESH) || ! $region->contains($entityKey)) { // Cancel put result if entity put fail - if ( ! $persister->storeEntityCache($entity, $entityKey)) { + if (! $persister->storeEntityCache($entity, $entityKey)) { return false; } } @@ -298,11 +291,11 @@ public function put(QueryCacheKey $key, ResultSetMapping $rsm, $result, array $h // @TODO - move to cache hydration components foreach ($rsm->relationMap as $alias => $name) { - $parentAlias = $rsm->parentAliasMap[$alias]; - $parentClass = $rsm->aliasMap[$parentAlias]; - $metadata = $this->em->getClassMetadata($parentClass); - $assoc = $metadata->associationMappings[$name]; - $assocValue = $this->getAssociationValue($rsm, $alias, $entity); + $parentAlias = $rsm->parentAliasMap[$alias]; + $parentClass = $rsm->aliasMap[$parentAlias]; + $metadata = $this->em->getClassMetadata($parentClass); + $assoc = $metadata->associationMappings[$name]; + $assocValue = $this->getAssociationValue($rsm, $alias, $entity); if ($assocValue === null) { continue; @@ -311,7 +304,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, $assoc, $assocValue)) === null) { return false; } @@ -321,7 +314,7 @@ public function put(QueryCacheKey $key, ResultSetMapping $rsm, $result, array $h } // store single nested association - if ( ! is_array($assocValue)) { + if (! is_array($assocValue)) { // Cancel put result if association put fail if ($this->storeAssociationCache($key, $assoc, $assocValue) === null) { return false; @@ -344,9 +337,8 @@ public function put(QueryCacheKey $key, ResultSetMapping $rsm, $result, array $h } /** - * @param \Doctrine\ORM\Cache\QueryCacheKey $key - * @param array $assoc - * @param mixed $assocValue + * @param array $assoc + * @param mixed $assocValue * * @return mixed[]|null * @@ -363,9 +355,9 @@ private function storeAssociationCache(QueryCacheKey $key, array $assoc, $assocV $assocIdentifier = $this->uow->getEntityIdentifier($assocValue); $entityKey = new EntityCacheKey($assocMetadata->rootEntityName, $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; } } @@ -373,7 +365,7 @@ private function storeAssociationCache(QueryCacheKey $key, array $assoc, $assocV return [ 'targetEntity' => $assocMetadata->rootEntityName, 'identifier' => $assocIdentifier, - 'type' => $assoc['type'] + 'type' => $assoc['type'], ]; } @@ -386,7 +378,7 @@ private function storeAssociationCache(QueryCacheKey $key, array $assoc, $assocV if (($key->cacheMode & Cache::MODE_REFRESH) || ! $assocRegion->contains($entityKey)) { // Entity put fail - if ( ! $assocPersister->storeEntityCache($assocItem, $entityKey)) { + if (! $assocPersister->storeEntityCache($assocItem, $entityKey)) { return null; } } @@ -402,9 +394,8 @@ private function storeAssociationCache(QueryCacheKey $key, array $assoc, $assocV } /** - * @param \Doctrine\ORM\Query\ResultSetMapping $rsm - * @param string $assocAlias - * @param object $entity + * @param string $assocAlias + * @param object $entity * * @return array|object */ @@ -420,9 +411,8 @@ private function getAssociationValue(ResultSetMapping $rsm, $assocAlias, $entity array_unshift($path, [ 'field' => $field, - 'class' => $class - ] - ); + 'class' => $class, + ]); $alias = $parent; } diff --git a/lib/Doctrine/ORM/Cache/EntityCacheEntry.php b/lib/Doctrine/ORM/Cache/EntityCacheEntry.php index 155618be984..81b00ff72c2 100644 --- a/lib/Doctrine/ORM/Cache/EntityCacheEntry.php +++ b/lib/Doctrine/ORM/Cache/EntityCacheEntry.php @@ -22,11 +22,10 @@ use Doctrine\ORM\EntityManagerInterface; +use function array_map; + /** * Entity cache entry - * - * @since 2.5 - * @author Fabio B. Silva */ class EntityCacheEntry implements CacheEntry { @@ -71,14 +70,12 @@ public static function __set_state(array $values) /** * Retrieves the entity data resolving cache entries * - * @param \Doctrine\ORM\EntityManagerInterface $em - * * @return array */ public function resolveAssociationEntries(EntityManagerInterface $em) { - return array_map(function($value) use ($em) { - if ( ! ($value instanceof AssociationCacheEntry)) { + return array_map(static function ($value) use ($em) { + if (! ($value instanceof AssociationCacheEntry)) { return $value; } diff --git a/lib/Doctrine/ORM/Cache/EntityCacheKey.php b/lib/Doctrine/ORM/Cache/EntityCacheKey.php index 281e610fa6c..ee2d1471f67 100644 --- a/lib/Doctrine/ORM/Cache/EntityCacheKey.php +++ b/lib/Doctrine/ORM/Cache/EntityCacheKey.php @@ -20,11 +20,13 @@ namespace Doctrine\ORM\Cache; +use function implode; +use function ksort; +use function str_replace; +use function strtolower; + /** * Defines entity classes roles to be stored in the cache region. - * - * @since 2.5 - * @author Fabio B. Silva */ class EntityCacheKey extends CacheKey { diff --git a/lib/Doctrine/ORM/Cache/EntityHydrator.php b/lib/Doctrine/ORM/Cache/EntityHydrator.php index 05a394da7b2..f8e64148bdc 100644 --- a/lib/Doctrine/ORM/Cache/EntityHydrator.php +++ b/lib/Doctrine/ORM/Cache/EntityHydrator.php @@ -24,26 +24,23 @@ /** * Hydrator cache entry for entities - * - * @since 2.5 - * @author Fabio B. Silva */ interface EntityHydrator { /** - * @param \Doctrine\ORM\Mapping\ClassMetadata $metadata The entity metadata. - * @param \Doctrine\ORM\Cache\EntityCacheKey $key The entity cache key. - * @param object $entity The entity. + * @param ClassMetadata $metadata The entity metadata. + * @param EntityCacheKey $key The entity cache key. + * @param object $entity The entity. * - * @return \Doctrine\ORM\Cache\EntityCacheEntry + * @return EntityCacheEntry */ public function buildCacheEntry(ClassMetadata $metadata, EntityCacheKey $key, $entity); /** - * @param \Doctrine\ORM\Mapping\ClassMetadata $metadata The entity metadata. - * @param \Doctrine\ORM\Cache\EntityCacheKey $key The entity cache key. - * @param \Doctrine\ORM\Cache\EntityCacheEntry $entry The entity cache entry. - * @param object $entity The entity to load the cache into. If not specified, a new entity is created. + * @param ClassMetadata $metadata The entity metadata. + * @param EntityCacheKey $key The entity cache key. + * @param EntityCacheEntry $entry The entity cache entry. + * @param object $entity The entity to load the cache into. If not specified, a new entity is created. */ public function loadCacheEntry(ClassMetadata $metadata, EntityCacheKey $key, EntityCacheEntry $entry, $entity = null); } diff --git a/lib/Doctrine/ORM/Cache/Lock.php b/lib/Doctrine/ORM/Cache/Lock.php index 60f7d6c9d7d..0f304463063 100644 --- a/lib/Doctrine/ORM/Cache/Lock.php +++ b/lib/Doctrine/ORM/Cache/Lock.php @@ -20,27 +20,23 @@ namespace Doctrine\ORM\Cache; +use function time; +use function uniqid; + /** * Cache Lock - * - * @since 2.5 - * @author Fabio B. Silva */ class Lock { - /** - * @var string - */ + /** @var string */ public $value; - /** - * @var integer - */ + /** @var int */ public $time; /** - * @param string $value - * @param integer $time + * @param string $value + * @param int $time */ public function __construct($value, $time = null) { @@ -49,7 +45,7 @@ public function __construct($value, $time = null) } /** - * @return \Doctrine\ORM\Cache\Lock + * @return Lock */ public static function createLockRead() { diff --git a/lib/Doctrine/ORM/Cache/LockException.php b/lib/Doctrine/ORM/Cache/LockException.php index d4c76240aa9..96d75139caf 100644 --- a/lib/Doctrine/ORM/Cache/LockException.php +++ b/lib/Doctrine/ORM/Cache/LockException.php @@ -22,11 +22,7 @@ /** * Lock exception for cache. - * - * @since 2.5 - * @author Fabio B. Silva */ class LockException extends CacheException { - } diff --git a/lib/Doctrine/ORM/Cache/Logging/CacheLogger.php b/lib/Doctrine/ORM/Cache/Logging/CacheLogger.php index bdae4eea8c5..ea2c4018092 100644 --- a/lib/Doctrine/ORM/Cache/Logging/CacheLogger.php +++ b/lib/Doctrine/ORM/Cache/Logging/CacheLogger.php @@ -26,81 +26,78 @@ /** * Interface for logging. - * - * @since 2.5 - * @author Fabio B. Silva */ interface CacheLogger { /** * Log an entity put into second level cache. * - * @param string $regionName The name of the cache region. - * @param \Doctrine\ORM\Cache\EntityCacheKey $key The cache key of the entity. + * @param string $regionName The name of the cache region. + * @param EntityCacheKey $key The cache key of the entity. */ public function entityCachePut($regionName, EntityCacheKey $key); /** * Log an entity get from second level cache resulted in a hit. * - * @param string $regionName The name of the cache region. - * @param \Doctrine\ORM\Cache\EntityCacheKey $key The cache key of the entity. + * @param string $regionName The name of the cache region. + * @param EntityCacheKey $key The cache key of the entity. */ public function entityCacheHit($regionName, EntityCacheKey $key); /** * Log an entity get from second level cache resulted in a miss. * - * @param string $regionName The name of the cache region. - * @param \Doctrine\ORM\Cache\EntityCacheKey $key The cache key of the entity. + * @param string $regionName The name of the cache region. + * @param EntityCacheKey $key The cache key of the entity. */ public function entityCacheMiss($regionName, EntityCacheKey $key); /** - * Log an entity put into second level cache. - * - * @param string $regionName The name of the cache region. - * @param \Doctrine\ORM\Cache\CollectionCacheKey $key The cache key of the collection. - */ + * Log an entity put into second level cache. + * + * @param string $regionName The name of the cache region. + * @param CollectionCacheKey $key The cache key of the collection. + */ public function collectionCachePut($regionName, CollectionCacheKey $key); /** * Log an entity get from second level cache resulted in a hit. * - * @param string $regionName The name of the cache region. - * @param \Doctrine\ORM\Cache\CollectionCacheKey $key The cache key of the collection. + * @param string $regionName The name of the cache region. + * @param CollectionCacheKey $key The cache key of the collection. */ public function collectionCacheHit($regionName, CollectionCacheKey $key); /** * Log an entity get from second level cache resulted in a miss. * - * @param string $regionName The name of the cache region. - * @param \Doctrine\ORM\Cache\CollectionCacheKey $key The cache key of the collection. + * @param string $regionName The name of the cache region. + * @param CollectionCacheKey $key The cache key of the collection. */ public function collectionCacheMiss($regionName, CollectionCacheKey $key); /** * Log a query put into the query cache. * - * @param string $regionName The name of the cache region. - * @param \Doctrine\ORM\Cache\QueryCacheKey $key The cache key of the query. + * @param string $regionName The name of the cache region. + * @param QueryCacheKey $key The cache key of the query. */ public function queryCachePut($regionName, QueryCacheKey $key); /** * Log a query get from the query cache resulted in a hit. * - * @param string $regionName The name of the cache region. - * @param \Doctrine\ORM\Cache\QueryCacheKey $key The cache key of the query. + * @param string $regionName The name of the cache region. + * @param QueryCacheKey $key The cache key of the query. */ public function queryCacheHit($regionName, QueryCacheKey $key); /** * Log a query get from the query cache resulted in a miss. * - * @param string $regionName The name of the cache region. - * @param \Doctrine\ORM\Cache\QueryCacheKey $key The cache key of the query. + * @param string $regionName The name of the cache region. + * @param QueryCacheKey $key The cache key of the query. */ public function queryCacheMiss($regionName, QueryCacheKey $key); } diff --git a/lib/Doctrine/ORM/Cache/Logging/CacheLoggerChain.php b/lib/Doctrine/ORM/Cache/Logging/CacheLoggerChain.php index 28a8125c972..3c62de1dc9b 100644 --- a/lib/Doctrine/ORM/Cache/Logging/CacheLoggerChain.php +++ b/lib/Doctrine/ORM/Cache/Logging/CacheLoggerChain.php @@ -26,20 +26,14 @@ /** * Cache logger chain - * - * @since 2.5 - * @author Fabio B. Silva */ class CacheLoggerChain implements CacheLogger { - /** - * @var array<\Doctrine\ORM\Cache\Logging\CacheLogger> - */ + /** @var array */ private $loggers = []; /** - * @param string $name - * @param \Doctrine\ORM\Cache\Logging\CacheLogger $logger + * @param string $name */ public function setLogger($name, CacheLogger $logger) { @@ -49,15 +43,15 @@ public function setLogger($name, CacheLogger $logger) /** * @param string $name * - * @return \Doctrine\ORM\Cache\Logging\CacheLogger|null + * @return CacheLogger|null */ public function getLogger($name) { - return isset($this->loggers[$name]) ? $this->loggers[$name] : null; + return $this->loggers[$name] ?? null; } /** - * @return array<\Doctrine\ORM\Cache\Logging\CacheLogger> + * @return array */ public function getLoggers() { diff --git a/lib/Doctrine/ORM/Cache/Logging/StatisticsCacheLogger.php b/lib/Doctrine/ORM/Cache/Logging/StatisticsCacheLogger.php index 8d73ff371d5..879c3eeb27f 100644 --- a/lib/Doctrine/ORM/Cache/Logging/StatisticsCacheLogger.php +++ b/lib/Doctrine/ORM/Cache/Logging/StatisticsCacheLogger.php @@ -24,27 +24,20 @@ use Doctrine\ORM\Cache\EntityCacheKey; use Doctrine\ORM\Cache\QueryCacheKey; +use function array_sum; + /** * Provide basic second level cache statistics. - * - * @since 2.5 - * @author Fabio B. Silva */ class StatisticsCacheLogger implements CacheLogger { - /** - * @var int[] - */ + /** @var int[] */ private $cacheMissCountMap = []; - /** - * @var int[] - */ + /** @var int[] */ private $cacheHitCountMap = []; - /** - * @var int[] - */ + /** @var int[] */ private $cachePutCountMap = []; /** @@ -146,7 +139,7 @@ public function queryCachePut($regionName, QueryCacheKey $key) */ public function getRegionHitCount($regionName) { - return isset($this->cacheHitCountMap[$regionName]) ? $this->cacheHitCountMap[$regionName] : 0; + return $this->cacheHitCountMap[$regionName] ?? 0; } /** @@ -158,7 +151,7 @@ public function getRegionHitCount($regionName) */ public function getRegionMissCount($regionName) { - return isset($this->cacheMissCountMap[$regionName]) ? $this->cacheMissCountMap[$regionName] : 0; + return $this->cacheMissCountMap[$regionName] ?? 0; } /** @@ -170,7 +163,7 @@ public function getRegionMissCount($regionName) */ public function getRegionPutCount($regionName) { - return isset($this->cachePutCountMap[$regionName]) ? $this->cachePutCountMap[$regionName] : 0; + return $this->cachePutCountMap[$regionName] ?? 0; } /** diff --git a/lib/Doctrine/ORM/Cache/MultiGetRegion.php b/lib/Doctrine/ORM/Cache/MultiGetRegion.php index be32b08f0fe..c73914ce914 100644 --- a/lib/Doctrine/ORM/Cache/MultiGetRegion.php +++ b/lib/Doctrine/ORM/Cache/MultiGetRegion.php @@ -24,9 +24,6 @@ * Defines a region that supports multi-get reading. * * With one method call we can get multiple items. - * - * @since 2.5 - * @author Asmir Mustafic */ interface MultiGetRegion { diff --git a/lib/Doctrine/ORM/Cache/Persister/CachedPersister.php b/lib/Doctrine/ORM/Cache/Persister/CachedPersister.php index 89afd32095f..f52926aa162 100644 --- a/lib/Doctrine/ORM/Cache/Persister/CachedPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/CachedPersister.php @@ -1,4 +1,5 @@ */ interface CachedPersister { @@ -40,7 +40,7 @@ public function afterTransactionRolledBack(); /** * Gets the The region access. * - * @return \Doctrine\ORM\Cache\Region + * @return Region */ public function getCacheRegion(); } diff --git a/lib/Doctrine/ORM/Cache/Persister/Collection/AbstractCollectionPersister.php b/lib/Doctrine/ORM/Cache/Persister/Collection/AbstractCollectionPersister.php index cad22555fe7..03675f59d18 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Collection/AbstractCollectionPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Collection/AbstractCollectionPersister.php @@ -21,99 +21,81 @@ namespace Doctrine\ORM\Cache\Persister\Collection; use Doctrine\Common\Collections\Criteria; -use Doctrine\ORM\Cache\EntityCacheKey; +use Doctrine\Common\Util\ClassUtils; use Doctrine\ORM\Cache\CollectionCacheKey; -use Doctrine\ORM\Cache\Persister\Entity\CachedEntityPersister; -use Doctrine\ORM\Persisters\Collection\CollectionPersister; -use Doctrine\ORM\PersistentCollection; -use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\Cache\CollectionHydrator; +use Doctrine\ORM\Cache\EntityCacheKey; +use Doctrine\ORM\Cache\Logging\CacheLogger; use Doctrine\ORM\Cache\Region; -use Doctrine\Common\Util\ClassUtils; +use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Mapping\ClassMetadataFactory; +use Doctrine\ORM\PersistentCollection; +use Doctrine\ORM\Persisters\Collection\CollectionPersister; +use Doctrine\ORM\UnitOfWork; + +use function array_values; +use function assert; +use function count; +use function is_array; -/** - * @author Fabio B. Silva - * @author Guilherme Blanco - * @since 2.5 - */ abstract class AbstractCollectionPersister implements CachedCollectionPersister { - /** - * @var \Doctrine\ORM\UnitOfWork - */ + /** @var UnitOfWork */ protected $uow; - /** - * @var \Doctrine\ORM\Mapping\ClassMetadataFactory - */ + /** @var ClassMetadataFactory */ protected $metadataFactory; - /** - * @var \Doctrine\ORM\Persisters\Collection\CollectionPersister - */ + /** @var CollectionPersister */ protected $persister; - /** - * @var \Doctrine\ORM\Mapping\ClassMetadata - */ + /** @var ClassMetadata */ protected $sourceEntity; - /** - * @var \Doctrine\ORM\Mapping\ClassMetadata - */ + /** @var ClassMetadata */ protected $targetEntity; - /** - * @var array - */ + /** @var array */ protected $association; - /** - * @var array - */ + /** @var array */ protected $queuedCache = []; - /** - * @var \Doctrine\ORM\Cache\Region - */ + /** @var Region */ protected $region; - /** - * @var string - */ + /** @var string */ protected $regionName; - /** - * @var \Doctrine\ORM\Cache\CollectionHydrator - */ + /** @var CollectionHydrator */ protected $hydrator; - /** - * @var \Doctrine\ORM\Cache\Logging\CacheLogger - */ + /** @var CacheLogger */ 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 array $association The association mapping. */ public function __construct(CollectionPersister $persister, Region $region, EntityManagerInterface $em, array $association) { - $configuration = $em->getConfiguration(); - $cacheConfig = $configuration->getSecondLevelCacheConfiguration(); - $cacheFactory = $cacheConfig->getCacheFactory(); - - $this->region = $region; - $this->persister = $persister; - $this->association = $association; - $this->regionName = $region->getName(); - $this->uow = $em->getUnitOfWork(); - $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']); + $configuration = $em->getConfiguration(); + $cacheConfig = $configuration->getSecondLevelCacheConfiguration(); + $cacheFactory = $cacheConfig->getCacheFactory(); + + $this->region = $region; + $this->persister = $persister; + $this->association = $association; + $this->regionName = $region->getName(); + $this->uow = $em->getUnitOfWork(); + $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']); } /** @@ -141,9 +123,6 @@ public function getTargetEntityMetadata() } /** - * @param \Doctrine\ORM\PersistentCollection $collection - * @param \Doctrine\ORM\Cache\CollectionCacheKey $key - * * @return object[]|null */ public function loadCollectionCache(PersistentCollection $collection, CollectionCacheKey $key) @@ -164,14 +143,14 @@ public function loadCollectionCache(PersistentCollection $collection, Collection */ public function storeCollectionCache(CollectionCacheKey $key, $elements) { - /* @var $targetPersister CachedEntityPersister */ + /** @var CachedEntityPersister $targetPersister */ $associationMapping = $this->sourceEntity->associationMappings[$key->association]; $targetPersister = $this->uow->getEntityPersister($this->targetEntity->rootEntityName); $targetRegion = $targetPersister->getCacheRegion(); $targetHydrator = $targetPersister->getEntityHydrator(); // Only preserve ordering if association configured it - if ( ! (isset($associationMapping['indexBy']) && $associationMapping['indexBy'])) { + if (! (isset($associationMapping['indexBy']) && $associationMapping['indexBy'])) { // Elements may be an array or a Collection $elements = array_values(is_array($elements) ? $elements : $elements->getValues()); } @@ -183,15 +162,15 @@ public function storeCollectionCache(CollectionCacheKey $key, $elements) continue; } - $class = $this->targetEntity; - $className = ClassUtils::getClass($elements[$index]); + $class = $this->targetEntity; + $className = ClassUtils::getClass($elements[$index]); if ($className !== $this->targetEntity->name) { $class = $this->metadataFactory->getMetadataFor($className); } - $entity = $elements[$index]; - $entityEntry = $targetHydrator->buildCacheEntry($class, $entityKey, $entity); + $entity = $elements[$index]; + $entityEntry = $targetHydrator->buildCacheEntry($class, $entityKey, $entity); $targetRegion->put($entityKey, $entityEntry); } @@ -261,8 +240,6 @@ public function loadCriteria(PersistentCollection $collection, Criteria $criteri /** * Clears cache entries related to the current collection - * - * @param PersistentCollection $collection */ protected function evictCollectionCache(PersistentCollection $collection) { @@ -285,10 +262,10 @@ protected function evictCollectionCache(PersistentCollection $collection) */ protected function evictElementCache($targetEntity, $element) { - /* @var $targetPersister CachedEntityPersister */ $targetPersister = $this->uow->getEntityPersister($targetEntity); - $targetRegion = $targetPersister->getCacheRegion(); - $key = new EntityCacheKey($targetEntity, $this->uow->getEntityIdentifier($element)); + assert($targetPersister instanceof CachedEntityPersister); + $targetRegion = $targetPersister->getCacheRegion(); + $key = new EntityCacheKey($targetEntity, $this->uow->getEntityIdentifier($element)); $targetRegion->evict($key); diff --git a/lib/Doctrine/ORM/Cache/Persister/Collection/CachedCollectionPersister.php b/lib/Doctrine/ORM/Cache/Persister/Collection/CachedCollectionPersister.php index 5722027c49d..67147024398 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Collection/CachedCollectionPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Collection/CachedCollectionPersister.php @@ -20,44 +20,39 @@ namespace Doctrine\ORM\Cache\Persister\Collection; +use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Cache\CollectionCacheKey; use Doctrine\ORM\Cache\Persister\CachedPersister; -use Doctrine\ORM\Persisters\Collection\CollectionPersister; +use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\PersistentCollection; +use Doctrine\ORM\Persisters\Collection\CollectionPersister; /** * Interface for second level cache collection persisters. - * - * @author Fabio B. Silva - * @since 2.5 */ interface CachedCollectionPersister extends CachedPersister, CollectionPersister { /** - * @return \Doctrine\ORM\Mapping\ClassMetadata + * @return ClassMetadata */ public function getSourceEntityMetadata(); /** - * @return \Doctrine\ORM\Mapping\ClassMetadata + * @return ClassMetadata */ public function getTargetEntityMetadata(); /** * Loads a collection from cache * - * @param \Doctrine\ORM\PersistentCollection $collection - * @param \Doctrine\ORM\Cache\CollectionCacheKey $key - * - * @return \Doctrine\ORM\PersistentCollection|null + * @return PersistentCollection|null */ public function loadCollectionCache(PersistentCollection $collection, CollectionCacheKey $key); /** * Stores a collection into cache * - * @param \Doctrine\ORM\Cache\CollectionCacheKey $key - * @param array|\Doctrine\Common\Collections\Collection $elements + * @param array|Collection $elements * * @return void */ diff --git a/lib/Doctrine/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersister.php b/lib/Doctrine/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersister.php index fbd46f6eafe..660e6f7fd5d 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersister.php @@ -23,10 +23,8 @@ use Doctrine\ORM\Cache\CollectionCacheKey; use Doctrine\ORM\PersistentCollection; -/** - * @author Fabio B. Silva - * @since 2.5 - */ +use function spl_object_hash; + class NonStrictReadWriteCachedCollectionPersister extends AbstractCollectionPersister { /** @@ -78,7 +76,7 @@ public function update(PersistentCollection $collection) $isInitialized = $collection->isInitialized(); $isDirty = $collection->isDirty(); - if ( ! $isInitialized && ! $isDirty) { + if (! $isInitialized && ! $isDirty) { return; } @@ -98,7 +96,7 @@ public function update(PersistentCollection $collection) $this->queuedCache['update'][spl_object_hash($collection)] = [ 'key' => $key, - 'list' => $collection + 'list' => $collection, ]; } } diff --git a/lib/Doctrine/ORM/Cache/Persister/Collection/ReadOnlyCachedCollectionPersister.php b/lib/Doctrine/ORM/Cache/Persister/Collection/ReadOnlyCachedCollectionPersister.php index dfc816c5ab9..25b380fa9f1 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Collection/ReadOnlyCachedCollectionPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Collection/ReadOnlyCachedCollectionPersister.php @@ -20,19 +20,15 @@ namespace Doctrine\ORM\Cache\Persister\Collection; -use Doctrine\ORM\PersistentCollection; -use Doctrine\ORM\Cache\CacheException; use Doctrine\Common\Util\ClassUtils; +use Doctrine\ORM\Cache\CacheException; +use Doctrine\ORM\PersistentCollection; -/** - * @author Fabio B. Silva - * @since 2.5 - */ class ReadOnlyCachedCollectionPersister extends NonStrictReadWriteCachedCollectionPersister { /** - * {@inheritdoc} - */ + * {@inheritdoc} + */ public function update(PersistentCollection $collection) { if ($collection->isDirty() && $collection->getSnapshot()) { diff --git a/lib/Doctrine/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersister.php b/lib/Doctrine/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersister.php index 74bb044451b..3ceea169855 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersister.php @@ -20,23 +20,21 @@ 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\PersistentCollection; +use Doctrine\ORM\Persisters\Collection\CollectionPersister; + +use function spl_object_hash; -/** - * @author Fabio B. Silva - * @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 array $association The association mapping. */ public function __construct(CollectionPersister $persister, ConcurrentRegion $region, EntityManagerInterface $em, array $association) { @@ -100,7 +98,7 @@ public function delete(PersistentCollection $collection) $this->queuedCache['delete'][spl_object_hash($collection)] = [ 'key' => $key, - 'lock' => $lock + 'lock' => $lock, ]; } @@ -112,7 +110,7 @@ public function update(PersistentCollection $collection) $isInitialized = $collection->isInitialized(); $isDirty = $collection->isDirty(); - if ( ! $isInitialized && ! $isDirty) { + if (! $isInitialized && ! $isDirty) { return; } @@ -128,7 +126,7 @@ public function update(PersistentCollection $collection) $this->queuedCache['update'][spl_object_hash($collection)] = [ 'key' => $key, - 'lock' => $lock + 'lock' => $lock, ]; } } diff --git a/lib/Doctrine/ORM/Cache/Persister/Entity/AbstractEntityPersister.php b/lib/Doctrine/ORM/Cache/Persister/Entity/AbstractEntityPersister.php index 555cde97127..7fcf4bd4cab 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Entity/AbstractEntityPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Entity/AbstractEntityPersister.php @@ -20,85 +20,65 @@ namespace Doctrine\ORM\Cache\Persister\Entity; +use Doctrine\Common\Collections\Criteria; +use Doctrine\Common\Util\ClassUtils; use Doctrine\ORM\Cache; -use Doctrine\ORM\Cache\Region; -use Doctrine\ORM\Cache\EntityCacheKey; use Doctrine\ORM\Cache\CollectionCacheKey; -use Doctrine\ORM\Cache\TimestampCacheKey; -use Doctrine\ORM\Cache\QueryCacheKey; +use Doctrine\ORM\Cache\EntityCacheKey; +use Doctrine\ORM\Cache\EntityHydrator; +use Doctrine\ORM\Cache\Logging\CacheLogger; use Doctrine\ORM\Cache\Persister\CachedPersister; +use Doctrine\ORM\Cache\QueryCacheKey; +use Doctrine\ORM\Cache\Region; +use Doctrine\ORM\Cache\TimestampCacheKey; +use Doctrine\ORM\Cache\TimestampRegion; +use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Mapping\ClassMetadataFactory; use Doctrine\ORM\PersistentCollection; -use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Persisters\Entity\EntityPersister; +use Doctrine\ORM\UnitOfWork; -use Doctrine\Common\Util\ClassUtils; -use Doctrine\Common\Collections\Criteria; +use function assert; +use function serialize; +use function sha1; -/** - * @author Fabio B. Silva - * @since 2.5 - */ abstract class AbstractEntityPersister implements CachedEntityPersister { - /** - * @var \Doctrine\ORM\UnitOfWork - */ + /** @var UnitOfWork */ protected $uow; - /** - * @var \Doctrine\ORM\Mapping\ClassMetadataFactory - */ + /** @var ClassMetadataFactory */ protected $metadataFactory; - /** - * @var \Doctrine\ORM\Persisters\Entity\EntityPersister - */ + /** @var EntityPersister */ protected $persister; - /** - * @var \Doctrine\ORM\Mapping\ClassMetadata - */ + /** @var ClassMetadata */ protected $class; - /** - * @var array - */ + /** @var array */ protected $queuedCache = []; - /** - * @var \Doctrine\ORM\Cache\Region - */ + /** @var Region */ protected $region; - /** - * @var \Doctrine\ORM\Cache\TimestampRegion - */ + /** @var TimestampRegion */ protected $timestampRegion; - /** - * @var \Doctrine\ORM\Cache\TimestampCacheKey - */ + /** @var TimestampCacheKey */ protected $timestampKey; - /** - * @var \Doctrine\ORM\Cache\EntityHydrator - */ + /** @var EntityHydrator */ protected $hydrator; - /** - * @var \Doctrine\ORM\Cache - */ + /** @var Cache */ protected $cache; - /** - * @var \Doctrine\ORM\Cache\Logging\CacheLogger - */ + /** @var CacheLogger */ protected $cacheLogger; - /** - * @var string - */ + /** @var string */ protected $regionName; /** @@ -109,28 +89,28 @@ abstract class AbstractEntityPersister implements CachedEntityPersister protected $joinedAssociations; /** - * @param \Doctrine\ORM\Persisters\Entity\EntityPersister $persister The entity persister to cache. - * @param \Doctrine\ORM\Cache\Region $region The entity cache region. - * @param \Doctrine\ORM\EntityManagerInterface $em The entity manager. - * @param \Doctrine\ORM\Mapping\ClassMetadata $class The entity metadata. + * @param EntityPersister $persister The entity persister to cache. + * @param Region $region The entity cache region. + * @param EntityManagerInterface $em The entity manager. + * @param ClassMetadata $class The entity metadata. */ public function __construct(EntityPersister $persister, Region $region, EntityManagerInterface $em, ClassMetadata $class) { - $configuration = $em->getConfiguration(); - $cacheConfig = $configuration->getSecondLevelCacheConfiguration(); - $cacheFactory = $cacheConfig->getCacheFactory(); + $configuration = $em->getConfiguration(); + $cacheConfig = $configuration->getSecondLevelCacheConfiguration(); + $cacheFactory = $cacheConfig->getCacheFactory(); - $this->class = $class; - $this->region = $region; - $this->persister = $persister; - $this->cache = $em->getCache(); - $this->regionName = $region->getName(); - $this->uow = $em->getUnitOfWork(); - $this->metadataFactory = $em->getMetadataFactory(); - $this->cacheLogger = $cacheConfig->getCacheLogger(); - $this->timestampRegion = $cacheFactory->getTimestampRegion(); - $this->hydrator = $cacheFactory->buildEntityHydrator($em, $class); - $this->timestampKey = new TimestampCacheKey($this->class->rootEntityName); + $this->class = $class; + $this->region = $region; + $this->persister = $persister; + $this->cache = $em->getCache(); + $this->regionName = $region->getName(); + $this->uow = $em->getUnitOfWork(); + $this->metadataFactory = $em->getMetadataFactory(); + $this->cacheLogger = $cacheConfig->getCacheLogger(); + $this->timestampRegion = $cacheFactory->getTimestampRegion(); + $this->hydrator = $cacheFactory->buildEntityHydrator($em, $class); + $this->timestampKey = new TimestampCacheKey($this->class->rootEntityName); } /** @@ -152,7 +132,7 @@ public function getInserts() /** * {@inheritdoc} */ - public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit = null, $offset = null, array $orderBy = null) + 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); } @@ -192,9 +172,9 @@ public function getSelectConditionStatementSQL($field, $value, $assoc = null, $c /** * {@inheritdoc} */ - public function exists($entity, Criteria $extraConditions = null) + public function exists($entity, ?Criteria $extraConditions = null) { - if (null === $extraConditions) { + if ($extraConditions === null) { $key = new EntityCacheKey($this->class->rootEntityName, $this->class->getIdentifierValues($entity)); if ($this->region->contains($key)) { @@ -214,7 +194,7 @@ public function getCacheRegion() } /** - * @return \Doctrine\ORM\Cache\EntityHydrator + * @return EntityHydrator */ public function getEntityHydrator() { @@ -226,8 +206,8 @@ public function getEntityHydrator() */ public function storeEntityCache($entity, EntityCacheKey $key) { - $class = $this->class; - $className = ClassUtils::getClass($entity); + $class = $this->class; + $className = ClassUtils::getClass($entity); if ($className !== $this->class->name) { $class = $this->metadataFactory->getMetadataFor($className); @@ -252,10 +232,11 @@ private function storeJoinedAssociations($entity) $associations = []; foreach ($this->class->associationMappings as $name => $assoc) { - if (isset($assoc['cache']) && + if ( + isset($assoc['cache']) && ($assoc['type'] & ClassMetadata::TO_ONE) && - ($assoc['fetch'] === ClassMetadata::FETCH_EAGER || ! $assoc['isOwningSide'])) { - + ($assoc['fetch'] === ClassMetadata::FETCH_EAGER || ! $assoc['isOwningSide']) + ) { $associations[] = $name; } } @@ -291,7 +272,7 @@ private function storeJoinedAssociations($entity) * * @return string */ - protected function getHash($query, $criteria, array $orderBy = null, $limit = null, $offset = null) + protected function getHash($query, $criteria, ?array $orderBy = null, $limit = null, $offset = null) { [$params] = $criteria instanceof Criteria ? $this->persister->expandCriteriaParameters($criteria) @@ -361,7 +342,7 @@ public function executeInserts() /** * {@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, $assoc = null, array $hints = [], $lockMode = null, $limit = null, ?array $orderBy = null) { if ($entity !== null || $assoc !== null || ! empty($hints) || $lockMode !== null) { return $this->persister->load($criteria, $entity, $assoc, $hints, $lockMode, $limit, $orderBy); @@ -405,7 +386,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 = null, $limit = null, $offset = null) { $query = $this->persister->getSelectSQL($criteria, null, null, $limit, $offset, $orderBy); $hash = $this->getHash($query, $criteria, null, null, null); @@ -469,8 +450,8 @@ public function loadById(array $identifier, $entity = null) return null; } - $class = $this->class; - $className = ClassUtils::getClass($entity); + $class = $this->class; + $className = ClassUtils::getClass($entity); if ($className !== $this->class->name) { $class = $this->metadataFactory->getMetadataFor($className); @@ -479,7 +460,7 @@ public function loadById(array $identifier, $entity = null) $cacheEntry = $this->hydrator->buildCacheEntry($class, $cacheKey, $entity); $cached = $this->region->put($cacheKey, $cacheEntry); - if ($cached && (null === $this->joinedAssociations || $this->joinedAssociations)) { + if ($cached && ($this->joinedAssociations === null || $this->joinedAssociations)) { $this->storeJoinedAssociations($entity); } @@ -549,7 +530,7 @@ public function loadManyToManyCollection(array $assoc, $sourceEntity, Persistent $persister = $this->uow->getCollectionPersister($assoc); $hasCache = ($persister instanceof CachedPersister); - if ( ! $hasCache) { + if (! $hasCache) { return $this->persister->loadManyToManyCollection($assoc, $sourceEntity, $collection); } @@ -584,7 +565,7 @@ public function loadOneToManyCollection(array $assoc, $sourceEntity, PersistentC $persister = $this->uow->getCollectionPersister($assoc); $hasCache = ($persister instanceof CachedPersister); - if ( ! $hasCache) { + if (! $hasCache) { return $this->persister->loadOneToManyCollection($assoc, $sourceEntity, $collection); } @@ -643,8 +624,8 @@ public function refresh(array $id, $entity, $lockMode = null) */ protected function buildCollectionCacheKey(array $association, $ownerId) { - /** @var ClassMetadata $metadata */ $metadata = $this->metadataFactory->getMetadataFor($association['sourceEntity']); + assert($metadata instanceof ClassMetadata); return new CollectionCacheKey($metadata->rootEntityName, $association['fieldName'], $ownerId); } diff --git a/lib/Doctrine/ORM/Cache/Persister/Entity/CachedEntityPersister.php b/lib/Doctrine/ORM/Cache/Persister/Entity/CachedEntityPersister.php index 89582700c63..d8d40dfc238 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Entity/CachedEntityPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Entity/CachedEntityPersister.php @@ -21,27 +21,24 @@ namespace Doctrine\ORM\Cache\Persister\Entity; use Doctrine\ORM\Cache\EntityCacheKey; +use Doctrine\ORM\Cache\EntityHydrator; use Doctrine\ORM\Cache\Persister\CachedPersister; use Doctrine\ORM\Persisters\Entity\EntityPersister; /** * Interface for second level cache entity persisters. - * - * @author Fabio B. Silva - * @since 2.5 */ interface CachedEntityPersister extends CachedPersister, EntityPersister { /** - * @return \Doctrine\ORM\Cache\EntityHydrator + * @return EntityHydrator */ public function getEntityHydrator(); /** - * @param object $entity - * @param \Doctrine\ORM\Cache\EntityCacheKey $key + * @param object $entity * - * @return boolean + * @return bool */ public function storeEntityCache($entity, EntityCacheKey $key); } diff --git a/lib/Doctrine/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersister.php b/lib/Doctrine/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersister.php index 4ced02192f6..c2b36c18d00 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersister.php @@ -22,12 +22,10 @@ use Doctrine\ORM\Cache\EntityCacheKey; +use function get_class; + /** * Specific non-strict read/write cached entity persister - * - * @author Fabio B. Silva - * @author Guilherme Blanco - * @since 2.5 */ class NonStrictReadWriteCachedEntityPersister extends AbstractEntityPersister { @@ -108,11 +106,11 @@ 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)); - $entry = $this->hydrator->buildCacheEntry($class, $key, $entity); - $cached = $this->region->put($key, $entry); - $isChanged = $isChanged ?: $cached; + $class = $this->metadataFactory->getMetadataFor(get_class($entity)); + $key = new EntityCacheKey($class->rootEntityName, $this->uow->getEntityIdentifier($entity)); + $entry = $this->hydrator->buildCacheEntry($class, $key, $entity); + $cached = $this->region->put($key, $entry); + $isChanged = $isChanged ?: $cached; if ($this->cacheLogger && $cached) { $this->cacheLogger->entityCachePut($this->regionName, $key); diff --git a/lib/Doctrine/ORM/Cache/Persister/Entity/ReadOnlyCachedEntityPersister.php b/lib/Doctrine/ORM/Cache/Persister/Entity/ReadOnlyCachedEntityPersister.php index ce93d7b0e61..19e760d02eb 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Entity/ReadOnlyCachedEntityPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Entity/ReadOnlyCachedEntityPersister.php @@ -20,14 +20,11 @@ namespace Doctrine\ORM\Cache\Persister\Entity; -use Doctrine\ORM\Cache\CacheException; use Doctrine\Common\Util\ClassUtils; +use Doctrine\ORM\Cache\CacheException; /** * Specific read-only region entity persister - * - * @author Fabio B. Silva - * @since 2.5 */ class ReadOnlyCachedEntityPersister extends NonStrictReadWriteCachedEntityPersister { diff --git a/lib/Doctrine/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersister.php b/lib/Doctrine/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersister.php index 79a4c8c3dad..96815d5f81a 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersister.php @@ -20,26 +20,22 @@ namespace Doctrine\ORM\Cache\Persister\Entity; -use Doctrine\ORM\Persisters\Entity\EntityPersister; -use Doctrine\ORM\Mapping\ClassMetadata; -use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Cache\ConcurrentRegion; use Doctrine\ORM\Cache\EntityCacheKey; +use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Persisters\Entity\EntityPersister; /** * Specific read-write entity persister - * - * @author Fabio B. Silva - * @author Guilherme Blanco - * @since 2.5 */ class ReadWriteCachedEntityPersister extends AbstractEntityPersister { /** - * @param \Doctrine\ORM\Persisters\Entity\EntityPersister $persister The entity persister to cache. - * @param \Doctrine\ORM\Cache\ConcurrentRegion $region The entity cache region. - * @param \Doctrine\ORM\EntityManagerInterface $em The entity manager. - * @param \Doctrine\ORM\Mapping\ClassMetadata $class The entity metadata. + * @param EntityPersister $persister The entity persister to cache. + * @param ConcurrentRegion $region The entity cache region. + * @param EntityManagerInterface $em The entity manager. + * @param ClassMetadata $class The entity metadata. */ public function __construct(EntityPersister $persister, ConcurrentRegion $region, EntityManagerInterface $em, ClassMetadata $class) { @@ -115,7 +111,7 @@ public function delete($entity) $this->queuedCache['delete'][] = [ 'lock' => $lock, - 'key' => $key + 'key' => $key, ]; return $deleted; @@ -137,7 +133,7 @@ public function update($entity) $this->queuedCache['update'][] = [ 'lock' => $lock, - 'key' => $key + 'key' => $key, ]; } } diff --git a/lib/Doctrine/ORM/Cache/QueryCache.php b/lib/Doctrine/ORM/Cache/QueryCache.php index de2496253b3..7aeb168c090 100644 --- a/lib/Doctrine/ORM/Cache/QueryCache.php +++ b/lib/Doctrine/ORM/Cache/QueryCache.php @@ -25,38 +25,31 @@ /** * Defines the contract for caches capable of storing query results. * These caches should only concern themselves with storing the matching result ids. - * - * @since 2.5 - * @author Fabio B. Silva */ interface QueryCache { /** - * @return boolean + * @return bool */ public function clear(); /** - * @param \Doctrine\ORM\Cache\QueryCacheKey $key - * @param \Doctrine\ORM\Query\ResultSetMapping $rsm - * @param mixed $result - * @param array $hints + * @param mixed $result + * @param array $hints * - * @return boolean + * @return bool */ public function put(QueryCacheKey $key, ResultSetMapping $rsm, $result, array $hints = []); /** - * @param \Doctrine\ORM\Cache\QueryCacheKey $key - * @param \Doctrine\ORM\Query\ResultSetMapping $rsm - * @param array $hints + * @param array $hints * * @return array|null */ public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = []); /** - * @return \Doctrine\ORM\Cache\Region + * @return Region */ public function getRegion(); } diff --git a/lib/Doctrine/ORM/Cache/QueryCacheEntry.php b/lib/Doctrine/ORM/Cache/QueryCacheEntry.php index b6af393fde1..cc4c964d6f0 100644 --- a/lib/Doctrine/ORM/Cache/QueryCacheEntry.php +++ b/lib/Doctrine/ORM/Cache/QueryCacheEntry.php @@ -20,11 +20,10 @@ namespace Doctrine\ORM\Cache; +use function microtime; + /** * Query cache entry - * - * @since 2.5 - * @author Fabio B. Silva */ class QueryCacheEntry implements CacheEntry { diff --git a/lib/Doctrine/ORM/Cache/QueryCacheKey.php b/lib/Doctrine/ORM/Cache/QueryCacheKey.php index 0e072a36fc0..b82af60f84b 100644 --- a/lib/Doctrine/ORM/Cache/QueryCacheKey.php +++ b/lib/Doctrine/ORM/Cache/QueryCacheKey.php @@ -24,23 +24,20 @@ /** * A cache key that identifies a particular query. - * - * @since 2.5 - * @author Fabio B. Silva */ class QueryCacheKey extends CacheKey { /** * READ-ONLY: Public only for performance reasons, it should be considered immutable. * - * @var integer Cache key lifetime + * @var int Cache key lifetime */ public $lifetime; /** * READ-ONLY: Public only for performance reasons, it should be considered immutable. * - * @var integer Cache mode (Doctrine\ORM\Cache::MODE_*) + * @var int Cache mode (Doctrine\ORM\Cache::MODE_*) */ public $cacheMode; @@ -52,16 +49,15 @@ class QueryCacheKey extends CacheKey public $timestampKey; /** - * @param string $hash Result cache id - * @param integer $lifetime Query lifetime - * @param int $cacheMode Query cache mode - * @param TimestampCacheKey|null $timestampKey + * @param string $hash Result cache id + * @param int $lifetime Query lifetime + * @param int $cacheMode Query cache mode */ public function __construct( $hash, $lifetime = 0, $cacheMode = Cache::MODE_NORMAL, - TimestampCacheKey $timestampKey = null + ?TimestampCacheKey $timestampKey = null ) { $this->hash = $hash; $this->lifetime = $lifetime; diff --git a/lib/Doctrine/ORM/Cache/QueryCacheValidator.php b/lib/Doctrine/ORM/Cache/QueryCacheValidator.php index 682a41ec4fa..737b8bf1b74 100644 --- a/lib/Doctrine/ORM/Cache/QueryCacheValidator.php +++ b/lib/Doctrine/ORM/Cache/QueryCacheValidator.php @@ -22,19 +22,13 @@ /** * Cache query validator interface. - * - * @since 2.5 - * @author Fabio B. Silva */ interface QueryCacheValidator { /** * Checks if the query entry is valid * - * @param \Doctrine\ORM\Cache\QueryCacheKey $key - * @param \Doctrine\ORM\Cache\QueryCacheEntry $entry - * - * @return boolean + * @return bool */ public function isValid(QueryCacheKey $key, QueryCacheEntry $entry); } diff --git a/lib/Doctrine/ORM/Cache/Region.php b/lib/Doctrine/ORM/Cache/Region.php index 3bffbbce747..59bb5598711 100644 --- a/lib/Doctrine/ORM/Cache/Region.php +++ b/lib/Doctrine/ORM/Cache/Region.php @@ -22,9 +22,6 @@ /** * Defines a contract for accessing a particular named region. - * - * @since 2.5 - * @author Fabio B. Silva */ interface Region extends MultiGetRegion { @@ -38,47 +35,47 @@ public function getName(); /** * Determine whether this region contains data for the given key. * - * @param \Doctrine\ORM\Cache\CacheKey $key The cache key + * @param CacheKey $key The cache key * - * @return boolean TRUE if the underlying cache contains corresponding data; FALSE otherwise. + * @return bool TRUE if the underlying cache contains corresponding data; FALSE otherwise. */ public function contains(CacheKey $key); /** * Get an item from the cache. * - * @param \Doctrine\ORM\Cache\CacheKey $key The key of the item to be retrieved. + * @param CacheKey $key The key of the item to be retrieved. * - * @return \Doctrine\ORM\Cache\CacheEntry|null The cached entry or NULL + * @return CacheEntry|null The cached entry or NULL * - * @throws \Doctrine\ORM\Cache\CacheException Indicates a problem accessing the item or region. + * @throws CacheException Indicates a problem accessing the item or region. */ public function get(CacheKey $key); /** * Put an item into the cache. * - * @param \Doctrine\ORM\Cache\CacheKey $key The key under which to cache the item. - * @param \Doctrine\ORM\Cache\CacheEntry $entry The entry to cache. - * @param \Doctrine\ORM\Cache\Lock $lock The lock previously obtained. + * @param CacheKey $key The key under which to cache the item. + * @param CacheEntry $entry The entry to cache. + * @param Lock $lock The lock previously obtained. * - * @throws \Doctrine\ORM\Cache\CacheException Indicates a problem accessing the region. + * @throws CacheException Indicates a problem accessing the region. */ - public function put(CacheKey $key, CacheEntry $entry, Lock $lock = null); + public function put(CacheKey $key, CacheEntry $entry, ?Lock $lock = null); /** * Remove an item from the cache. * - * @param \Doctrine\ORM\Cache\CacheKey $key The key under which to cache the item. + * @param CacheKey $key The key under which to cache the item. * - * @throws \Doctrine\ORM\Cache\CacheException Indicates a problem accessing the region. + * @throws CacheException Indicates a problem accessing the region. */ public function evict(CacheKey $key); /** * Remove all contents of this particular cache region. * - * @throws \Doctrine\ORM\Cache\CacheException Indicates problem accessing the region. + * @throws CacheException Indicates problem accessing the region. */ public function evictAll(); } diff --git a/lib/Doctrine/ORM/Cache/Region/DefaultMultiGetRegion.php b/lib/Doctrine/ORM/Cache/Region/DefaultMultiGetRegion.php index 7b5f28ecf33..61ae0de8733 100644 --- a/lib/Doctrine/ORM/Cache/Region/DefaultMultiGetRegion.php +++ b/lib/Doctrine/ORM/Cache/Region/DefaultMultiGetRegion.php @@ -20,15 +20,15 @@ namespace Doctrine\ORM\Cache\Region; +use Doctrine\Common\Cache\Cache; use Doctrine\Common\Cache\MultiGetCache; use Doctrine\ORM\Cache\CacheEntry; use Doctrine\ORM\Cache\CollectionCacheEntry; +use function count; + /** * A cache region that enables the retrieval of multiple elements with one call - * - * @since 2.5 - * @author Asmir Mustafic */ class DefaultMultiGetRegion extends DefaultRegion { @@ -36,7 +36,7 @@ class DefaultMultiGetRegion extends DefaultRegion * Note that the multiple type is due to doctrine/cache not integrating the MultiGetCache interface * in its signature due to BC in 1.x * - * @var MultiGetCache|\Doctrine\Common\Cache\Cache + * @var MultiGetCache|Cache */ protected $cache; @@ -47,7 +47,7 @@ class DefaultMultiGetRegion extends DefaultRegion */ public function __construct($name, MultiGetCache $cache, $lifetime = 0) { - /* @var $cache \Doctrine\Common\Cache\Cache */ + /** @var Cache $cache */ parent::__construct($name, $cache, $lifetime); } diff --git a/lib/Doctrine/ORM/Cache/Region/DefaultRegion.php b/lib/Doctrine/ORM/Cache/Region/DefaultRegion.php index ab069cefb52..ad87c381f48 100644 --- a/lib/Doctrine/ORM/Cache/Region/DefaultRegion.php +++ b/lib/Doctrine/ORM/Cache/Region/DefaultRegion.php @@ -20,7 +20,9 @@ namespace Doctrine\ORM\Cache\Region; +use BadMethodCallException; use Doctrine\Common\Cache\Cache as CacheAdapter; +use Doctrine\Common\Cache\CacheProvider; use Doctrine\Common\Cache\ClearableCache; use Doctrine\ORM\Cache\CacheEntry; use Doctrine\ORM\Cache\CacheKey; @@ -28,41 +30,34 @@ use Doctrine\ORM\Cache\Lock; use Doctrine\ORM\Cache\Region; +use function get_class; +use function sprintf; + /** * The simplest cache region compatible with all doctrine-cache drivers. - * - * @since 2.5 - * @author Fabio B. Silva */ class DefaultRegion implements Region { - const REGION_KEY_SEPARATOR = '_'; + public const REGION_KEY_SEPARATOR = '_'; - /** - * @var CacheAdapter - */ + /** @var CacheAdapter */ protected $cache; - /** - * @var string - */ + /** @var string */ protected $name; - /** - * @var integer - */ + /** @var int */ protected $lifetime = 0; /** - * @param string $name - * @param CacheAdapter $cache - * @param integer $lifetime + * @param string $name + * @param int $lifetime */ public function __construct($name, CacheAdapter $cache, $lifetime = 0) { $this->cache = $cache; $this->name = (string) $name; - $this->lifetime = (integer) $lifetime; + $this->lifetime = (int) $lifetime; } /** @@ -74,7 +69,7 @@ public function getName() } /** - * @return \Doctrine\Common\Cache\CacheProvider + * @return CacheProvider */ public function getCache() { @@ -125,7 +120,6 @@ public function getMultiple(CollectionCacheEntry $collection) } /** - * @param CacheKey $key * @return string */ protected function getCacheEntryKey(CacheKey $key) @@ -136,7 +130,7 @@ protected function getCacheEntryKey(CacheKey $key) /** * {@inheritdoc} */ - public function put(CacheKey $key, CacheEntry $entry, Lock $lock = null) + public function put(CacheKey $key, CacheEntry $entry, ?Lock $lock = null) { return $this->cache->save($this->getCacheEntryKey($key), $entry, $this->lifetime); } @@ -155,7 +149,7 @@ public function evict(CacheKey $key) public function evictAll() { if (! $this->cache instanceof ClearableCache) { - throw new \BadMethodCallException(sprintf( + throw new BadMethodCallException(sprintf( 'Clearing all cache entries is not supported by the supplied cache adapter of type %s', get_class($this->cache) )); diff --git a/lib/Doctrine/ORM/Cache/Region/FileLockRegion.php b/lib/Doctrine/ORM/Cache/Region/FileLockRegion.php index db605cc26d9..cd4111540d2 100644 --- a/lib/Doctrine/ORM/Cache/Region/FileLockRegion.php +++ b/lib/Doctrine/ORM/Cache/Region/FileLockRegion.php @@ -20,31 +20,45 @@ namespace Doctrine\ORM\Cache\Region; +use Doctrine\ORM\Cache\CacheEntry; +use Doctrine\ORM\Cache\CacheKey; use Doctrine\ORM\Cache\CollectionCacheEntry; +use Doctrine\ORM\Cache\ConcurrentRegion; use Doctrine\ORM\Cache\Lock; use Doctrine\ORM\Cache\Region; -use Doctrine\ORM\Cache\CacheKey; -use Doctrine\ORM\Cache\CacheEntry; -use Doctrine\ORM\Cache\ConcurrentRegion; +use InvalidArgumentException; + +use function array_filter; +use function array_map; +use function chmod; +use function file_get_contents; +use function file_put_contents; +use function fileatime; +use function glob; +use function is_dir; +use function is_file; +use function is_writable; +use function mkdir; +use function sprintf; +use function time; +use function unlink; + +use const DIRECTORY_SEPARATOR; +use const LOCK_EX; /** * Very naive concurrent region, based on file locks. - * - * @since 2.5 - * @author Fabio B. Silva */ class FileLockRegion implements ConcurrentRegion { - const LOCK_EXTENSION = 'lock'; + public const LOCK_EXTENSION = 'lock'; /** * var \Doctrine\ORM\Cache\Region */ private $region; - /** - * @var string - */ + /** @var string */ private $directory; /** @@ -53,20 +67,19 @@ class FileLockRegion implements ConcurrentRegion private $lockLifetime; /** - * @param \Doctrine\ORM\Cache\Region $region - * @param string $directory - * @param string $lockLifetime + * @param string $directory + * @param string $lockLifetime * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public function __construct(Region $region, $directory, $lockLifetime) { - if ( ! is_dir($directory) && ! @mkdir($directory, 0775, true)) { - throw new \InvalidArgumentException(sprintf('The directory "%s" does not exist and could not be created.', $directory)); + if (! is_dir($directory) && ! @mkdir($directory, 0775, true)) { + throw new InvalidArgumentException(sprintf('The directory "%s" does not exist and could not be created.', $directory)); } - if ( ! is_writable($directory)) { - throw new \InvalidArgumentException(sprintf('The directory "%s" is not writable.', $directory)); + if (! is_writable($directory)) { + throw new InvalidArgumentException(sprintf('The directory "%s" is not writable.', $directory)); } $this->region = $region; @@ -75,23 +88,20 @@ public function __construct(Region $region, $directory, $lockLifetime) } /** - * @param \Doctrine\ORM\Cache\CacheKey $key - * @param \Doctrine\ORM\Cache\Lock $lock - * - * @return boolean + * @return bool */ - private function isLocked(CacheKey $key, Lock $lock = null) + private function isLocked(CacheKey $key, ?Lock $lock = null) { $filename = $this->getLockFileName($key); - if ( ! is_file($filename)) { + if (! is_file($filename)) { return false; } - $time = $this->getLockTime($filename); - $content = $this->getLockContent($filename); + $time = $this->getLockTime($filename); + $content = $this->getLockContent($filename); - if ( ! $content || ! $time) { + if (! $content || ! $time) { @unlink($filename); return false; @@ -102,7 +112,7 @@ private function isLocked(CacheKey $key, Lock $lock = null) } // outdated lock - if (($time + $this->lockLifetime) <= time()) { + if ($time + $this->lockLifetime <= time()) { @unlink($filename); return false; @@ -112,8 +122,6 @@ private function isLocked(CacheKey $key, Lock $lock = null) } /** - * @param \Doctrine\ORM\Cache\CacheKey $key - * * @return string */ private function getLockFileName(CacheKey $key) @@ -134,7 +142,7 @@ private function getLockContent($filename) /** * @param string $filename * - * @return integer + * @return int */ private function getLockTime($filename) { @@ -188,7 +196,7 @@ public function getMultiple(CollectionCacheEntry $collection) /** * {@inheritdoc} */ - public function put(CacheKey $key, CacheEntry $entry, Lock $lock = null) + public function put(CacheKey $key, CacheEntry $entry, ?Lock $lock = null) { if ($this->isLocked($key, $lock)) { return false; @@ -216,7 +224,7 @@ public function evictAll() { // The check below is necessary because on some platforms glob returns false // when nothing matched (even though no errors occurred) - $filenames = glob(sprintf("%s/*.%s" , $this->directory, self::LOCK_EXTENSION)); + $filenames = glob(sprintf('%s/*.%s', $this->directory, self::LOCK_EXTENSION)); if ($filenames) { foreach ($filenames as $filename) { @@ -239,9 +247,10 @@ public function lock(CacheKey $key) $lock = Lock::createLockRead(); $filename = $this->getLockFileName($key); - if ( ! @file_put_contents($filename, $lock->value, LOCK_EX)) { + if (! @file_put_contents($filename, $lock->value, LOCK_EX)) { return null; } + chmod($filename, 0664); return $lock; @@ -258,7 +267,7 @@ public function unlock(CacheKey $key, Lock $lock) return false; } - if ( ! @unlink($this->getLockFileName($key))) { + if (! @unlink($this->getLockFileName($key))) { return false; } diff --git a/lib/Doctrine/ORM/Cache/Region/UpdateTimestampCache.php b/lib/Doctrine/ORM/Cache/Region/UpdateTimestampCache.php index dfdf9062aa3..4bb867859f9 100644 --- a/lib/Doctrine/ORM/Cache/Region/UpdateTimestampCache.php +++ b/lib/Doctrine/ORM/Cache/Region/UpdateTimestampCache.php @@ -20,15 +20,12 @@ namespace Doctrine\ORM\Cache\Region; +use Doctrine\ORM\Cache\CacheKey; use Doctrine\ORM\Cache\TimestampCacheEntry; use Doctrine\ORM\Cache\TimestampRegion; -use Doctrine\ORM\Cache\CacheKey; /** * Tracks the timestamps of the most recent updates to particular keys. - * - * @since 2.5 - * @author Fabio B. Silva */ class UpdateTimestampCache extends DefaultRegion implements TimestampRegion { @@ -37,6 +34,6 @@ class UpdateTimestampCache extends DefaultRegion implements TimestampRegion */ public function update(CacheKey $key) { - $this->put($key, new TimestampCacheEntry); + $this->put($key, new TimestampCacheEntry()); } } diff --git a/lib/Doctrine/ORM/Cache/RegionsConfiguration.php b/lib/Doctrine/ORM/Cache/RegionsConfiguration.php index d79c5b1af28..0609ed1aa2f 100644 --- a/lib/Doctrine/ORM/Cache/RegionsConfiguration.php +++ b/lib/Doctrine/ORM/Cache/RegionsConfiguration.php @@ -22,44 +22,33 @@ /** * Cache regions configuration - * - * @since 2.5 - * @author Fabio B. Silva */ class RegionsConfiguration { - /** - * @var array - */ + /** @var array */ private $lifetimes = []; - /** - * @var array - */ + /** @var array */ private $lockLifetimes = []; - /** - * @var integer - */ + /** @var int */ private $defaultLifetime; - /** - * @var integer - */ + /** @var int */ private $defaultLockLifetime; /** - * @param integer $defaultLifetime - * @param integer $defaultLockLifetime + * @param int $defaultLifetime + * @param int $defaultLockLifetime */ public function __construct($defaultLifetime = 3600, $defaultLockLifetime = 60) { - $this->defaultLifetime = (integer) $defaultLifetime; - $this->defaultLockLifetime = (integer) $defaultLockLifetime; + $this->defaultLifetime = (int) $defaultLifetime; + $this->defaultLockLifetime = (int) $defaultLockLifetime; } /** - * @return integer + * @return int */ public function getDefaultLifetime() { @@ -67,15 +56,15 @@ public function getDefaultLifetime() } /** - * @param integer $defaultLifetime + * @param int $defaultLifetime */ public function setDefaultLifetime($defaultLifetime) { - $this->defaultLifetime = (integer) $defaultLifetime; + $this->defaultLifetime = (int) $defaultLifetime; } /** - * @return integer + * @return int */ public function getDefaultLockLifetime() { @@ -83,52 +72,48 @@ public function getDefaultLockLifetime() } /** - * @param integer $defaultLockLifetime + * @param int $defaultLockLifetime */ public function setDefaultLockLifetime($defaultLockLifetime) { - $this->defaultLockLifetime = (integer) $defaultLockLifetime; + $this->defaultLockLifetime = (int) $defaultLockLifetime; } /** * @param string $regionName * - * @return integer + * @return int */ public function getLifetime($regionName) { - return isset($this->lifetimes[$regionName]) - ? $this->lifetimes[$regionName] - : $this->defaultLifetime; + return $this->lifetimes[$regionName] ?? $this->defaultLifetime; } /** - * @param string $name - * @param integer $lifetime + * @param string $name + * @param int $lifetime */ public function setLifetime($name, $lifetime) { - $this->lifetimes[$name] = (integer) $lifetime; + $this->lifetimes[$name] = (int) $lifetime; } /** * @param string $regionName * - * @return integer + * @return int */ public function getLockLifetime($regionName) { - return isset($this->lockLifetimes[$regionName]) - ? $this->lockLifetimes[$regionName] - : $this->defaultLockLifetime; + return $this->lockLifetimes[$regionName] ?? $this->defaultLockLifetime; } /** - * @param string $name - * @param integer $lifetime + * @param string $name + * @param int $lifetime */ public function setLockLifetime($name, $lifetime) { - $this->lockLifetimes[$name] = (integer) $lifetime; + $this->lockLifetimes[$name] = (int) $lifetime; } } diff --git a/lib/Doctrine/ORM/Cache/TimestampCacheEntry.php b/lib/Doctrine/ORM/Cache/TimestampCacheEntry.php index 0b7ce0be6a0..f803429fe17 100644 --- a/lib/Doctrine/ORM/Cache/TimestampCacheEntry.php +++ b/lib/Doctrine/ORM/Cache/TimestampCacheEntry.php @@ -20,11 +20,10 @@ namespace Doctrine\ORM\Cache; +use function microtime; + /** * Timestamp cache entry - * - * @since 2.5 - * @author Fabio B. Silva */ class TimestampCacheEntry implements CacheEntry { diff --git a/lib/Doctrine/ORM/Cache/TimestampCacheKey.php b/lib/Doctrine/ORM/Cache/TimestampCacheKey.php index dfa72274b23..32511938ad9 100644 --- a/lib/Doctrine/ORM/Cache/TimestampCacheKey.php +++ b/lib/Doctrine/ORM/Cache/TimestampCacheKey.php @@ -22,9 +22,6 @@ /** * A key that identifies a timestamped space. - * - * @since 2.5 - * @author Fabio B. Silva */ class TimestampCacheKey extends CacheKey { diff --git a/lib/Doctrine/ORM/Cache/TimestampQueryCacheValidator.php b/lib/Doctrine/ORM/Cache/TimestampQueryCacheValidator.php index c6404d3b25d..196c4e1e0f2 100644 --- a/lib/Doctrine/ORM/Cache/TimestampQueryCacheValidator.php +++ b/lib/Doctrine/ORM/Cache/TimestampQueryCacheValidator.php @@ -20,20 +20,13 @@ namespace Doctrine\ORM\Cache; -/** - * @since 2.5 - * @author Fabio B. Silva - */ +use function microtime; + class TimestampQueryCacheValidator implements QueryCacheValidator { - /** - * @var TimestampRegion - */ + /** @var TimestampRegion */ private $timestampRegion; - /** - * @param TimestampRegion $timestampRegion - */ public function __construct(TimestampRegion $timestampRegion) { $this->timestampRegion = $timestampRegion; @@ -48,17 +41,14 @@ public function isValid(QueryCacheKey $key, QueryCacheEntry $entry) return false; } - if ($key->lifetime == 0) { + if ($key->lifetime === 0) { return true; } - return ($entry->time + $key->lifetime) > microtime(true); + return $entry->time + $key->lifetime > microtime(true); } /** - * @param QueryCacheKey $key - * @param QueryCacheEntry $entry - * * @return bool */ private function regionUpdated(QueryCacheKey $key, QueryCacheEntry $entry) diff --git a/lib/Doctrine/ORM/Cache/TimestampRegion.php b/lib/Doctrine/ORM/Cache/TimestampRegion.php index 9e0c25ca6ab..d835577a747 100644 --- a/lib/Doctrine/ORM/Cache/TimestampRegion.php +++ b/lib/Doctrine/ORM/Cache/TimestampRegion.php @@ -22,18 +22,15 @@ /** * Defines the contract for a cache region which will specifically be used to store entity "update timestamps". - * - * @since 2.5 - * @author Fabio B. Silva */ interface TimestampRegion extends Region { /** * Update an specific key into the cache region. * - * @param \Doctrine\ORM\Cache\CacheKey $key The key of the item to update the timestamp. + * @param CacheKey $key The key of the item to update the timestamp. * - * @throws \Doctrine\ORM\Cache\LockException Indicates a problem accessing the region. + * @throws LockException Indicates a problem accessing the region. */ public function update(CacheKey $key); } diff --git a/lib/Doctrine/ORM/Configuration.php b/lib/Doctrine/ORM/Configuration.php index 27684d997f0..dbb069f4a71 100644 --- a/lib/Doctrine/ORM/Configuration.php +++ b/lib/Doctrine/ORM/Configuration.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class Configuration extends \Doctrine\DBAL\Configuration { @@ -70,38 +68,36 @@ public function setProxyDir($dir) /** * Gets the directory where Doctrine generates any necessary proxy class files. * - * @return string|null - * * @deprecated 2.7 We're switch to `ocramius/proxy-manager` and this method isn't applicable any longer + * * @see https://github.com/Ocramius/ProxyManager + * + * @return string|null */ public function getProxyDir() { - return isset($this->_attributes['proxyDir']) - ? $this->_attributes['proxyDir'] - : null; + return $this->_attributes['proxyDir'] ?? null; } /** * Gets the strategy for automatically generating proxy classes. * - * @return int Possible values are constants of Doctrine\Common\Proxy\AbstractProxyFactory. - * * @deprecated 2.7 We're switch to `ocramius/proxy-manager` and this method isn't applicable any longer + * * @see https://github.com/Ocramius/ProxyManager + * + * @return int Possible values are constants of Doctrine\Common\Proxy\AbstractProxyFactory. */ public function getAutoGenerateProxyClasses() { - return isset($this->_attributes['autoGenerateProxyClasses']) - ? $this->_attributes['autoGenerateProxyClasses'] - : AbstractProxyFactory::AUTOGENERATE_ALWAYS; + return $this->_attributes['autoGenerateProxyClasses'] ?? AbstractProxyFactory::AUTOGENERATE_ALWAYS; } /** * Sets the strategy for automatically generating proxy classes. * - * @param boolean|int $autoGenerate Possible values are constants of Doctrine\Common\Proxy\AbstractProxyFactory. - * True is converted to AUTOGENERATE_ALWAYS, false to AUTOGENERATE_NEVER. + * @param bool|int $autoGenerate Possible values are constants of Doctrine\Common\Proxy\AbstractProxyFactory. + * True is converted to AUTOGENERATE_ALWAYS, false to AUTOGENERATE_NEVER. * * @return void */ @@ -113,16 +109,15 @@ public function setAutoGenerateProxyClasses($autoGenerate) /** * Gets the namespace where proxy classes reside. * - * @return string|null - * * @deprecated 2.7 We're switch to `ocramius/proxy-manager` and this method isn't applicable any longer + * * @see https://github.com/Ocramius/ProxyManager + * + * @return string|null */ public function getProxyNamespace() { - return isset($this->_attributes['proxyNamespace']) - ? $this->_attributes['proxyNamespace'] - : null; + return $this->_attributes['proxyNamespace'] ?? null; } /** @@ -140,8 +135,6 @@ public function setProxyNamespace($ns) /** * Sets the cache driver implementation that is used for metadata caching. * - * @param MappingDriver $driverImpl - * * @return void * * @todo Force parameter to be a Closure to ensure lazy evaluation @@ -204,7 +197,7 @@ 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); } @@ -242,28 +235,22 @@ public function getEntityNamespaces() */ public function getMetadataDriverImpl() { - return isset($this->_attributes['metadataDriverImpl']) - ? $this->_attributes['metadataDriverImpl'] - : null; + return $this->_attributes['metadataDriverImpl'] ?? null; } /** * Gets the cache driver implementation that is used for the query cache (SQL cache). * - * @return \Doctrine\Common\Cache\Cache|null + * @return CacheDriver|null */ public function getQueryCacheImpl() { - return isset($this->_attributes['queryCacheImpl']) - ? $this->_attributes['queryCacheImpl'] - : null; + return $this->_attributes['queryCacheImpl'] ?? null; } /** * Sets the cache driver implementation that is used for the query cache (SQL cache). * - * @param \Doctrine\Common\Cache\Cache $cacheImpl - * * @return void */ public function setQueryCacheImpl(CacheDriver $cacheImpl) @@ -274,20 +261,16 @@ public function setQueryCacheImpl(CacheDriver $cacheImpl) /** * Gets the cache driver implementation that is used for the hydration cache (SQL cache). * - * @return \Doctrine\Common\Cache\Cache|null + * @return CacheDriver|null */ public function getHydrationCacheImpl() { - return isset($this->_attributes['hydrationCacheImpl']) - ? $this->_attributes['hydrationCacheImpl'] - : null; + return $this->_attributes['hydrationCacheImpl'] ?? null; } /** * Sets the cache driver implementation that is used for the hydration cache (SQL cache). * - * @param \Doctrine\Common\Cache\Cache $cacheImpl - * * @return void */ public function setHydrationCacheImpl(CacheDriver $cacheImpl) @@ -298,20 +281,16 @@ public function setHydrationCacheImpl(CacheDriver $cacheImpl) /** * Gets the cache driver implementation that is used for metadata caching. * - * @return \Doctrine\Common\Cache\Cache|null + * @return CacheDriver|null */ public function getMetadataCacheImpl() { - return isset($this->_attributes['metadataCacheImpl']) - ? $this->_attributes['metadataCacheImpl'] - : null; + return $this->_attributes['metadataCacheImpl'] ?? null; } /** * Sets the cache driver implementation that is used for metadata caching. * - * @param \Doctrine\Common\Cache\Cache $cacheImpl - * * @return void */ public function setMetadataCacheImpl(CacheDriver $cacheImpl) @@ -343,7 +322,7 @@ 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); } @@ -376,7 +355,7 @@ 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); } @@ -396,7 +375,7 @@ public function ensureProductionSettings() { $queryCacheImpl = $this->getQueryCacheImpl(); - if ( ! $queryCacheImpl) { + if (! $queryCacheImpl) { throw ORMException::queryCacheNotConfigured(); } @@ -406,7 +385,7 @@ public function ensureProductionSettings() $metadataCacheImpl = $this->getMetadataCacheImpl(); - if ( ! $metadataCacheImpl) { + if (! $metadataCacheImpl) { throw ORMException::metadataCacheNotConfigured(); } @@ -442,15 +421,14 @@ public function addCustomStringFunction($name, $className) * @param string $name * * @return string|null + * * @psalm-return ?class-string */ public function getCustomStringFunction($name) { $name = strtolower($name); - return isset($this->_attributes['customStringFunctions'][$name]) - ? $this->_attributes['customStringFunctions'][$name] - : null; + return $this->_attributes['customStringFunctions'][$name] ?? null; } /** @@ -495,15 +473,14 @@ public function addCustomNumericFunction($name, $className) * @param string $name * * @return string|null + * * @psalm-return ?class-string */ public function getCustomNumericFunction($name) { $name = strtolower($name); - return isset($this->_attributes['customNumericFunctions'][$name]) - ? $this->_attributes['customNumericFunctions'][$name] - : null; + return $this->_attributes['customNumericFunctions'][$name] ?? null; } /** @@ -557,9 +534,7 @@ public function getCustomDatetimeFunction($name) { $name = strtolower($name); - return isset($this->_attributes['customDatetimeFunctions'][$name]) - ? $this->_attributes['customDatetimeFunctions'][$name] - : null; + return $this->_attributes['customDatetimeFunctions'][$name] ?? null; } /** @@ -610,9 +585,7 @@ public function setCustomHydrationModes($modes) */ public function getCustomHydrationMode($modeName) { - return isset($this->_attributes['customHydrationModes'][$modeName]) - ? $this->_attributes['customHydrationModes'][$modeName] - : null; + return $this->_attributes['customHydrationModes'][$modeName] ?? null; } /** @@ -649,7 +622,7 @@ public function setClassMetadataFactoryName($cmfName) */ public function getClassMetadataFactoryName() { - if ( ! isset($this->_attributes['classMetadataFactoryName'])) { + if (! isset($this->_attributes['classMetadataFactoryName'])) { $this->_attributes['classMetadataFactoryName'] = ClassMetadataFactory::class; } @@ -679,16 +652,12 @@ public function addFilter($name, $className) */ public function getFilterClassName($name) { - return isset($this->_attributes['filters'][$name]) - ? $this->_attributes['filters'][$name] - : null; + return $this->_attributes['filters'][$name] ?? null; } /** * Sets default repository class. * - * @since 2.2 - * * @param string $className * * @return void @@ -697,9 +666,9 @@ public function getFilterClassName($name) */ public function setDefaultRepositoryClassName($className) { - $reflectionClass = new \ReflectionClass($className); + $reflectionClass = new ReflectionClass($className); - if ( ! $reflectionClass->implementsInterface(ObjectRepository::class)) { + if (! $reflectionClass->implementsInterface(ObjectRepository::class)) { throw ORMException::invalidEntityRepository($className); } @@ -709,26 +678,18 @@ public function setDefaultRepositoryClassName($className) /** * Get default repository class. * - * @since 2.2 - * * @return string * * @psalm-return class-string */ public function getDefaultRepositoryClassName() { - return isset($this->_attributes['defaultRepositoryClassName']) - ? $this->_attributes['defaultRepositoryClassName'] - : EntityRepository::class; + return $this->_attributes['defaultRepositoryClassName'] ?? EntityRepository::class; } /** * Sets naming strategy. * - * @since 2.3 - * - * @param NamingStrategy $namingStrategy - * * @return void */ public function setNamingStrategy(NamingStrategy $namingStrategy) @@ -739,13 +700,11 @@ public function setNamingStrategy(NamingStrategy $namingStrategy) /** * Gets naming strategy.. * - * @since 2.3 - * * @return NamingStrategy */ public function getNamingStrategy() { - if ( ! isset($this->_attributes['namingStrategy'])) { + if (! isset($this->_attributes['namingStrategy'])) { $this->_attributes['namingStrategy'] = new DefaultNamingStrategy(); } @@ -755,10 +714,6 @@ public function getNamingStrategy() /** * Sets quote strategy. * - * @since 2.3 - * - * @param \Doctrine\ORM\Mapping\QuoteStrategy $quoteStrategy - * * @return void */ public function setQuoteStrategy(QuoteStrategy $quoteStrategy) @@ -769,13 +724,11 @@ public function setQuoteStrategy(QuoteStrategy $quoteStrategy) /** * Gets quote strategy. * - * @since 2.3 - * - * @return \Doctrine\ORM\Mapping\QuoteStrategy + * @return QuoteStrategy */ public function getQuoteStrategy() { - if ( ! isset($this->_attributes['quoteStrategy'])) { + if (! isset($this->_attributes['quoteStrategy'])) { $this->_attributes['quoteStrategy'] = new DefaultQuoteStrategy(); } @@ -784,9 +737,6 @@ public function getQuoteStrategy() /** * Set the entity listener resolver. - * - * @since 2.4 - * @param \Doctrine\ORM\Mapping\EntityListenerResolver $resolver */ public function setEntityListenerResolver(EntityListenerResolver $resolver) { @@ -796,12 +746,11 @@ public function setEntityListenerResolver(EntityListenerResolver $resolver) /** * Get the entity listener resolver. * - * @since 2.4 - * @return \Doctrine\ORM\Mapping\EntityListenerResolver + * @return EntityListenerResolver */ public function getEntityListenerResolver() { - if ( ! isset($this->_attributes['entityListenerResolver'])) { + if (! isset($this->_attributes['entityListenerResolver'])) { $this->_attributes['entityListenerResolver'] = new DefaultEntityListenerResolver(); } @@ -810,9 +759,6 @@ public function getEntityListenerResolver() /** * Set the entity repository factory. - * - * @since 2.4 - * @param \Doctrine\ORM\Repository\RepositoryFactory $repositoryFactory */ public function setRepositoryFactory(RepositoryFactory $repositoryFactory) { @@ -822,45 +768,32 @@ public function setRepositoryFactory(RepositoryFactory $repositoryFactory) /** * Get the entity repository factory. * - * @since 2.4 - * @return \Doctrine\ORM\Repository\RepositoryFactory + * @return RepositoryFactory */ public function getRepositoryFactory() { - return isset($this->_attributes['repositoryFactory']) - ? $this->_attributes['repositoryFactory'] - : new DefaultRepositoryFactory(); + return $this->_attributes['repositoryFactory'] ?? new DefaultRepositoryFactory(); } /** - * @since 2.5 - * - * @return boolean + * @return bool */ public function isSecondLevelCacheEnabled() { - return isset($this->_attributes['isSecondLevelCacheEnabled']) - ? $this->_attributes['isSecondLevelCacheEnabled'] - : false; + return $this->_attributes['isSecondLevelCacheEnabled'] ?? false; } /** - * @since 2.5 - * - * @param boolean $flag + * @param bool $flag * * @return void */ public function setSecondLevelCacheEnabled($flag = true) { - $this->_attributes['isSecondLevelCacheEnabled'] = (boolean) $flag; + $this->_attributes['isSecondLevelCacheEnabled'] = (bool) $flag; } /** - * @since 2.5 - * - * @param \Doctrine\ORM\Cache\CacheConfiguration $cacheConfig - * * @return void */ public function setSecondLevelCacheConfiguration(CacheConfiguration $cacheConfig) @@ -869,38 +802,30 @@ public function setSecondLevelCacheConfiguration(CacheConfiguration $cacheConfig } /** - * @since 2.5 - * - * @return \Doctrine\ORM\Cache\CacheConfiguration|null + * @return CacheConfiguration|null */ public function getSecondLevelCacheConfiguration() { - if ( ! isset($this->_attributes['secondLevelCacheConfiguration']) && $this->isSecondLevelCacheEnabled()) { + if (! isset($this->_attributes['secondLevelCacheConfiguration']) && $this->isSecondLevelCacheEnabled()) { $this->_attributes['secondLevelCacheConfiguration'] = new CacheConfiguration(); } - return isset($this->_attributes['secondLevelCacheConfiguration']) - ? $this->_attributes['secondLevelCacheConfiguration'] - : null; + return $this->_attributes['secondLevelCacheConfiguration'] ?? null; } /** * Returns query hints, which will be applied to every query in application * - * @since 2.5 - * * @return array */ public function getDefaultQueryHints() { - return isset($this->_attributes['defaultQueryHints']) ? $this->_attributes['defaultQueryHints'] : []; + return $this->_attributes['defaultQueryHints'] ?? []; } /** * Sets array of query hints, which will be applied to every query in application * - * @since 2.5 - * * @param array $defaultQueryHints */ public function setDefaultQueryHints(array $defaultQueryHints) @@ -911,24 +836,18 @@ public function setDefaultQueryHints(array $defaultQueryHints) /** * Gets the value of a default query hint. If the hint name is not recognized, FALSE is returned. * - * @since 2.5 - * * @param string $name The name of the hint. * * @return mixed The value of the hint or FALSE, if the hint name is not recognized. */ public function getDefaultQueryHint($name) { - return isset($this->_attributes['defaultQueryHints'][$name]) - ? $this->_attributes['defaultQueryHints'][$name] - : false; + return $this->_attributes['defaultQueryHints'][$name] ?? false; } /** * Sets a default query hint. If the hint name is not recognized, it is silently ignored. * - * @since 2.5 - * * @param string $name The name of the hint. * @param mixed $value The value of the hint. */ diff --git a/lib/Doctrine/ORM/Decorator/EntityManagerDecorator.php b/lib/Doctrine/ORM/Decorator/EntityManagerDecorator.php index 16959dfb143..b1d11f3c6f9 100644 --- a/lib/Doctrine/ORM/Decorator/EntityManagerDecorator.php +++ b/lib/Doctrine/ORM/Decorator/EntityManagerDecorator.php @@ -1,4 +1,5 @@ wrapped = $wrapped; diff --git a/lib/Doctrine/ORM/EntityManager.php b/lib/Doctrine/ORM/EntityManager.php index 3f357fdbbeb..52c311e881c 100644 --- a/lib/Doctrine/ORM/EntityManager.php +++ b/lib/Doctrine/ORM/EntityManager.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ /* final */class EntityManager implements EntityManagerInterface { /** * The used Configuration. * - * @var \Doctrine\ORM\Configuration + * @var Configuration */ private $config; /** * The database connection used by the EntityManager. * - * @var \Doctrine\DBAL\Connection + * @var Connection */ private $conn; /** * The metadata factory, used to retrieve the ORM metadata of entity classes. * - * @var \Doctrine\ORM\Mapping\ClassMetadataFactory + * @var ClassMetadataFactory */ private $metadataFactory; /** * The UnitOfWork used to coordinate object-level transactions. * - * @var \Doctrine\ORM\UnitOfWork + * @var UnitOfWork */ private $unitOfWork; /** * The event manager that is the central point of the event system. * - * @var \Doctrine\Common\EventManager + * @var EventManager */ private $eventManager; /** * The proxy factory used to create dynamic proxies. * - * @var \Doctrine\ORM\Proxy\ProxyFactory + * @var ProxyFactory */ private $proxyFactory; /** * The repository factory used to create dynamic repositories. * - * @var \Doctrine\ORM\Repository\RepositoryFactory + * @var RepositoryFactory */ private $repositoryFactory; /** * The expression builder instance used to generate query expressions. * - * @var \Doctrine\ORM\Query\Expr + * @var Expr */ private $expressionBuilder; @@ -134,32 +145,26 @@ /** * Collection of query filters. * - * @var \Doctrine\ORM\Query\FilterCollection + * @var FilterCollection */ private $filterCollection; - /** - * @var \Doctrine\ORM\Cache The second level cache regions API. - */ + /** @var Cache The second level cache regions API. */ private $cache; /** * Creates a new EntityManager that operates on the given database connection * and uses the given Configuration and EventManager implementations. - * - * @param \Doctrine\DBAL\Connection $conn - * @param \Doctrine\ORM\Configuration $config - * @param \Doctrine\Common\EventManager $eventManager */ protected function __construct(Connection $conn, Configuration $config, EventManager $eventManager) { - $this->conn = $conn; - $this->config = $config; - $this->eventManager = $eventManager; + $this->conn = $conn; + $this->config = $config; + $this->eventManager = $eventManager; $metadataFactoryClassName = $config->getClassMetadataFactoryName(); - $this->metadataFactory = new $metadataFactoryClassName; + $this->metadataFactory = new $metadataFactoryClassName(); $this->metadataFactory->setEntityManager($this); $this->metadataFactory->setCacheDriver($this->config->getMetadataCacheImpl()); @@ -173,9 +178,9 @@ protected function __construct(Connection $conn, Configuration $config, EventMan ); if ($config->isSecondLevelCacheEnabled()) { - $cacheConfig = $config->getSecondLevelCacheConfiguration(); - $cacheFactory = $cacheConfig->getCacheFactory(); - $this->cache = $cacheFactory->createCache($this); + $cacheConfig = $config->getSecondLevelCacheConfiguration(); + $cacheFactory = $cacheConfig->getCacheFactory(); + $this->cache = $cacheFactory->createCache($this); } } @@ -190,7 +195,7 @@ public function getConnection() /** * Gets the metadata factory used to gather the metadata of classes. * - * @return \Doctrine\ORM\Mapping\ClassMetadataFactory + * @return ClassMetadataFactory */ public function getMetadataFactory() { @@ -203,7 +208,7 @@ public function getMetadataFactory() public function getExpressionBuilder() { if ($this->expressionBuilder === null) { - $this->expressionBuilder = new Query\Expr; + $this->expressionBuilder = new Query\Expr(); } return $this->expressionBuilder; @@ -230,8 +235,8 @@ public function getCache() */ public function transactional($func) { - if (!is_callable($func)) { - throw new \InvalidArgumentException('Expected argument of type "callable", got "' . gettype($func) . '"'); + if (! is_callable($func)) { + throw new InvalidArgumentException('Expected argument of type "callable", got "' . gettype($func) . '"'); } $this->conn->beginTransaction(); @@ -281,7 +286,7 @@ public function rollback() * * @param string $className * - * @return \Doctrine\ORM\Mapping\ClassMetadata + * @return ClassMetadata */ public function getClassMetadata($className) { @@ -295,7 +300,7 @@ public function createQuery($dql = '') { $query = new Query($this); - if ( ! empty($dql)) { + if (! empty($dql)) { $query->setDQL($dql); } @@ -349,12 +354,12 @@ 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 + * @param object|array|null $entity * * @return void * - * @throws \Doctrine\ORM\OptimisticLockException If a version check on an entity that - * makes use of optimistic locking fails. + * @throws OptimisticLockException If a version check on an entity that + * makes use of optimistic locking fails. * @throws ORMException */ public function flush($entity = null) @@ -374,13 +379,13 @@ public function flush($entity = null) /** * Finds an Entity by its identifier. * - * @param string $className The class name of the entity to find. - * @param mixed $id The identity of the entity to find. - * @param integer|null $lockMode One of the \Doctrine\DBAL\LockMode::* constants - * or NULL if no specific lock mode should be used - * during the search. - * @param integer|null $lockVersion The version of the entity to find when using - * optimistic locking. + * @param string $className The class name of the entity to find. + * @param mixed $id The identity of the entity to find. + * @param int|null $lockMode One of the \Doctrine\DBAL\LockMode::* constants + * or NULL if no specific lock mode should be used + * during the search. + * @param int|null $lockVersion The version of the entity to find when using + * optimistic locking. * * @return object|null The entity instance or NULL if the entity can not be found. * @@ -401,7 +406,7 @@ public function find($className, $id, $lockMode = null, $lockVersion = null) $this->checkLockRequirements($lockMode, $class); } - if ( ! is_array($id)) { + if (! is_array($id)) { if ($class->isIdentifierComposite) { throw ORMInvalidArgumentException::invalidCompositeIdentifier(); } @@ -422,7 +427,7 @@ public function find($className, $id, $lockMode = null, $lockVersion = null) $sortedId = []; foreach ($class->identifier as $identifier) { - if ( ! isset($id[$identifier])) { + if (! isset($id[$identifier])) { throw ORMException::missingIdentifierField($class->name, $identifier); } @@ -438,18 +443,18 @@ public function find($className, $id, $lockMode = null, $lockVersion = null) // Check identity map first if (($entity = $unitOfWork->tryGetById($sortedId, $class->rootEntityName)) !== false) { - if ( ! ($entity instanceof $class->name)) { + if (! ($entity instanceof $class->name)) { return null; } switch (true) { - case LockMode::OPTIMISTIC === $lockMode: + case $lockMode === LockMode::OPTIMISTIC: $this->lock($entity, $lockMode, $lockVersion); break; - case LockMode::NONE === $lockMode: - case LockMode::PESSIMISTIC_READ === $lockMode: - case LockMode::PESSIMISTIC_WRITE === $lockMode: + case $lockMode === LockMode::NONE: + case $lockMode === LockMode::PESSIMISTIC_READ: + case $lockMode === LockMode::PESSIMISTIC_WRITE: $persister = $unitOfWork->getEntityPersister($class->name); $persister->refresh($sortedId, $entity, $lockMode); break; @@ -461,15 +466,15 @@ public function find($className, $id, $lockMode = null, $lockVersion = null) $persister = $unitOfWork->getEntityPersister($class->name); switch (true) { - case LockMode::OPTIMISTIC === $lockMode: + case $lockMode === LockMode::OPTIMISTIC: $entity = $persister->load($sortedId); $unitOfWork->lock($entity, $lockMode, $lockVersion); return $entity; - case LockMode::PESSIMISTIC_READ === $lockMode: - case LockMode::PESSIMISTIC_WRITE === $lockMode: + case $lockMode === LockMode::PESSIMISTIC_READ: + case $lockMode === LockMode::PESSIMISTIC_WRITE: return $persister->load($sortedId, null, null, [], $lockMode); default: @@ -484,14 +489,14 @@ public function getReference($entityName, $id) { $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\')); - if ( ! is_array($id)) { + if (! is_array($id)) { $id = [$class->identifier[0] => $id]; } $sortedId = []; foreach ($class->identifier as $identifier) { - if ( ! isset($id[$identifier])) { + if (! isset($id[$identifier])) { throw ORMException::missingIdentifierField($class->name, $identifier); } @@ -505,7 +510,7 @@ public function getReference($entityName, $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; + return $entity instanceof $class->name ? $entity : null; } if ($class->subClasses) { @@ -528,10 +533,10 @@ public function getPartialReference($entityName, $identifier) // 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; + return $entity instanceof $class->name ? $entity : null; } - if ( ! is_array($identifier)) { + if (! is_array($identifier)) { $identifier = [$class->identifier[0] => $identifier]; } @@ -559,7 +564,7 @@ public function getPartialReference($entityName, $identifier) */ public function clear($entityName = null) { - if (null !== $entityName && ! is_string($entityName)) { + if ($entityName !== null && ! is_string($entityName)) { throw ORMInvalidArgumentException::invalidEntityName($entityName); } @@ -571,7 +576,7 @@ public function clear($entityName = null) } $this->unitOfWork->clear( - null === $entityName + $entityName === null ? null : $this->metadataFactory->getMetadataFor($entityName)->getName() ); @@ -605,7 +610,7 @@ public function close() */ public function persist($entity) { - if ( ! is_object($entity)) { + if (! is_object($entity)) { throw ORMInvalidArgumentException::invalidObject('EntityManager#persist()', $entity); } @@ -629,7 +634,7 @@ public function persist($entity) */ public function remove($entity) { - if ( ! is_object($entity)) { + if (! is_object($entity)) { throw ORMInvalidArgumentException::invalidObject('EntityManager#remove()', $entity); } @@ -651,7 +656,7 @@ public function remove($entity) */ public function refresh($entity) { - if ( ! is_object($entity)) { + if (! is_object($entity)) { throw ORMInvalidArgumentException::invalidObject('EntityManager#refresh()', $entity); } @@ -667,19 +672,19 @@ public function refresh($entity) * Entities which previously referenced the detached entity will continue to * reference it. * + * @deprecated 2.7 This method is being removed from the ORM and won't have any replacement + * * @param object $entity The entity to detach. * * @return void * * @throws ORMInvalidArgumentException - * - * @deprecated 2.7 This method is being removed from the ORM and won't have any replacement */ public function detach($entity) { @trigger_error('Method ' . __METHOD__ . '() is deprecated and will be removed in Doctrine ORM 3.0.', E_USER_DEPRECATED); - if ( ! is_object($entity)) { + if (! is_object($entity)) { throw ORMInvalidArgumentException::invalidObject('EntityManager#detach()', $entity); } @@ -691,20 +696,20 @@ public function detach($entity) * of this EntityManager and returns the managed copy of the entity. * The entity passed to merge will not become associated/managed with this EntityManager. * + * @deprecated 2.7 This method is being removed from the ORM and won't have any replacement + * * @param object $entity The detached entity to merge into the persistence context. * * @return object The managed copy of the entity. * * @throws ORMInvalidArgumentException * @throws ORMException - * - * @deprecated 2.7 This method is being removed from the ORM and won't have any replacement */ public function merge($entity) { @trigger_error('Method ' . __METHOD__ . '() is deprecated and will be removed in Doctrine ORM 3.0.', E_USER_DEPRECATED); - if ( ! is_object($entity)) { + if (! is_object($entity)) { throw ORMInvalidArgumentException::invalidObject('EntityManager#merge()', $entity); } @@ -720,7 +725,7 @@ public function copy($entity, $deep = false) { @trigger_error('Method ' . __METHOD__ . '() is deprecated and will be removed in Doctrine ORM 3.0.', E_USER_DEPRECATED); - throw new \BadMethodCallException("Not implemented."); + throw new BadMethodCallException('Not implemented.'); } /** @@ -752,7 +757,7 @@ public function getRepository($entityName) * * @param object $entity * - * @return boolean TRUE if this EntityManager currently manages the given entity, FALSE otherwise. + * @return bool TRUE if this EntityManager currently manages the given entity, FALSE otherwise. */ public function contains($entity) { @@ -796,7 +801,7 @@ private function errorIfClosed() */ public function isOpen() { - return (!$this->closed); + return ! $this->closed; } /** @@ -870,12 +875,12 @@ public function initializeObject($obj) * * @return EntityManager The created EntityManager. * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException * @throws ORMException */ - public static function create($connection, Configuration $config, EventManager $eventManager = null) + public static function create($connection, Configuration $config, ?EventManager $eventManager = null) { - if ( ! $config->getMetadataDriverImpl()) { + if (! $config->getMetadataDriverImpl()) { throw ORMException::missingMappingDriverImpl(); } @@ -893,17 +898,17 @@ public static function create($connection, Configuration $config, EventManager $ * * @return Connection * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException * @throws ORMException */ - protected static function createConnection($connection, Configuration $config, EventManager $eventManager = null) + protected static function createConnection($connection, Configuration $config, ?EventManager $eventManager = null) { if (is_array($connection)) { return DriverManager::getConnection($connection, $config, $eventManager ?: new EventManager()); } - if ( ! $connection instanceof Connection) { - throw new \InvalidArgumentException( + if (! $connection instanceof Connection) { + throw new InvalidArgumentException( sprintf( 'Invalid $connection argument of type %s given%s.', is_object($connection) ? get_class($connection) : gettype($connection), @@ -924,7 +929,7 @@ protected static function createConnection($connection, Configuration $config, E */ public function getFilters() { - if (null === $this->filterCollection) { + if ($this->filterCollection === null) { $this->filterCollection = new FilterCollection($this); } @@ -936,7 +941,7 @@ public function getFilters() */ public function isFiltersStateClean() { - return null === $this->filterCollection || $this->filterCollection->isClean(); + return $this->filterCollection === null || $this->filterCollection->isClean(); } /** @@ -944,12 +949,10 @@ public function isFiltersStateClean() */ public function hasFilters() { - return null !== $this->filterCollection; + return $this->filterCollection !== null; } /** - * @param int $lockMode - * @param ClassMetadata $class * @throws OptimisticLockException * @throws TransactionRequiredException */ @@ -957,13 +960,14 @@ private function checkLockRequirements(int $lockMode, ClassMetadata $class): voi { switch ($lockMode) { case LockMode::OPTIMISTIC: - if (!$class->isVersioned) { + if (! $class->isVersioned) { throw OptimisticLockException::notVersioned($class->name); } + break; case LockMode::PESSIMISTIC_READ: case LockMode::PESSIMISTIC_WRITE: - if (!$this->getConnection()->isTransactionActive()) { + if (! $this->getConnection()->isTransactionActive()) { throw TransactionRequiredException::transactionRequired(); } } diff --git a/lib/Doctrine/ORM/EntityManagerInterface.php b/lib/Doctrine/ORM/EntityManagerInterface.php index f29585b6523..1ac153f8bb0 100644 --- a/lib/Doctrine/ORM/EntityManagerInterface.php +++ b/lib/Doctrine/ORM/EntityManagerInterface.php @@ -1,4 +1,5 @@ - * * @method Mapping\ClassMetadata getClassMetadata($className) */ interface EntityManagerInterface extends ObjectManager @@ -35,14 +40,14 @@ interface EntityManagerInterface extends ObjectManager /** * Returns the cache API for managing the second level cache regions or NULL if the cache is not enabled. * - * @return \Doctrine\ORM\Cache|null + * @return Cache|null */ public function getCache(); /** * Gets the database connection object used by the EntityManager. * - * @return \Doctrine\DBAL\Connection + * @return Connection */ public function getConnection(); @@ -58,7 +63,7 @@ public function getConnection(); * ->where($expr->orX($expr->eq('u.id', 1), $expr->eq('u.id', 2))); * * - * @return \Doctrine\ORM\Query\Expr + * @return Expr */ public function getExpressionBuilder(); @@ -196,12 +201,12 @@ public function close(); * * @deprecated 2.7 This method is being removed from the ORM and won't have any replacement * - * @param object $entity The entity to copy. - * @param boolean $deep FALSE for a shallow copy, TRUE for a deep copy. + * @param object $entity The entity to copy. + * @param bool $deep FALSE for a shallow copy, TRUE for a deep copy. * * @return object The new entity. * - * @throws \BadMethodCallException + * @throws BadMethodCallException */ public function copy($entity, $deep = false); @@ -222,7 +227,7 @@ public function lock($entity, $lockMode, $lockVersion = null); /** * Gets the EventManager used by the EntityManager. * - * @return \Doctrine\Common\EventManager + * @return EventManager */ public function getEventManager(); @@ -248,17 +253,17 @@ public function isOpen(); public function getUnitOfWork(); /** - * Gets a hydrator for the given hydration mode. - * - * This method caches the hydrator instances which is used for all queries that don't - * selectively iterate over the result. - * - * @deprecated - * - * @param string|int $hydrationMode - * - * @return \Doctrine\ORM\Internal\Hydration\AbstractHydrator - */ + * Gets a hydrator for the given hydration mode. + * + * This method caches the hydrator instances which is used for all queries that don't + * selectively iterate over the result. + * + * @deprecated + * + * @param string|int $hydrationMode + * + * @return AbstractHydrator + */ public function getHydrator($hydrationMode); /** @@ -266,7 +271,7 @@ public function getHydrator($hydrationMode); * * @param string|int $hydrationMode * - * @return \Doctrine\ORM\Internal\Hydration\AbstractHydrator + * @return AbstractHydrator * * @throws ORMException */ @@ -275,28 +280,28 @@ public function newHydrator($hydrationMode); /** * Gets the proxy factory used by the EntityManager to create entity proxies. * - * @return \Doctrine\ORM\Proxy\ProxyFactory + * @return ProxyFactory */ public function getProxyFactory(); /** * Gets the enabled filters. * - * @return \Doctrine\ORM\Query\FilterCollection The active filter collection. + * @return FilterCollection The active filter collection. */ public function getFilters(); /** * Checks whether the state of the filter collection is clean. * - * @return boolean True, if the filter collection is clean. + * @return bool True, if the filter collection is clean. */ public function isFiltersStateClean(); /** * Checks whether the Entity Manager has filters. * - * @return boolean True, if the EM has a filter collection. + * @return bool True, if the EM has a filter collection. */ public function hasFilters(); } diff --git a/lib/Doctrine/ORM/EntityNotFoundException.php b/lib/Doctrine/ORM/EntityNotFoundException.php index 5b21e15c276..5f6e340930e 100644 --- a/lib/Doctrine/ORM/EntityNotFoundException.php +++ b/lib/Doctrine/ORM/EntityNotFoundException.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - * * @template T * @template-implements Selectable * @template-implements ObjectRepository */ class EntityRepository implements ObjectRepository, Selectable { - /** - * @var string - */ + /** @var string */ protected $_entityName; - /** - * @var EntityManager - */ + /** @var EntityManager */ protected $_em; - /** - * @var \Doctrine\ORM\Mapping\ClassMetadata - */ + /** @var ClassMetadata */ protected $_class; /** @var Inflector */ @@ -131,8 +128,8 @@ public function createNamedQuery($queryName) */ public function createNativeNamedQuery($queryName) { - $queryMapping = $this->_class->getNamedNativeQuery($queryName); - $rsm = new Query\ResultSetMappingBuilder($this->_em); + $queryMapping = $this->_class->getNamedNativeQuery($queryName); + $rsm = new Query\ResultSetMappingBuilder($this->_em); $rsm->addNamedNativeQueryMapping($this->_class, $queryMapping); return $this->_em->createNativeQuery($queryMapping['query'], $rsm); @@ -141,9 +138,9 @@ public function createNativeNamedQuery($queryName) /** * Clears the repository, causing all managed entities to become detached. * - * @return void - * * @deprecated 2.8 This method is being removed from the ORM and won't have any replacement + * + * @return void */ public function clear() { @@ -194,7 +191,7 @@ public function findAll() * * @psalm-return list */ - public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) + public function findBy(array $criteria, ?array $orderBy = null, $limit = null, $offset = null) { $persister = $this->_em->getUnitOfWork()->getEntityPersister($this->_entityName); @@ -211,7 +208,7 @@ public function findBy(array $criteria, array $orderBy = null, $limit = null, $o * * @psalm-return ?T */ - public function findOneBy(array $criteria, array $orderBy = null) + public function findOneBy(array $criteria, ?array $orderBy = null) { $persister = $this->_em->getUnitOfWork()->getEntityPersister($this->_entityName); @@ -221,11 +218,11 @@ public function findOneBy(array $criteria, array $orderBy = null) /** * Counts entities by a set of criteria. * - * @todo Add this method to `ObjectRepository` interface in the next major release - * * @param array $criteria * * @return int The cardinality of the objects that match the given criteria. + * + * @todo Add this method to `ObjectRepository` interface in the next major release */ public function count(array $criteria) { @@ -241,25 +238,25 @@ public function count(array $criteria) * @return mixed The returned value from the resolved method. * * @throws ORMException - * @throws \BadMethodCallException If the method called is invalid + * @throws BadMethodCallException If the method called is invalid */ public function __call($method, $arguments) { - if (0 === strpos($method, 'findBy')) { + if (strpos($method, 'findBy') === 0) { return $this->resolveMagicCall('findBy', substr($method, 6), $arguments); } - if (0 === strpos($method, 'findOneBy')) { + if (strpos($method, 'findOneBy') === 0) { return $this->resolveMagicCall('findOneBy', substr($method, 9), $arguments); } - if (0 === strpos($method, 'countBy')) { + if (strpos($method, 'countBy') === 0) { return $this->resolveMagicCall('count', substr($method, 7), $arguments); } - throw new \BadMethodCallException( - "Undefined method '$method'. The method name must start with ". - "either findBy, findOneBy or countBy!" + throw new BadMethodCallException( + "Undefined method '$method'. The method name must start with " . + 'either findBy, findOneBy or countBy!' ); } @@ -299,11 +296,9 @@ protected function getClassMetadata() * Select all elements from a selectable that match the expression and * return a new collection containing these elements. * - * @param \Doctrine\Common\Collections\Criteria $criteria - * - * @return \Doctrine\Common\Collections\Collection + * @return Collection * - * @psalm-return \Doctrine\Common\Collections\Collection + * @psalm-return Collection */ public function matching(Criteria $criteria) { @@ -319,9 +314,9 @@ public function matching(Criteria $criteria) * @param string $by The property name used as condition * @param array $arguments The arguments to pass at method call * - * @throws ORMException If the method called is invalid or the requested field/association does not exist - * * @return mixed + * + * @throws ORMException If the method called is invalid or the requested field/association does not exist */ private function resolveMagicCall($method, $by, array $arguments) { diff --git a/lib/Doctrine/ORM/Event/LifecycleEventArgs.php b/lib/Doctrine/ORM/Event/LifecycleEventArgs.php index 4b481221123..578bf94c266 100644 --- a/lib/Doctrine/ORM/Event/LifecycleEventArgs.php +++ b/lib/Doctrine/ORM/Event/LifecycleEventArgs.php @@ -1,4 +1,5 @@ - * @author Benjamin Eberlei */ class LifecycleEventArgs extends BaseLifecycleEventArgs { @@ -45,7 +44,7 @@ public function getEntity() /** * Retrieves associated EntityManager. * - * @return \Doctrine\ORM\EntityManager + * @return EntityManager */ public function getEntityManager() { diff --git a/lib/Doctrine/ORM/Event/ListenersInvoker.php b/lib/Doctrine/ORM/Event/ListenersInvoker.php index 7be8d48ebb1..ab010271a72 100644 --- a/lib/Doctrine/ORM/Event/ListenersInvoker.php +++ b/lib/Doctrine/ORM/Event/ListenersInvoker.php @@ -1,4 +1,5 @@ - * @since 2.4 */ class ListenersInvoker { - const INVOKE_NONE = 0; - const INVOKE_LISTENERS = 1; - const INVOKE_CALLBACKS = 2; - const INVOKE_MANAGER = 4; + public const INVOKE_NONE = 0; + public const INVOKE_LISTENERS = 1; + public const INVOKE_CALLBACKS = 2; + public const INVOKE_MANAGER = 4; - /** - * @var \Doctrine\ORM\Mapping\EntityListenerResolver The Entity listener resolver. - */ + /** @var EntityListenerResolver The Entity listener resolver. */ private $resolver; /** * The EventManager used for dispatching events. * - * @var \Doctrine\Common\EventManager + * @var EventManager */ private $eventManager; /** * Initializes a new ListenersInvoker instance. - * - * @param EntityManagerInterface $em */ public function __construct(EntityManagerInterface $em) { @@ -62,10 +58,10 @@ public function __construct(EntityManagerInterface $em) /** * Get the subscribed event systems * - * @param \Doctrine\ORM\Mapping\ClassMetadata $metadata The entity metadata. - * @param string $eventName The entity lifecycle event. + * @param ClassMetadata $metadata The entity metadata. + * @param string $eventName The entity lifecycle event. * - * @return integer Bitmask of subscribed event systems. + * @return int Bitmask of subscribed event systems. */ public function getSubscribedSystems(ClassMetadata $metadata, $eventName) { @@ -89,11 +85,11 @@ public function getSubscribedSystems(ClassMetadata $metadata, $eventName) /** * Dispatches the lifecycle event of the given entity. * - * @param \Doctrine\ORM\Mapping\ClassMetadata $metadata The entity metadata. - * @param string $eventName The entity lifecycle event. - * @param object $entity The Entity on which the event occurred. - * @param \Doctrine\Common\EventArgs $event The Event args. - * @param integer $invoke Bitmask to invoke listeners. + * @param ClassMetadata $metadata The entity metadata. + * @param string $eventName The entity lifecycle event. + * @param object $entity The Entity on which the event occurred. + * @param EventArgs $event The Event args. + * @param int $invoke Bitmask to invoke listeners. */ public function invoke(ClassMetadata $metadata, $eventName, $entity, EventArgs $event, $invoke) { @@ -105,9 +101,9 @@ public function invoke(ClassMetadata $metadata, $eventName, $entity, EventArgs $ if ($invoke & self::INVOKE_LISTENERS) { foreach ($metadata->entityListeners[$eventName] as $listener) { - $class = $listener['class']; - $method = $listener['method']; - $instance = $this->resolver->resolve($class); + $class = $listener['class']; + $method = $listener['method']; + $instance = $this->resolver->resolve($class); $instance->$method($entity, $event); } diff --git a/lib/Doctrine/ORM/Event/LoadClassMetadataEventArgs.php b/lib/Doctrine/ORM/Event/LoadClassMetadataEventArgs.php index 4380245cab5..ef998048faa 100644 --- a/lib/Doctrine/ORM/Event/LoadClassMetadataEventArgs.php +++ b/lib/Doctrine/ORM/Event/LoadClassMetadataEventArgs.php @@ -1,4 +1,5 @@ - * @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() + * @method __construct(ClassMetadata $classMetadata, EntityManager $objectManager) + * @method ClassMetadata getClassMetadata() */ class LoadClassMetadataEventArgs extends BaseLoadClassMetadataEventArgs { /** * Retrieve associated EntityManager. * - * @return \Doctrine\ORM\EntityManager + * @return EntityManager */ public function getEntityManager() { diff --git a/lib/Doctrine/ORM/Event/OnClassMetadataNotFoundEventArgs.php b/lib/Doctrine/ORM/Event/OnClassMetadataNotFoundEventArgs.php index 0a45fd84737..f1258b2b618 100644 --- a/lib/Doctrine/ORM/Event/OnClassMetadataNotFoundEventArgs.php +++ b/lib/Doctrine/ORM/Event/OnClassMetadataNotFoundEventArgs.php @@ -1,4 +1,5 @@ - * @since 2.5 */ class OnClassMetadataNotFoundEventArgs extends ManagerEventArgs { - /** - * @var string - */ + /** @var string */ private $className; - /** - * @var ClassMetadata|null - */ + /** @var ClassMetadata|null */ private $foundMetadata; /** - * Constructor. - * - * @param string $className - * @param ObjectManager $objectManager + * @param string $className */ public function __construct($className, ObjectManager $objectManager) { @@ -58,10 +48,7 @@ public function __construct($className, ObjectManager $objectManager) parent::__construct($objectManager); } - /** - * @param ClassMetadata|null $classMetadata - */ - public function setFoundMetadata(ClassMetadata $classMetadata = null) + public function setFoundMetadata(?ClassMetadata $classMetadata = null) { $this->foundMetadata = $classMetadata; } diff --git a/lib/Doctrine/ORM/Event/OnClearEventArgs.php b/lib/Doctrine/ORM/Event/OnClearEventArgs.php index 8c4dd41b20f..492628b3b5c 100644 --- a/lib/Doctrine/ORM/Event/OnClearEventArgs.php +++ b/lib/Doctrine/ORM/Event/OnClearEventArgs.php @@ -1,4 +1,5 @@ - * @author Benjamin Eberlei */ -class OnClearEventArgs extends \Doctrine\Common\EventArgs +class OnClearEventArgs extends EventArgs { - /** - * @var EntityManagerInterface - */ + /** @var EntityManagerInterface */ private $em; - /** - * @var string|null - */ + /** @var string|null */ private $entityClass; /** - * Constructor. - * - * @param EntityManagerInterface $em - * @param string|null $entityClass Optional entity class. + * @param string|null $entityClass Optional entity class. */ public function __construct(EntityManagerInterface $em, $entityClass = null) { @@ -57,7 +49,7 @@ public function __construct(EntityManagerInterface $em, $entityClass = null) /** * Retrieves associated EntityManager. * - * @return \Doctrine\ORM\EntityManager + * @return EntityManager */ public function getEntityManager() { @@ -81,6 +73,6 @@ public function getEntityClass() */ public function clearsAllEntities() { - return ($this->entityClass === null); + return $this->entityClass === null; } } diff --git a/lib/Doctrine/ORM/Event/OnFlushEventArgs.php b/lib/Doctrine/ORM/Event/OnFlushEventArgs.php index 6a9c7c7f464..35ac28e95b0 100644 --- a/lib/Doctrine/ORM/Event/OnFlushEventArgs.php +++ b/lib/Doctrine/ORM/Event/OnFlushEventArgs.php @@ -1,4 +1,5 @@ - * @author Benjamin Eberlei */ class OnFlushEventArgs extends EventArgs { - /** - * @var EntityManagerInterface - */ + /** @var EntityManagerInterface */ private $em; - /** - * Constructor. - * - * @param EntityManagerInterface $em - */ public function __construct(EntityManagerInterface $em) { $this->em = $em; @@ -51,11 +42,10 @@ public function __construct(EntityManagerInterface $em) /** * Retrieve associated EntityManager. * - * @return \Doctrine\ORM\EntityManager + * @return EntityManager */ public function getEntityManager() { return $this->em; } - } diff --git a/lib/Doctrine/ORM/Event/PostFlushEventArgs.php b/lib/Doctrine/ORM/Event/PostFlushEventArgs.php index 860f2d33b90..349aaee6f66 100644 --- a/lib/Doctrine/ORM/Event/PostFlushEventArgs.php +++ b/lib/Doctrine/ORM/Event/PostFlushEventArgs.php @@ -1,4 +1,5 @@ . */ + namespace Doctrine\ORM\Event; use Doctrine\Common\EventArgs; +use Doctrine\ORM\EntityManager; use Doctrine\ORM\EntityManagerInterface; /** * Provides event arguments for the postFlush event. * - * @license http://www.opensource.org/licenses/mit-license.php MIT * @link www.doctrine-project.org - * @since 2.0 - * @author Daniel Freudenberger */ class PostFlushEventArgs extends EventArgs { - /** - * @var \Doctrine\ORM\EntityManager - */ + /** @var EntityManager */ private $em; - /** - * Constructor. - * - * @param EntityManagerInterface $em - */ public function __construct(EntityManagerInterface $em) { $this->em = $em; @@ -49,7 +42,7 @@ public function __construct(EntityManagerInterface $em) /** * Retrieves associated EntityManager. * - * @return \Doctrine\ORM\EntityManager + * @return EntityManager */ public function getEntityManager() { diff --git a/lib/Doctrine/ORM/Event/PreFlushEventArgs.php b/lib/Doctrine/ORM/Event/PreFlushEventArgs.php index d01a9263960..6fe684c26bd 100644 --- a/lib/Doctrine/ORM/Event/PreFlushEventArgs.php +++ b/lib/Doctrine/ORM/Event/PreFlushEventArgs.php @@ -1,4 +1,5 @@ - * @author Benjamin Eberlei */ class PreFlushEventArgs extends EventArgs { - /** - * @var \Doctrine\ORM\EntityManager - */ + /** @var EntityManager */ private $em; - /** - * Constructor. - * - * @param EntityManagerInterface $em - */ public function __construct(EntityManagerInterface $em) { $this->em = $em; } /** - * @return \Doctrine\ORM\EntityManager + * @return EntityManager */ public function getEntityManager() { diff --git a/lib/Doctrine/ORM/Event/PreUpdateEventArgs.php b/lib/Doctrine/ORM/Event/PreUpdateEventArgs.php index d9a9f9db2cc..520fcf1df41 100644 --- a/lib/Doctrine/ORM/Event/PreUpdateEventArgs.php +++ b/lib/Doctrine/ORM/Event/PreUpdateEventArgs.php @@ -1,4 +1,5 @@ - * @author Roman Borschel - * @author Benjamin Eberlei - * @since 2.0 */ class PreUpdateEventArgs extends LifecycleEventArgs { - /** - * @var array - */ + /** @var array */ private $entityChangeSet; /** - * Constructor. - * - * @param object $entity - * @param EntityManagerInterface $em - * @param array $changeSet + * @param object $entity + * @param array $changeSet */ public function __construct($entity, EntityManagerInterface $em, array &$changeSet) { @@ -65,7 +60,7 @@ public function getEntityChangeSet() * * @param string $field * - * @return boolean + * @return bool */ public function hasChangedField($field) { @@ -122,12 +117,12 @@ public function setNewValue($field, $value) * * @return void * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ private function assertValidField($field) { - if ( ! isset($this->entityChangeSet[$field])) { - throw new \InvalidArgumentException(sprintf( + if (! isset($this->entityChangeSet[$field])) { + throw new InvalidArgumentException(sprintf( 'Field "%s" is not a valid field of the entity "%s" in PreUpdateEventArgs.', $field, get_class($this->getEntity()) diff --git a/lib/Doctrine/ORM/Events.php b/lib/Doctrine/ORM/Events.php index e16b47a4214..84b3c82eee1 100644 --- a/lib/Doctrine/ORM/Events.php +++ b/lib/Doctrine/ORM/Events.php @@ -1,4 +1,5 @@ - * @since 2.0 */ final class Events { @@ -41,30 +39,24 @@ private function __construct() * EntityManager remove operation for that entity is executed. * * This is an entity lifecycle event. - * - * @var string */ - const preRemove = 'preRemove'; + public const preRemove = 'preRemove'; /** * The postRemove event occurs for an entity after the entity has * been deleted. It will be invoked after the database delete operations. * * This is an entity lifecycle event. - * - * @var string */ - const postRemove = 'postRemove'; + public const postRemove = 'postRemove'; /** * The prePersist event occurs for a given entity before the respective * EntityManager persist operation for that entity is executed. * * This is an entity lifecycle event. - * - * @var string */ - const prePersist = 'prePersist'; + public const prePersist = 'prePersist'; /** * The postPersist event occurs for an entity after the entity has @@ -72,30 +64,24 @@ private function __construct() * Generated primary key values are available in the postPersist event. * * This is an entity lifecycle event. - * - * @var string */ - const postPersist = 'postPersist'; + public const postPersist = 'postPersist'; /** * The preUpdate event occurs before the database update operations to * entity data. * * This is an entity lifecycle event. - * - * @var string */ - const preUpdate = 'preUpdate'; + public const preUpdate = 'preUpdate'; /** * The postUpdate event occurs after the database update operations to * entity data. * * This is an entity lifecycle event. - * - * @var string */ - const postUpdate = 'postUpdate'; + public const postUpdate = 'postUpdate'; /** * The postLoad event occurs for an entity after the entity has been loaded @@ -107,33 +93,27 @@ private function __construct() * or event handler. * * This is an entity lifecycle event. - * - * @var string */ - const postLoad = 'postLoad'; + public const postLoad = 'postLoad'; /** * The loadClassMetadata event occurs after the mapping metadata for a class * has been loaded from a mapping source (annotations/xml/yaml). - * - * @var string */ - const loadClassMetadata = 'loadClassMetadata'; + public const loadClassMetadata = 'loadClassMetadata'; /** * The onClassMetadataNotFound event occurs whenever loading metadata for a class * failed. - * - * @var string */ - const onClassMetadataNotFound = 'onClassMetadataNotFound'; + public const onClassMetadataNotFound = 'onClassMetadataNotFound'; /** * The preFlush event occurs when the EntityManager#flush() operation is invoked, * but before any changes to managed entities have been calculated. This event is * always raised right after EntityManager#flush() call. */ - const preFlush = 'preFlush'; + public const preFlush = 'preFlush'; /** * The onFlush event occurs when the EntityManager#flush() operation is invoked, @@ -141,10 +121,8 @@ private function __construct() * actual database operations are executed. The event is only raised if there is * actually something to do for the underlying UnitOfWork. If nothing needs to be done, * the onFlush event is not raised. - * - * @var string */ - const onFlush = 'onFlush'; + public const onFlush = 'onFlush'; /** * The postFlush event occurs when the EntityManager#flush() operation is invoked and @@ -152,16 +130,12 @@ private function __construct() * actually something to do for the underlying UnitOfWork. If nothing needs to be done, * the postFlush event is not raised. The event won't be raised if an error occurs during the * flush operation. - * - * @var string */ - const postFlush = 'postFlush'; + public const postFlush = 'postFlush'; /** * The onClear event occurs when the EntityManager#clear() operation is invoked, * after all references to entities have been removed from the unit of work. - * - * @var string */ - const onClear = 'onClear'; + public const onClear = 'onClear'; } diff --git a/lib/Doctrine/ORM/Id/AbstractIdGenerator.php b/lib/Doctrine/ORM/Id/AbstractIdGenerator.php index 51887b5be73..8995d7d5594 100644 --- a/lib/Doctrine/ORM/Id/AbstractIdGenerator.php +++ b/lib/Doctrine/ORM/Id/AbstractIdGenerator.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class AssignedGenerator extends AbstractIdGenerator { @@ -38,7 +35,7 @@ class AssignedGenerator extends AbstractIdGenerator * * {@inheritDoc} * - * @throws \Doctrine\ORM\ORMException + * @throws ORMException */ public function generate(EntityManager $em, $entity) { @@ -49,7 +46,7 @@ public function generate(EntityManager $em, $entity) foreach ($idFields as $idField) { $value = $class->getFieldValue($entity, $idField); - if ( ! isset($value)) { + if (! isset($value)) { throw ORMException::entityMissingAssignedIdForField($entity, $idField); } diff --git a/lib/Doctrine/ORM/Id/BigIntegerIdentityGenerator.php b/lib/Doctrine/ORM/Id/BigIntegerIdentityGenerator.php index 01d139f485b..5ea7b68cee2 100644 --- a/lib/Doctrine/ORM/Id/BigIntegerIdentityGenerator.php +++ b/lib/Doctrine/ORM/Id/BigIntegerIdentityGenerator.php @@ -1,4 +1,5 @@ */ class SequenceGenerator extends AbstractIdGenerator implements Serializable { @@ -44,25 +45,21 @@ class SequenceGenerator extends AbstractIdGenerator implements Serializable */ private $_sequenceName; - /** - * @var int - */ + /** @var int */ private $_nextValue = 0; - /** - * @var int|null - */ + /** @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. + * @param string $sequenceName The name of the sequence. + * @param int $allocationSize The allocation size of the sequence. */ public function __construct($sequenceName, $allocationSize) { - $this->_sequenceName = $sequenceName; + $this->_sequenceName = $sequenceName; $this->_allocationSize = $allocationSize; } @@ -71,7 +68,7 @@ public function __construct($sequenceName, $allocationSize) */ public function generate(EntityManager $em, $entity) { - if ($this->_maxValue === null || $this->_nextValue == $this->_maxValue) { + if ($this->_maxValue === null || $this->_nextValue === $this->_maxValue) { // Allocate new values $conn = $em->getConnection(); $sql = $conn->getDatabasePlatform()->getSequenceNextValSQL($this->_sequenceName); @@ -87,7 +84,7 @@ public function generate(EntityManager $em, $entity) /** * Gets the maximum value of the currently allocated bag of values. * - * @return integer|null + * @return int|null */ public function getCurrentMaxValue() { @@ -97,7 +94,7 @@ public function getCurrentMaxValue() /** * Gets the next value that will be returned by generate(). * - * @return integer + * @return int */ public function getNextValue() { @@ -111,8 +108,8 @@ public function serialize() { return serialize( [ - 'allocationSize' => $this->_allocationSize, - 'sequenceName' => $this->_sequenceName + 'allocationSize' => $this->_allocationSize, + 'sequenceName' => $this->_sequenceName, ] ); } @@ -126,7 +123,7 @@ public function unserialize($serialized) { $array = unserialize($serialized); - $this->_sequenceName = $array['sequenceName']; + $this->_sequenceName = $array['sequenceName']; $this->_allocationSize = $array['allocationSize']; } } diff --git a/lib/Doctrine/ORM/Id/TableGenerator.php b/lib/Doctrine/ORM/Id/TableGenerator.php index 02385f51158..bf8994d9bdb 100644 --- a/lib/Doctrine/ORM/Id/TableGenerator.php +++ b/lib/Doctrine/ORM/Id/TableGenerator.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class TableGenerator extends AbstractIdGenerator { - /** - * @var string - */ + /** @var string */ private $_tableName; - /** - * @var string - */ + /** @var string */ private $_sequenceName; - /** - * @var int - */ + /** @var int */ private $_allocationSize; - /** - * @var int|null - */ + /** @var int|null */ private $_nextValue; - /** - * @var int|null - */ + /** @var int|null */ private $_maxValue; /** @@ -64,8 +49,8 @@ class TableGenerator extends AbstractIdGenerator */ public function __construct($tableName, $sequenceName = 'default', $allocationSize = 10) { - $this->_tableName = $tableName; - $this->_sequenceName = $sequenceName; + $this->_tableName = $tableName; + $this->_sequenceName = $sequenceName; $this->_allocationSize = $allocationSize; } @@ -73,9 +58,10 @@ public function __construct($tableName, $sequenceName = 'default', $allocationSi * {@inheritDoc} */ public function generate( - EntityManager $em, $entity) - { - if ($this->_maxValue === null || $this->_nextValue == $this->_maxValue) { + EntityManager $em, + $entity + ) { + if ($this->_maxValue === null || $this->_nextValue === $this->_maxValue) { // Allocate new values $conn = $em->getConnection(); @@ -84,15 +70,17 @@ public function generate( $sql = $conn->getDatabasePlatform()->getTableHiLoCurrentValSql($this->_tableName, $this->_sequenceName); $currentLevel = $conn->fetchColumn($sql); - if ($currentLevel != null) { + if ($currentLevel !== null) { $this->_nextValue = $currentLevel; - $this->_maxValue = $this->_nextValue + $this->_allocationSize; + $this->_maxValue = $this->_nextValue + $this->_allocationSize; $updateSql = $conn->getDatabasePlatform()->getTableHiLoUpdateNextValSql( - $this->_tableName, $this->_sequenceName, $this->_allocationSize + $this->_tableName, + $this->_sequenceName, + $this->_allocationSize ); - if ($conn->executeUpdate($updateSql, [1 => $currentLevel, 2 => $currentLevel+1]) !== 1) { + if ($conn->executeUpdate($updateSql, [1 => $currentLevel, 2 => $currentLevel + 1]) !== 1) { // no affected rows, concurrency issue, throw exception } } else { diff --git a/lib/Doctrine/ORM/Id/UuidGenerator.php b/lib/Doctrine/ORM/Id/UuidGenerator.php index 7cac5ccf40f..b48c81af12b 100644 --- a/lib/Doctrine/ORM/Id/UuidGenerator.php +++ b/lib/Doctrine/ORM/Id/UuidGenerator.php @@ -1,4 +1,5 @@ */ class UuidGenerator extends AbstractIdGenerator { @@ -35,7 +33,7 @@ class UuidGenerator extends AbstractIdGenerator public function generate(EntityManager $em, $entity) { $conn = $em->getConnection(); - $sql = 'SELECT ' . $conn->getDatabasePlatform()->getGuidExpression(); + $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 30b9caa8206..db769f3a09f 100644 --- a/lib/Doctrine/ORM/Internal/CommitOrderCalculator.php +++ b/lib/Doctrine/ORM/Internal/CommitOrderCalculator.php @@ -20,22 +20,22 @@ namespace Doctrine\ORM\Internal; +use stdClass; + +use function array_reverse; + /** * CommitOrderCalculator implements topological sorting, which is an ordering * algorithm for directed graphs (DG) and/or directed acyclic graphs (DAG) by * using a depth-first searching (DFS) to traverse the graph built in memory. * This algorithm have a linear running time based on nodes (V) and dependency * between the nodes (E), resulting in a computational complexity of O(V + E). - * - * @since 2.0 - * @author Guilherme Blanco - * @author Roman Borschel */ class CommitOrderCalculator { - const NOT_VISITED = 0; - const IN_PROGRESS = 1; - const VISITED = 2; + public const NOT_VISITED = 0; + public const IN_PROGRESS = 1; + public const VISITED = 2; /** * Matrix of nodes (aka. vertex). @@ -52,7 +52,7 @@ class CommitOrderCalculator * - dependencyList (array) * Map of node dependencies defined as hashes. * - * @var array<\stdClass> + * @var array */ private $nodeList = []; @@ -68,7 +68,7 @@ class CommitOrderCalculator * * @param string $hash * - * @return boolean + * @return bool */ public function hasNode($hash) { @@ -85,7 +85,7 @@ public function hasNode($hash) */ public function addNode($hash, $node) { - $vertex = new \stdClass(); + $vertex = new stdClass(); $vertex->hash = $hash; $vertex->state = self::NOT_VISITED; @@ -98,16 +98,16 @@ public function addNode($hash, $node) /** * Adds a new dependency (edge) to the graph using their hashes. * - * @param string $fromHash - * @param string $toHash - * @param integer $weight + * @param string $fromHash + * @param string $toHash + * @param int $weight * * @return void */ public function addDependency($fromHash, $toHash, $weight) { $vertex = $this->nodeList[$fromHash]; - $edge = new \stdClass(); + $edge = new stdClass(); $edge->from = $fromHash; $edge->to = $toHash; @@ -147,7 +147,7 @@ public function sort() * * {@internal Highly performance-sensitive method.} * - * @param \stdClass $vertex + * @param stdClass $vertex */ private function visit($vertex) { @@ -162,9 +162,10 @@ private function visit($vertex) break; case self::IN_PROGRESS: - if (isset($adjacentVertex->dependencyList[$vertex->hash]) && - $adjacentVertex->dependencyList[$vertex->hash]->weight < $edge->weight) { - + if ( + isset($adjacentVertex->dependencyList[$vertex->hash]) && + $adjacentVertex->dependencyList[$vertex->hash]->weight < $edge->weight + ) { // If we have some non-visited dependencies in the in-progress dependency, we // need to visit them before adding the node. foreach ($adjacentVertex->dependencyList as $adjacentEdge) { @@ -179,6 +180,7 @@ private function visit($vertex) $this->sortedNodeList[] = $adjacentVertex->value; } + break; case self::NOT_VISITED: diff --git a/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php b/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php index 8ac93cc1372..0be65fe6328 100644 --- a/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php +++ b/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php @@ -1,4 +1,5 @@ - * @author Roman Borschel - * @author Guilherme Blanco */ abstract class AbstractHydrator { /** * The ResultSetMapping. * - * @var \Doctrine\ORM\Query\ResultSetMapping + * @var ResultSetMapping */ protected $_rsm; @@ -62,14 +64,14 @@ abstract class AbstractHydrator /** * The dbms Platform instance. * - * @var \Doctrine\DBAL\Platforms\AbstractPlatform + * @var AbstractPlatform */ protected $_platform; /** * The UnitOfWork of the associated EntityManager. * - * @var \Doctrine\ORM\UnitOfWork + * @var UnitOfWork */ protected $_uow; @@ -90,7 +92,7 @@ abstract class AbstractHydrator /** * The statement that provides the data to hydrate. * - * @var \Doctrine\DBAL\Driver\Statement + * @var Statement */ protected $_stmt; @@ -151,7 +153,7 @@ public function iterate($stmt, $resultSetMapping, array $hints = []) * * @return iterable */ - public function toIterable(Statement $stmt, ResultSetMapping $resultSetMapping, array $hints = []) : iterable + public function toIterable(Statement $stmt, ResultSetMapping $resultSetMapping, array $hints = []): iterable { $this->_stmt = $stmt; $this->_rsm = $resultSetMapping; @@ -286,7 +288,7 @@ protected function cleanup() */ protected function hydrateRowData(array $row, array &$result) { - throw new HydrationException("hydrateRowData() not implemented by this hydrator."); + throw new HydrationException('hydrateRowData() not implemented by this hydrator.'); } /** @@ -305,7 +307,7 @@ abstract protected function hydrateAllData(); * field names during this procedure as well as any necessary conversions on * the values applied. Scalar values are kept in a specific key 'scalars'. * - * @param array $data SQL Result Row. + * @param array $data SQL Result Row. * @param array &$id Dql-Alias => ID-Hash. * @param array &$nonemptyComponents Does this DQL-Alias has at least one non NULL value? * @@ -335,7 +337,7 @@ protected function gatherRowData(array $data, array &$id, array &$nonemptyCompon $fieldName = $cacheKeyInfo['fieldName']; switch (true) { - case (isset($cacheKeyInfo['isNewObjectParameter'])): + case isset($cacheKeyInfo['isNewObjectParameter']): $argIndex = $cacheKeyInfo['argIndex']; $objIndex = $cacheKeyInfo['objIndex']; $type = $cacheKeyInfo['type']; @@ -345,7 +347,7 @@ protected function gatherRowData(array $data, array &$id, array &$nonemptyCompon $rowData['newObjects'][$objIndex]['args'][$argIndex] = $value; break; - case (isset($cacheKeyInfo['isScalar'])): + case isset($cacheKeyInfo['isScalar']): $type = $cacheKeyInfo['type']; $value = $type->convertToPHPValue($value, $this->_platform); @@ -359,7 +361,8 @@ protected function gatherRowData(array $data, array &$id, array &$nonemptyCompon // If there are field name collisions in the child class, then we need // to only hydrate if we are looking at the correct discriminator value - if (isset($cacheKeyInfo['discriminatorColumn'], $data[$cacheKeyInfo['discriminatorColumn']]) + if ( + isset($cacheKeyInfo['discriminatorColumn'], $data[$cacheKeyInfo['discriminatorColumn']]) && ! in_array((string) $data[$cacheKeyInfo['discriminatorColumn']], $cacheKeyInfo['discriminatorValues'], true) ) { break; @@ -377,9 +380,10 @@ protected function gatherRowData(array $data, array &$id, array &$nonemptyCompon : $value; if ($cacheKeyInfo['isIdentifier'] && $value !== null) { - $id[$dqlAlias] .= '|' . $value; + $id[$dqlAlias] .= '|' . $value; $nonemptyComponents[$dqlAlias] = true; } + break; } } @@ -440,13 +444,13 @@ protected function hydrateColumnInfo($key) switch (true) { // NOTE: Most of the times it's a field mapping, so keep it first!!! - case (isset($this->_rsm->fieldMappings[$key])): + case isset($this->_rsm->fieldMappings[$key]): $classMetadata = $this->getClassMetadata($this->_rsm->declaringClasses[$key]); $fieldName = $this->_rsm->fieldMappings[$key]; $fieldMapping = $classMetadata->fieldMappings[$fieldName]; $ownerMap = $this->_rsm->columnOwnerMap[$key]; $columnInfo = [ - 'isIdentifier' => \in_array($fieldName, $classMetadata->identifier, true), + 'isIdentifier' => in_array($fieldName, $classMetadata->identifier, true), 'fieldName' => $fieldName, 'type' => Type::getType($fieldMapping['type']), 'dqlAlias' => $ownerMap, @@ -455,7 +459,7 @@ protected function hydrateColumnInfo($key) // the current discriminator value must be saved in order to disambiguate fields hydration, // should there be field name collisions if ($classMetadata->parentClasses && isset($this->_rsm->discriminatorColumns[$ownerMap])) { - return $this->_cache[$key] = \array_merge( + return $this->_cache[$key] = array_merge( $columnInfo, [ 'discriminatorColumn' => $this->_rsm->discriminatorColumns[$ownerMap], @@ -467,7 +471,7 @@ protected function hydrateColumnInfo($key) return $this->_cache[$key] = $columnInfo; - 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]; @@ -478,7 +482,7 @@ protected function hydrateColumnInfo($key) 'type' => Type::getType($this->_rsm->typeMappings[$key]), 'argIndex' => $mapping['argIndex'], 'objIndex' => $mapping['objIndex'], - 'class' => new \ReflectionClass($mapping['className']), + 'class' => new ReflectionClass($mapping['className']), ]; case isset($this->_rsm->scalarMappings[$key], $this->_hints[LimitSubqueryWalker::FORCE_DBAL_TYPE_CONVERSION]): @@ -487,14 +491,15 @@ protected function hydrateColumnInfo($key) 'type' => Type::getType($this->_rsm->typeMappings[$key]), 'dqlAlias' => '', ]; - case (isset($this->_rsm->scalarMappings[$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]), ]; - 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]; @@ -522,10 +527,10 @@ protected function hydrateColumnInfo($key) /** * @return string[] */ - private function getDiscriminatorValues(ClassMetadata $classMetadata) : array + private function getDiscriminatorValues(ClassMetadata $classMetadata): array { $values = array_map( - function (string $subClass) : string { + function (string $subClass): string { return (string) $this->getClassMetadata($subClass)->discriminatorValue; }, $classMetadata->subClasses @@ -541,11 +546,11 @@ function (string $subClass) : string { * * @param string $className * - * @return \Doctrine\ORM\Mapping\ClassMetadata + * @return ClassMetadata */ protected function getClassMetadata($className) { - if ( ! isset($this->_metadataCache[$className])) { + if (! isset($this->_metadataCache[$className])) { $this->_metadataCache[$className] = $this->_em->getClassMetadata($className); } @@ -555,9 +560,8 @@ protected function getClassMetadata($className) /** * Register entity as managed in UnitOfWork. * - * @param ClassMetadata $class - * @param object $entity - * @param array $data + * @param object $entity + * @param array $data * * @return void * @@ -578,7 +582,7 @@ protected function registerManaged(ClassMetadata $class, $entity, array $data) $id = [ $fieldName => isset($class->associationMappings[$fieldName]) ? $data[$class->associationMappings[$fieldName]['joinColumns'][0]['name']] - : $data[$fieldName] + : $data[$fieldName], ]; } diff --git a/lib/Doctrine/ORM/Internal/Hydration/ArrayHydrator.php b/lib/Doctrine/ORM/Internal/Hydration/ArrayHydrator.php index c26b99be38c..7e46315fa83 100644 --- a/lib/Doctrine/ORM/Internal/Hydration/ArrayHydrator.php +++ b/lib/Doctrine/ORM/Internal/Hydration/ArrayHydrator.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco */ class ArrayHydrator extends AbstractHydrator { - /** - * @var array - */ + /** @var array */ private $_rootAliases = []; - /** - * @var bool - */ + /** @var bool */ private $_isSimpleQuery = false; - /** - * @var array - */ + /** @var array */ private $_identifierMap = []; - /** - * @var array - */ + /** @var array */ private $_resultPointers = []; - /** - * @var array - */ + /** @var array */ private $_idTemplate = []; - /** - * @var int - */ + /** @var int */ private $_resultCounter = 0; /** @@ -96,9 +87,9 @@ 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); + $rowData = $this->gatherRowData($row, $id, $nonemptyComponents); // 2) Now hydrate the data found in the current row. foreach ($rowData['data'] as $dqlAlias => $data) { @@ -111,7 +102,7 @@ protected function hydrateRowData(array $row, array &$result) $path = $parent . '.' . $dqlAlias; // missing parent data, skipping as RIGHT JOIN hydration is not supported. - if ( ! isset($nonemptyComponents[$parent]) ) { + if (! isset($nonemptyComponents[$parent])) { continue; } @@ -121,7 +112,7 @@ protected function hydrateRowData(array $row, array &$result) $first = reset($this->_resultPointers); // TODO: Exception if $key === null ? $baseElement =& $this->_resultPointers[$parent][key($first)]; - } else if (isset($this->_resultPointers[$parent])) { + } elseif (isset($this->_resultPointers[$parent])) { $baseElement =& $this->_resultPointers[$parent]; } else { unset($this->_resultPointers[$dqlAlias]); // Ticket #1228 @@ -134,10 +125,10 @@ protected function hydrateRowData(array $row, array &$result) $relation = $parentClass->associationMappings[$relationAlias]; // Check the type of the relation (many or single-valued) - if ( ! ($relation['type'] & ClassMetadata::TO_ONE)) { + if (! ($relation['type'] & ClassMetadata::TO_ONE)) { $oneToOne = false; - if ( ! isset($baseElement[$relationAlias])) { + if (! isset($baseElement[$relationAlias])) { $baseElement[$relationAlias] = []; } @@ -146,7 +137,7 @@ protected function hydrateRowData(array $row, array &$result) $index = $indexExists ? $this->_identifierMap[$path][$id[$parent]][$id[$dqlAlias]] : false; $indexIsValid = $index !== false ? isset($baseElement[$relationAlias][$index]) : false; - if ( ! $indexExists || ! $indexIsValid) { + if (! $indexExists || ! $indexIsValid) { $element = $data; if (isset($this->_rsm->indexByMap[$dqlAlias])) { @@ -164,11 +155,11 @@ protected function hydrateRowData(array $row, array &$result) $oneToOne = true; if ( - ( ! isset($nonemptyComponents[$dqlAlias])) && + ! isset($nonemptyComponents[$dqlAlias]) && ( ! isset($baseElement[$relationAlias])) ) { $baseElement[$relationAlias] = null; - } else if ( ! isset($baseElement[$relationAlias])) { + } elseif (! isset($baseElement[$relationAlias])) { $baseElement[$relationAlias] = $data; } } @@ -182,10 +173,10 @@ protected function hydrateRowData(array $row, array &$result) // It's a root result element $this->_rootAliases[$dqlAlias] = true; // Mark as root - $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 (! isset($nonemptyComponents[$dqlAlias])) { $result[] = $this->_rsm->isMixed ? [$entityKey => null] : null; @@ -203,18 +194,18 @@ protected function hydrateRowData(array $row, array &$result) : $data; if (isset($this->_rsm->indexByMap[$dqlAlias])) { - $resultKey = $row[$this->_rsm->indexByMap[$dqlAlias]]; + $resultKey = $row[$this->_rsm->indexByMap[$dqlAlias]]; $result[$resultKey] = $element; } else { $resultKey = $this->_resultCounter; - $result[] = $element; + $result[] = $element; ++$this->_resultCounter; } $this->_identifierMap[$dqlAlias][$id[$dqlAlias]] = $resultKey; } else { - $index = $this->_identifierMap[$dqlAlias][$id[$dqlAlias]]; + $index = $this->_identifierMap[$dqlAlias][$id[$dqlAlias]]; $resultKey = $index; } @@ -222,13 +213,13 @@ protected function hydrateRowData(array $row, array &$result) } } - if ( ! isset($resultKey)) { + if (! isset($resultKey)) { $this->_resultCounter++; } // Append scalar values to mixed result sets if (isset($rowData['scalars'])) { - if ( ! isset($resultKey)) { + 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']] @@ -242,18 +233,18 @@ protected function hydrateRowData(array $row, array &$result) // Append new object to mixed result sets if (isset($rowData['newObjects'])) { - if ( ! isset($resultKey)) { + if (! isset($resultKey)) { $resultKey = $this->_resultCounter - 1; } - $scalarCount = (isset($rowData['scalars'])? count($rowData['scalars']): 0); + $scalarCount = (isset($rowData['scalars']) ? count($rowData['scalars']) : 0); foreach ($rowData['newObjects'] as $objIndex => $newObject) { - $class = $newObject['class']; - $args = $newObject['args']; - $obj = $class->newInstanceArgs($args); + $class = $newObject['class']; + $args = $newObject['args']; + $obj = $class->newInstanceArgs($args); - if (count($args) == $scalarCount || ($scalarCount == 0 && count($rowData['newObjects']) == 1)) { + if (count($args) === $scalarCount || ($scalarCount === 0 && count($rowData['newObjects']) === 1)) { $result[$resultKey] = $obj; continue; @@ -268,10 +259,10 @@ protected function hydrateRowData(array $row, array &$result) * Updates the result pointer for an Entity. The result pointers point to the * last seen instance of each Entity type. This is used for graph construction. * - * @param array $coll The element. - * @param boolean|integer $index Index of the element in the collection. - * @param string $dqlAlias - * @param boolean $oneToOne Whether it is a single-valued association or not. + * @param array $coll The element. + * @param bool|int $index Index of the element in the collection. + * @param string $dqlAlias + * @param bool $oneToOne Whether it is a single-valued association or not. * * @return void */ @@ -295,7 +286,7 @@ private function updateResultPointer(array &$coll, $index, $dqlAlias, $oneToOne) return; } - if ( ! $coll) { + if (! $coll) { return; } diff --git a/lib/Doctrine/ORM/Internal/Hydration/HydrationException.php b/lib/Doctrine/ORM/Internal/Hydration/HydrationException.php index 9caf03ddfb9..753d2fcfe36 100644 --- a/lib/Doctrine/ORM/Internal/Hydration/HydrationException.php +++ b/lib/Doctrine/ORM/Internal/Hydration/HydrationException.php @@ -1,4 +1,5 @@ _rewinded == true) { - throw new HydrationException("Can only iterate a Result once."); + if ($this->_rewinded === true) { + throw new HydrationException('Can only iterate a Result once.'); } else { - $this->_current = $this->next(); + $this->_current = $this->next(); $this->_rewinded = true; } } @@ -104,6 +99,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 5048216cf7b..e3804b3d4c8 100644 --- a/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php +++ b/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Fabio B. Silva */ class ObjectHydrator extends AbstractHydrator { - /** - * @var array - */ + /** @var array */ private $identifierMap = []; - /** - * @var array - */ + /** @var array */ private $resultPointers = []; - /** - * @var array - */ + /** @var array */ private $idTemplate = []; - /** - * @var integer - */ + /** @var int */ private $resultCounter = 0; - /** - * @var array - */ + /** @var array */ private $rootAliases = []; - /** - * @var array - */ + /** @var array */ private $initializedCollections = []; - /** - * @var array - */ + /** @var array */ private $existingCollections = []; /** @@ -79,7 +69,7 @@ class ObjectHydrator extends AbstractHydrator */ protected function prepare() { - if ( ! isset($this->_hints[UnitOfWork::HINT_DEFEREAGERLOAD])) { + if (! isset($this->_hints[UnitOfWork::HINT_DEFEREAGERLOAD])) { $this->_hints[UnitOfWork::HINT_DEFEREAGERLOAD] = true; } @@ -89,13 +79,13 @@ protected function prepare() // 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]; - if ( ! isset($this->_rsm->aliasMap[$parent])) { + if (! isset($this->_rsm->aliasMap[$parent])) { throw HydrationException::parentObjectOfRelationNotFound($dqlAlias, $parent); } @@ -121,7 +111,7 @@ protected function prepare() $class = $this->getClassMetadata($className); $inverseAssoc = $class->associationMappings[$assoc['inversedBy']]; - if ( ! ($inverseAssoc['type'] & ClassMetadata::TO_ONE)) { + if (! ($inverseAssoc['type'] & ClassMetadata::TO_ONE)) { continue; } @@ -135,14 +125,14 @@ 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(); - $this->identifierMap = + $this->identifierMap = $this->initializedCollections = - $this->existingCollections = - $this->resultPointers = []; + $this->existingCollections = + $this->resultPointers = []; if ($eagerLoad) { $this->_uow->triggerEagerLoads(); @@ -178,7 +168,7 @@ protected function hydrateAllData() * @param string $fieldName The name of the field on the entity that holds the collection. * @param string $parentDqlAlias Alias of the parent fetch joining this collection. * - * @return \Doctrine\ORM\PersistentCollection + * @return PersistentCollection */ private function initRelatedCollection($entity, $class, $fieldName, $parentDqlAlias) { @@ -190,9 +180,11 @@ private function initRelatedCollection($entity, $class, $fieldName, $parentDqlAl $value = new ArrayCollection((array) $value); } - if ( ! $value instanceof PersistentCollection) { + if (! $value instanceof PersistentCollection) { $value = new PersistentCollection( - $this->_em, $this->_metadataCache[$relation['targetEntity']], $value + $this->_em, + $this->_metadataCache[$relation['targetEntity']], + $value ); $value->setOwner($entity, $relation); @@ -200,7 +192,7 @@ private function initRelatedCollection($entity, $class, $fieldName, $parentDqlAl $this->_uow->setOriginalEntityProperty($oid, $fieldName, $value); $this->initializedCollections[$oid . $fieldName] = $value; - } else if ( + } elseif ( isset($this->_hints[Query::HINT_REFRESH]) || isset($this->_hints['fetched'][$parentDqlAlias][$fieldName]) && ! $value->isInitialized() @@ -236,24 +228,24 @@ private function getEntity(array $data, $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]; - if ( ! isset($data[$discrColumn])) { + if (! isset($data[$discrColumn])) { throw HydrationException::missingDiscriminatorColumn($className, $discrColumn, $dqlAlias); } - if ($data[$discrColumn] === "") { + if ($data[$discrColumn] === '') { throw HydrationException::emptyDiscriminatorValue($dqlAlias); } - $discrMap = $this->_metadataCache[$className]->discriminatorMap; + $discrMap = $this->_metadataCache[$className]->discriminatorMap; $discriminatorValue = (string) $data[$discrColumn]; - if ( ! isset($discrMap[$discriminatorValue])) { + if (! isset($discrMap[$discriminatorValue])) { throw HydrationException::invalidDiscriminatorValue($discriminatorValue, array_keys($discrMap)); } @@ -282,7 +274,7 @@ private function getEntityFromIdentityMap($className, array $data) // TODO: Abstract this code and UnitOfWork::createEntity() equivalent? $class = $this->_metadataCache[$className]; - /* @var $class ClassMetadata */ + /** @var ClassMetadata $class */ if ($class->isIdentifierComposite) { $idHash = ''; @@ -293,7 +285,7 @@ private function getEntityFromIdentityMap($className, array $data) } return $this->_uow->tryGetByIdHash(ltrim($idHash), $class->rootEntityName); - } else if (isset($class->associationMappings[$class->identifier[0]])) { + } elseif (isset($class->associationMappings[$class->identifier[0]])) { return $this->_uow->tryGetByIdHash($data[$class->associationMappings[$class->identifier[0]]['joinColumns'][0]['name']], $class->rootEntityName); } @@ -325,7 +317,7 @@ private function getEntityFromIdentityMap($className, array $data) protected function hydrateRowData(array $row, array &$result) { // Initialize - $id = $this->idTemplate; // initialize the id-memory + $id = $this->idTemplate; // initialize the id-memory $nonemptyComponents = []; // Split the row data into chunks of class data. $rowData = $this->gatherRowData($row, $id, $nonemptyComponents); @@ -346,28 +338,28 @@ protected function hydrateRowData(array $row, array &$result) $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]; + $relation = $parentClass->associationMappings[$relationField]; + $reflField = $parentClass->reflFields[$relationField]; // Get a reference to the parent object to which the joined element belongs. if ($this->_rsm->isMixed && isset($this->rootAliases[$parentAlias])) { - $objectClass = $this->resultPointers[$parentAlias]; + $objectClass = $this->resultPointers[$parentAlias]; $parentObject = $objectClass[key($objectClass)]; - } else if (isset($this->resultPointers[$parentAlias])) { + } elseif (isset($this->resultPointers[$parentAlias])) { $parentObject = $this->resultPointers[$parentAlias]; } else { // Parent object of relation not found, mark as not-fetched again $element = $this->getEntity($data, $dqlAlias); // Update result pointer and provide initial fetch data for parent - $this->resultPointers[$dqlAlias] = $element; + $this->resultPointers[$dqlAlias] = $element; $rowData['data'][$parentAlias][$relationField] = $element; // Mark as not-fetched again @@ -378,7 +370,7 @@ protected function hydrateRowData(array $row, array &$result) $oid = spl_object_hash($parentObject); // Check the type of the relation (many or single-valued) - if ( ! ($relation['type'] & ClassMetadata::TO_ONE)) { + if (! ($relation['type'] & ClassMetadata::TO_ONE)) { // PATH A: Collection-valued association $reflFieldValue = $reflField->getValue($parentObject); @@ -386,15 +378,15 @@ protected function hydrateRowData(array $row, array &$result) $collKey = $oid . $relationField; if (isset($this->initializedCollections[$collKey])) { $reflFieldValue = $this->initializedCollections[$collKey]; - } else if ( ! isset($this->existingCollections[$collKey])) { + } elseif (! isset($this->existingCollections[$collKey])) { $reflFieldValue = $this->initRelatedCollection($parentObject, $parentClass, $relationField, $parentAlias); } - $indexExists = isset($this->identifierMap[$path][$id[$parentAlias]][$id[$dqlAlias]]); - $index = $indexExists ? $this->identifierMap[$path][$id[$parentAlias]][$id[$dqlAlias]] : false; - $indexIsValid = $index !== false ? isset($reflFieldValue[$index]) : false; + $indexExists = isset($this->identifierMap[$path][$id[$parentAlias]][$id[$dqlAlias]]); + $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)) { @@ -414,6 +406,7 @@ protected function hydrateRowData(array $row, array &$result) $reflFieldValue->last(); $this->identifierMap[$path][$id[$parentAlias]][$id[$dqlAlias]] = $reflFieldValue->key(); } + // Update result pointer $this->resultPointers[$dqlAlias] = $element; } @@ -421,17 +414,16 @@ protected function hydrateRowData(array $row, array &$result) // Update result pointer $this->resultPointers[$dqlAlias] = $reflFieldValue[$index]; } - } else if ( ! $reflFieldValue) { + } elseif (! $reflFieldValue) { $this->initRelatedCollection($parentObject, $parentClass, $relationField, $parentAlias); - } else if ($reflFieldValue instanceof PersistentCollection && $reflFieldValue->isInitialized() === false) { + } elseif ($reflFieldValue instanceof PersistentCollection && $reflFieldValue->isInitialized() === false) { $reflFieldValue->setInitialized(true); } - } else { // PATH B: Single-valued association $reflFieldValue = $reflField->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])) { @@ -449,7 +441,7 @@ protected function hydrateRowData(array $row, array &$result) $targetClass->reflFields[$inverseAssoc['fieldName']]->setValue($element, $parentObject); $this->_uow->setOriginalEntityProperty(spl_object_hash($element), $inverseAssoc['fieldName'], $parentObject); } - } else if ($parentClass === $targetClass && $relation['mappedBy']) { + } elseif ($parentClass === $targetClass && $relation['mappedBy']) { // Special case: bi-directional self-referencing one-one on the same class $targetClass->reflFields[$relationField]->setValue($element, $parentObject); } @@ -458,6 +450,7 @@ protected function hydrateRowData(array $row, array &$result) $targetClass->reflFields[$relation['mappedBy']]->setValue($element, $parentObject); $this->_uow->setOriginalEntityProperty(spl_object_hash($element), $relation['mappedBy'], $parentObject); } + // Update result pointer $this->resultPointers[$dqlAlias] = $element; } else { @@ -473,22 +466,23 @@ 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 (! isset($nonemptyComponents[$dqlAlias])) { if ($this->_rsm->isMixed) { $result[] = [$entityKey => null]; } else { $result[] = null; } + $resultKey = $this->resultCounter; ++$this->resultCounter; continue; } // check for existing result from the iterations before - if ( ! isset($this->identifierMap[$dqlAlias][$id[$dqlAlias]])) { + if (! isset($this->identifierMap[$dqlAlias][$id[$dqlAlias]])) { $element = $this->getEntity($data, $dqlAlias); if ($this->_rsm->isMixed) { @@ -518,12 +512,11 @@ protected function hydrateRowData(array $row, array &$result) // Update result pointer $this->resultPointers[$dqlAlias] = $element; - } else { // Update result pointer - $index = $this->identifierMap[$dqlAlias][$id[$dqlAlias]]; + $index = $this->identifierMap[$dqlAlias][$id[$dqlAlias]]; $this->resultPointers[$dqlAlias] = $result[$index]; - $resultKey = $index; + $resultKey = $index; } } @@ -532,14 +525,14 @@ protected function hydrateRowData(array $row, array &$result) } } - if ( ! isset($resultKey) ) { + if (! isset($resultKey)) { $this->resultCounter++; } // Append scalar values to mixed result sets if (isset($rowData['scalars'])) { - if ( ! isset($resultKey) ) { - $resultKey = (isset($this->_rsm->indexByMap['scalars'])) + if (! isset($resultKey)) { + $resultKey = isset($this->_rsm->indexByMap['scalars']) ? $row[$this->_rsm->indexByMap['scalars']] : $this->resultCounter - 1; } @@ -551,19 +544,18 @@ protected function hydrateRowData(array $row, array &$result) // Append new object to mixed result sets if (isset($rowData['newObjects'])) { - if ( ! isset($resultKey) ) { + if (! isset($resultKey)) { $resultKey = $this->resultCounter - 1; } - - $scalarCount = (isset($rowData['scalars'])? count($rowData['scalars']): 0); + $scalarCount = (isset($rowData['scalars']) ? count($rowData['scalars']) : 0); foreach ($rowData['newObjects'] as $objIndex => $newObject) { - $class = $newObject['class']; - $args = $newObject['args']; - $obj = $class->newInstanceArgs($args); + $class = $newObject['class']; + $args = $newObject['args']; + $obj = $class->newInstanceArgs($args); - if ($scalarCount == 0 && count($rowData['newObjects']) == 1 ) { + if ($scalarCount === 0 && count($rowData['newObjects']) === 1) { $result[$resultKey] = $obj; continue; @@ -586,7 +578,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 56ce39bdc3c..4deed60e777 100644 --- a/lib/Doctrine/ORM/Internal/Hydration/ScalarHydrator.php +++ b/lib/Doctrine/ORM/Internal/Hydration/ScalarHydrator.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco */ class ScalarHydrator extends AbstractHydrator { @@ -37,7 +36,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 4f16cb03c06..09380fc31b5 100644 --- a/lib/Doctrine/ORM/Internal/Hydration/SimpleObjectHydrator.php +++ b/lib/Doctrine/ORM/Internal/Hydration/SimpleObjectHydrator.php @@ -1,4 +1,5 @@ _rsm->aliasMap) !== 1) { - throw new \RuntimeException("Cannot use SimpleObjectHydrator with a ResultSetMapping that contains more than one object result."); + throw new RuntimeException('Cannot use SimpleObjectHydrator with a ResultSetMapping that contains more than one object result.'); } if ($this->_rsm->scalarMappings) { - throw new \RuntimeException("Cannot use SimpleObjectHydrator with a ResultSetMapping that contains scalar mappings."); + throw new RuntimeException('Cannot use SimpleObjectHydrator with a ResultSetMapping that contains scalar mappings.'); } $this->class = $this->getClassMetadata(reset($this->_rsm->aliasMap)); @@ -116,17 +123,17 @@ protected function hydrateRowData(array $row, array &$result) foreach ($row as $column => $value) { // An ObjectHydrator should be used instead of SimpleObjectHydrator if (isset($this->_rsm->relationMap[$column])) { - throw new \Exception(sprintf('Unable to retrieve association information for column "%s"', $column)); + throw new Exception(sprintf('Unable to retrieve association information for column "%s"', $column)); } $cacheKeyInfo = $this->hydrateColumnInfo($column); - if ( ! $cacheKeyInfo) { + if (! $cacheKeyInfo) { continue; } // Check if value is null before conversion (because some types convert null to something else) - $valueIsNull = null === $value; + $valueIsNull = $value === null; // Convert field to a valid PHP value if (isset($cacheKeyInfo['type'])) { @@ -137,7 +144,7 @@ protected function hydrateRowData(array $row, array &$result) $fieldName = $cacheKeyInfo['fieldName']; // Prevent overwrite in case of inherit classes using same property name (See AbstractHydrator) - if ( ! isset($data[$fieldName]) || ! $valueIsNull) { + if (! isset($data[$fieldName]) || ! $valueIsNull) { // If we have inheritance in resultset, make sure the field belongs to the correct class if (isset($cacheKeyInfo['discriminatorValues']) && ! in_array((string) $discrColumnValue, $cacheKeyInfo['discriminatorValues'], true)) { continue; diff --git a/lib/Doctrine/ORM/Internal/Hydration/SingleScalarHydrator.php b/lib/Doctrine/ORM/Internal/Hydration/SingleScalarHydrator.php index b9caeb11b83..2eb652b2031 100644 --- a/lib/Doctrine/ORM/Internal/Hydration/SingleScalarHydrator.php +++ b/lib/Doctrine/ORM/Internal/Hydration/SingleScalarHydrator.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco */ class SingleScalarHydrator extends AbstractHydrator { @@ -36,7 +38,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) { @@ -46,7 +48,7 @@ protected function hydrateAllData() if ($numRows > 1) { throw new NonUniqueResultException('The query returned multiple rows. Change the query or use a different result function like getScalarResult().'); } - + if (count($data[key($data)]) > 1) { throw new NonUniqueResultException('The query returned a row containing multiple columns. Change the query or use a different result function like getScalarResult().'); } diff --git a/lib/Doctrine/ORM/Internal/HydrationCompleteHandler.php b/lib/Doctrine/ORM/Internal/HydrationCompleteHandler.php index 480cc13807a..ee5af437cb8 100644 --- a/lib/Doctrine/ORM/Internal/HydrationCompleteHandler.php +++ b/lib/Doctrine/ORM/Internal/HydrationCompleteHandler.php @@ -1,4 +1,5 @@ - * @since 2.5 */ final class HydrationCompleteHandler { - /** - * @var ListenersInvoker - */ + /** @var ListenersInvoker */ private $listenersInvoker; - /** - * @var EntityManagerInterface - */ + /** @var EntityManagerInterface */ private $em; - /** - * @var array[] - */ + /** @var array[] */ private $deferredPostLoadInvocations = []; /** * Constructor for this object - * - * @param ListenersInvoker $listenersInvoker - * @param EntityManagerInterface $em */ public function __construct(ListenersInvoker $listenersInvoker, EntityManagerInterface $em) { @@ -64,8 +53,7 @@ public function __construct(ListenersInvoker $listenersInvoker, EntityManagerInt /** * Method schedules invoking of postLoad entity to the very end of current hydration cycle. * - * @param ClassMetadata $class - * @param object $entity + * @param object $entity */ public function deferPostLoadInvoking(ClassMetadata $class, $entity) { diff --git a/lib/Doctrine/ORM/LazyCriteriaCollection.php b/lib/Doctrine/ORM/LazyCriteriaCollection.php index ad0238fbb95..1cd64d83514 100644 --- a/lib/Doctrine/ORM/LazyCriteriaCollection.php +++ b/lib/Doctrine/ORM/LazyCriteriaCollection.php @@ -1,4 +1,5 @@ - * @author Michaël Gallego */ class LazyCriteriaCollection extends AbstractLazyCollection implements Selectable { - /** - * @var BasicEntityPersister - */ + /** @var BasicEntityPersister */ protected $entityPersister; - /** - * @var Criteria - */ + /** @var Criteria */ protected $criteria; - /** - * @var integer|null - */ + /** @var int|null */ private $count; - /** - * @param EntityPersister $entityPersister - * @param Criteria $criteria - */ public function __construct(EntityPersister $entityPersister, Criteria $criteria) { $this->entityPersister = $entityPersister; @@ -66,7 +53,7 @@ public function __construct(EntityPersister $entityPersister, Criteria $criteria /** * Do an efficient count on the collection * - * @return integer + * @return int */ public function count() { @@ -85,7 +72,7 @@ public function count() /** * check if collection is empty without loading it * - * @return boolean TRUE if the collection is empty, FALSE otherwise. + * @return bool TRUE if the collection is empty, FALSE otherwise. */ public function isEmpty() { @@ -93,7 +80,7 @@ public function isEmpty() return $this->collection->isEmpty(); } - return !$this->count(); + return ! $this->count(); } /** diff --git a/lib/Doctrine/ORM/Mapping/Annotation.php b/lib/Doctrine/ORM/Mapping/Annotation.php index 19374ff3146..96e3a22aae3 100644 --- a/lib/Doctrine/ORM/Mapping/Annotation.php +++ b/lib/Doctrine/ORM/Mapping/Annotation.php @@ -1,4 +1,5 @@ */ class AnsiQuoteStrategy implements QuoteStrategy { @@ -89,7 +87,7 @@ public function getIdentifierColumnNames(ClassMetadata $class, AbstractPlatform /** * {@inheritdoc} */ - public function getColumnAlias($columnName, $counter, AbstractPlatform $platform, ClassMetadata $class = null) + public function getColumnAlias($columnName, $counter, AbstractPlatform $platform, ?ClassMetadata $class = null) { return $platform->getSQLResultCasing($columnName . '_' . $counter); } diff --git a/lib/Doctrine/ORM/Mapping/AssociationOverride.php b/lib/Doctrine/ORM/Mapping/AssociationOverride.php index e208b16228a..031eedd69ec 100644 --- a/lib/Doctrine/ORM/Mapping/AssociationOverride.php +++ b/lib/Doctrine/ORM/Mapping/AssociationOverride.php @@ -1,4 +1,5 @@ - * @since 2.3 - * * @Annotation * @Target("ANNOTATION") */ @@ -32,8 +30,8 @@ final class AssociationOverride implements Annotation { /** * The name of the relationship property whose mapping is being overridden. - * - * @var string + * + * @var string */ public $name; @@ -62,7 +60,6 @@ final class AssociationOverride implements Annotation * 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 index 217c9e45735..9f2eca11f74 100644 --- a/lib/Doctrine/ORM/Mapping/AssociationOverrides.php +++ b/lib/Doctrine/ORM/Mapping/AssociationOverrides.php @@ -1,4 +1,5 @@ - * @since 2.3 - * * @Annotation * @Target("CLASS") */ @@ -33,7 +31,7 @@ final class AssociationOverrides implements Annotation /** * Mapping overrides of relationship properties. * - * @var array<\Doctrine\ORM\Mapping\AssociationOverride> + * @var array<\Doctrine\ORM\Mapping\AssociationOverride> */ public $value; } diff --git a/lib/Doctrine/ORM/Mapping/AttributeOverride.php b/lib/Doctrine/ORM/Mapping/AttributeOverride.php index f86d3a1521d..ef85b904452 100644 --- a/lib/Doctrine/ORM/Mapping/AttributeOverride.php +++ b/lib/Doctrine/ORM/Mapping/AttributeOverride.php @@ -1,4 +1,5 @@ - * @since 2.3 - * * @Annotation * @Target("ANNOTATION") */ @@ -32,8 +30,8 @@ final class AttributeOverride implements Annotation { /** * The name of the property whose mapping is being overridden. - * - * @var string + * + * @var string */ public $name; diff --git a/lib/Doctrine/ORM/Mapping/AttributeOverrides.php b/lib/Doctrine/ORM/Mapping/AttributeOverrides.php index 63b2cc66e7f..b84341fb2cd 100644 --- a/lib/Doctrine/ORM/Mapping/AttributeOverrides.php +++ b/lib/Doctrine/ORM/Mapping/AttributeOverrides.php @@ -1,4 +1,5 @@ - * @since 2.3 - * * @Annotation * @Target("CLASS") */ diff --git a/lib/Doctrine/ORM/Mapping/Builder/AssociationBuilder.php b/lib/Doctrine/ORM/Mapping/Builder/AssociationBuilder.php index ff2f3d281c9..356d196491f 100644 --- a/lib/Doctrine/ORM/Mapping/Builder/AssociationBuilder.php +++ b/lib/Doctrine/ORM/Mapping/Builder/AssociationBuilder.php @@ -1,4 +1,5 @@ builder = $builder; $this->mapping = $mapping; - $this->type = $type; + $this->type = $type; } /** @@ -84,7 +77,7 @@ public function inversedBy($fieldName) */ public function cascadeAll() { - $this->mapping['cascade'] = ["ALL"]; + $this->mapping['cascade'] = ['ALL']; return $this; } @@ -94,7 +87,7 @@ public function cascadeAll() */ public function cascadePersist() { - $this->mapping['cascade'][] = "persist"; + $this->mapping['cascade'][] = 'persist'; return $this; } @@ -104,7 +97,7 @@ public function cascadePersist() */ public function cascadeRemove() { - $this->mapping['cascade'][] = "remove"; + $this->mapping['cascade'][] = 'remove'; return $this; } @@ -114,7 +107,7 @@ public function cascadeRemove() */ public function cascadeMerge() { - $this->mapping['cascade'][] = "merge"; + $this->mapping['cascade'][] = 'merge'; return $this; } @@ -124,7 +117,7 @@ public function cascadeMerge() */ public function cascadeDetach() { - $this->mapping['cascade'][] = "detach"; + $this->mapping['cascade'][] = 'detach'; return $this; } @@ -134,7 +127,7 @@ public function cascadeDetach() */ public function cascadeRefresh() { - $this->mapping['cascade'][] = "refresh"; + $this->mapping['cascade'][] = 'refresh'; return $this; } @@ -222,7 +215,7 @@ public function orphanRemoval() /** * @return ClassMetadataBuilder * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public function build() { @@ -230,13 +223,14 @@ public function build() if ($this->joinColumns) { $mapping['joinColumns'] = $this->joinColumns; } + $cm = $this->builder->getClassMetadata(); - if ($this->type == ClassMetadata::MANY_TO_ONE) { + if ($this->type === ClassMetadata::MANY_TO_ONE) { $cm->mapManyToOne($mapping); - } else if ($this->type == ClassMetadata::ONE_TO_ONE) { + } elseif ($this->type === ClassMetadata::ONE_TO_ONE) { $cm->mapOneToOne($mapping); } else { - throw new \InvalidArgumentException("Type should be a ToOne Association here"); + 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 index dc7faf40915..e7f50ded774 100644 --- a/lib/Doctrine/ORM/Mapping/Builder/ClassMetadataBuilder.php +++ b/lib/Doctrine/ORM/Mapping/Builder/ClassMetadataBuilder.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco */ class ClassMetadataBuilder { - /** - * @var \Doctrine\ORM\Mapping\ClassMetadataInfo - */ + /** @var ClassMetadataInfo */ private $cm; - /** - * @param \Doctrine\ORM\Mapping\ClassMetadataInfo $cm - */ public function __construct(ClassMetadataInfo $cm) { $this->cm = $cm; @@ -62,7 +54,7 @@ public function getClassMetadata() public function setMappedSuperClass() { $this->cm->isMappedSuperclass = true; - $this->cm->isEmbeddedClass = false; + $this->cm->isEmbeddedClass = false; return $this; } @@ -74,7 +66,7 @@ public function setMappedSuperClass() */ public function setEmbeddable() { - $this->cm->isEmbeddedClass = true; + $this->cm->isEmbeddedClass = true; $this->cm->isMappedSuperclass = false; return $this; @@ -95,7 +87,7 @@ public function addEmbedded($fieldName, $class, $columnPrefix = null) [ 'fieldName' => $fieldName, 'class' => $class, - 'columnPrefix' => $columnPrefix + 'columnPrefix' => $columnPrefix, ] ); @@ -152,7 +144,7 @@ public function setTable($name) */ public function addIndex(array $columns, $name) { - if (!isset($this->cm->table['indexes'])) { + if (! isset($this->cm->table['indexes'])) { $this->cm->table['indexes'] = []; } @@ -171,7 +163,7 @@ public function addIndex(array $columns, $name) */ public function addUniqueConstraint(array $columns, $name) { - if ( ! isset($this->cm->table['uniqueConstraints'])) { + if (! isset($this->cm->table['uniqueConstraints'])) { $this->cm->table['uniqueConstraints'] = []; } @@ -312,7 +304,7 @@ public function addLifecycleEvent($methodName, $event) public function addField($name, $type, array $mapping = []) { $mapping['fieldName'] = $name; - $mapping['type'] = $type; + $mapping['type'] = $type; $this->cm->mapField($mapping); @@ -333,7 +325,7 @@ public function createField($name, $type) $this, [ 'fieldName' => $name, - 'type' => $type + 'type' => $type, ] ); } @@ -353,7 +345,7 @@ public function createEmbedded($fieldName, $class) [ 'fieldName' => $fieldName, 'class' => $class, - 'columnPrefix' => null + 'columnPrefix' => null, ] ); } @@ -394,7 +386,7 @@ public function createManyToOne($name, $targetEntity) $this, [ 'fieldName' => $name, - 'targetEntity' => $targetEntity + 'targetEntity' => $targetEntity, ], ClassMetadata::MANY_TO_ONE ); @@ -414,7 +406,7 @@ public function createOneToOne($name, $targetEntity) $this, [ 'fieldName' => $name, - 'targetEntity' => $targetEntity + 'targetEntity' => $targetEntity, ], ClassMetadata::ONE_TO_ONE ); @@ -471,7 +463,7 @@ public function createManyToMany($name, $targetEntity) $this, [ 'fieldName' => $name, - 'targetEntity' => $targetEntity + 'targetEntity' => $targetEntity, ], ClassMetadata::MANY_TO_MANY ); @@ -528,7 +520,7 @@ public function createOneToMany($name, $targetEntity) $this, [ 'fieldName' => $name, - 'targetEntity' => $targetEntity + 'targetEntity' => $targetEntity, ], ClassMetadata::ONE_TO_MANY ); diff --git a/lib/Doctrine/ORM/Mapping/Builder/EmbeddedBuilder.php b/lib/Doctrine/ORM/Mapping/Builder/EmbeddedBuilder.php index de8383c5357..94bebe1d3ef 100644 --- a/lib/Doctrine/ORM/Mapping/Builder/EmbeddedBuilder.php +++ b/lib/Doctrine/ORM/Mapping/Builder/EmbeddedBuilder.php @@ -1,4 +1,5 @@ */ class EmbeddedBuilder { - /** - * @var ClassMetadataBuilder - */ + /** @var ClassMetadataBuilder */ private $builder; - /** - * @var array - */ + /** @var array */ private $mapping; /** - * @param ClassMetadataBuilder $builder - * @param array $mapping + * @param array $mapping */ public function __construct(ClassMetadataBuilder $builder, array $mapping) { @@ -53,6 +46,7 @@ public function __construct(ClassMetadataBuilder $builder, array $mapping) * Sets the column prefix for all of the embedded columns. * * @param string $columnPrefix + * * @return $this */ public function setColumnPrefix($columnPrefix) diff --git a/lib/Doctrine/ORM/Mapping/Builder/EntityListenerBuilder.php b/lib/Doctrine/ORM/Mapping/Builder/EntityListenerBuilder.php index e962726091c..dfa507d14e3 100644 --- a/lib/Doctrine/ORM/Mapping/Builder/EntityListenerBuilder.php +++ b/lib/Doctrine/ORM/Mapping/Builder/EntityListenerBuilder.php @@ -1,4 +1,5 @@ */ class EntityListenerBuilder { - /** - * @var array Hash-map to handle event names. - */ - static private $events = [ + /** @var array Hash-map to handle event names. */ + private static $events = [ Events::preRemove => true, Events::postRemove => true, Events::prePersist => true, @@ -42,27 +41,27 @@ class EntityListenerBuilder Events::preUpdate => true, Events::postUpdate => true, Events::postLoad => true, - Events::preFlush => 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. + * @param ClassMetadata $metadata The entity metadata. + * @param string $className The listener class name. * - * @throws \Doctrine\ORM\Mapping\MappingException When the listener class not found. + * @throws MappingException When the listener class not found. */ - static public function bindEntityListener(ClassMetadata $metadata, $className) + public static function bindEntityListener(ClassMetadata $metadata, $className) { $class = $metadata->fullyQualifiedClassName($className); - if ( ! class_exists($class)) { + if (! class_exists($class)) { throw MappingException::entityListenerClassNotFound($class, $className); } foreach (get_class_methods($class) as $method) { - if ( ! isset(self::$events[$method])) { + if (! isset(self::$events[$method])) { continue; } diff --git a/lib/Doctrine/ORM/Mapping/Builder/FieldBuilder.php b/lib/Doctrine/ORM/Mapping/Builder/FieldBuilder.php index 68ad14430e1..84595c43376 100644 --- a/lib/Doctrine/ORM/Mapping/Builder/FieldBuilder.php +++ b/lib/Doctrine/ORM/Mapping/Builder/FieldBuilder.php @@ -1,4 +1,5 @@ */ class FieldBuilder { - /** - * @var ClassMetadataBuilder - */ + /** @var ClassMetadataBuilder */ private $builder; - /** - * @var array - */ + /** @var array */ private $mapping; - /** - * @var bool - */ + /** @var bool */ private $version; - /** - * @var string - */ + /** @var string */ private $generatedValue; - /** - * @var array - */ + /** @var array */ private $sequenceDef; - /** - * @var string|null - */ + /** @var string|null */ private $customIdGenerator; /** - * @param ClassMetadataBuilder $builder - * @param array $mapping + * @param array $mapping */ public function __construct(ClassMetadataBuilder $builder, array $mapping) { @@ -157,6 +144,7 @@ public function scale($s) * Sets field as primary key. * * @deprecated Use makePrimaryKey() instead + * * @return FieldBuilder */ public function isPrimaryKey() diff --git a/lib/Doctrine/ORM/Mapping/Builder/ManyToManyAssociationBuilder.php b/lib/Doctrine/ORM/Mapping/Builder/ManyToManyAssociationBuilder.php index dce8c4562f9..2d0ff7d088a 100644 --- a/lib/Doctrine/ORM/Mapping/Builder/ManyToManyAssociationBuilder.php +++ b/lib/Doctrine/ORM/Mapping/Builder/ManyToManyAssociationBuilder.php @@ -1,4 +1,5 @@ */ class ManyToManyAssociationBuilder extends OneToManyAssociationBuilder { - /** - * @var string|null - */ + /** @var string|null */ private $joinTableName; - /** - * @var array - */ + /** @var array */ private $inverseJoinColumns = []; /** @@ -82,17 +76,20 @@ public function addInverseJoinColumn($columnName, $referencedColumnName, $nullab */ public function build() { - $mapping = $this->mapping; + $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); diff --git a/lib/Doctrine/ORM/Mapping/Builder/OneToManyAssociationBuilder.php b/lib/Doctrine/ORM/Mapping/Builder/OneToManyAssociationBuilder.php index a81f65291c9..8c205fe0d03 100644 --- a/lib/Doctrine/ORM/Mapping/Builder/OneToManyAssociationBuilder.php +++ b/lib/Doctrine/ORM/Mapping/Builder/OneToManyAssociationBuilder.php @@ -1,4 +1,5 @@ */ class OneToManyAssociationBuilder extends AssociationBuilder { @@ -62,6 +60,7 @@ public function build() if ($this->joinColumns) { $mapping['joinColumns'] = $this->joinColumns; } + $cm = $this->builder->getClassMetadata(); $cm->mapOneToMany($mapping); diff --git a/lib/Doctrine/ORM/Mapping/Cache.php b/lib/Doctrine/ORM/Mapping/Cache.php index 3226b603160..b4bf98d77f5 100644 --- a/lib/Doctrine/ORM/Mapping/Cache.php +++ b/lib/Doctrine/ORM/Mapping/Cache.php @@ -1,4 +1,5 @@ - * @since 2.5 - * * @Annotation * @Target({"CLASS","PROPERTY"}) */ @@ -32,13 +30,10 @@ 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. - */ + /** @var string Cache region name. */ public $region; } diff --git a/lib/Doctrine/ORM/Mapping/ChangeTrackingPolicy.php b/lib/Doctrine/ORM/Mapping/ChangeTrackingPolicy.php index 3657b764f1e..b37b335a3ce 100644 --- a/lib/Doctrine/ORM/Mapping/ChangeTrackingPolicy.php +++ b/lib/Doctrine/ORM/Mapping/ChangeTrackingPolicy.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class ClassMetadataFactory extends AbstractClassMetadataFactory { - /** - * @var EntityManagerInterface|null - */ + /** @var EntityManagerInterface|null */ private $em; - /** - * @var \Doctrine\DBAL\Platforms\AbstractPlatform - */ + /** @var AbstractPlatform */ private $targetPlatform; - /** - * @var MappingDriver - */ + /** @var MappingDriver */ private $driver; - /** - * @var \Doctrine\Common\EventManager - */ + /** @var EventManager */ private $evm; - /** - * @var array - */ + /** @var array */ private $embeddablesActiveNesting = []; /** @@ -85,9 +83,6 @@ protected function loadMetadata($name) return $loaded; } - /** - * @param EntityManagerInterface $em - */ public function setEntityManager(EntityManagerInterface $em) { $this->em = $em; @@ -98,8 +93,8 @@ public function setEntityManager(EntityManagerInterface $em) */ protected function initialize() { - $this->driver = $this->em->getConfiguration()->getMetadataDriverImpl(); - $this->evm = $this->em->getEventManager(); + $this->driver = $this->em->getConfiguration()->getMetadataDriverImpl(); + $this->evm = $this->em->getEventManager(); $this->initialized = true; } @@ -124,8 +119,8 @@ protected function onNotFoundMetadata($className) */ protected function doLoadMetadata($class, $parent, $rootEntityFound, array $nonSuperclassParents) { - /* @var $class ClassMetadata */ - /* @var $parent ClassMetadata */ + /** @var ClassMetadata $class */ + /** @var ClassMetadata $parent */ if ($parent) { $class->setInheritanceType($parent->inheritanceType); $class->setDiscriminatorColumn($parent->discriminatorColumn); @@ -140,7 +135,7 @@ protected function doLoadMetadata($class, $parent, $rootEntityFound, array $nonS $class->setLifecycleCallbacks($parent->lifecycleCallbacks); $class->setChangeTrackingPolicy($parent->changeTrackingPolicy); - if ( ! empty($parent->customGeneratorDefinition)) { + if (! empty($parent->customGeneratorDefinition)) { $class->setCustomGeneratorDefinition($parent->customGeneratorDefinition); } @@ -165,14 +160,13 @@ protected function doLoadMetadata($class, $parent, $rootEntityFound, array $nonS $this->completeIdGeneratorMapping($class); } - if (!$class->isMappedSuperclass) { + if (! $class->isMappedSuperclass) { foreach ($class->embeddedClasses as $property => $embeddableClass) { - if (isset($embeddableClass['inherited'])) { continue; } - if ( ! (isset($embeddableClass['class']) && $embeddableClass['class'])) { + if (! (isset($embeddableClass['class']) && $embeddableClass['class'])) { throw MappingException::missingEmbeddedClass($property); } @@ -217,19 +211,19 @@ protected function doLoadMetadata($class, $parent, $rootEntityFound, array $nonS $class->containsForeignIdentifier = true; } - if ( ! empty($parent->namedQueries)) { + if (! empty($parent->namedQueries)) { $this->addInheritedNamedQueries($class, $parent); } - if ( ! empty($parent->namedNativeQueries)) { + if (! empty($parent->namedNativeQueries)) { $this->addInheritedNamedNativeQueries($class, $parent); } - if ( ! empty($parent->sqlResultSetMappings)) { + if (! empty($parent->sqlResultSetMappings)) { $this->addInheritedSqlResultSetMappings($class, $parent); } - if ( ! empty($parent->entityListeners) && empty($class->entityListeners)) { + if (! empty($parent->entityListeners) && empty($class->entityListeners)) { $class->entityListeners = $parent->entityListeners; } } @@ -260,7 +254,7 @@ protected function doLoadMetadata($class, $parent, $rootEntityFound, array $nonS */ protected function validateRuntimeMetadata($class, $parent) { - if ( ! $class->reflClass ) { + if (! $class->reflClass) { // only validate if there is a reflection class instance return; } @@ -270,21 +264,23 @@ protected function validateRuntimeMetadata($class, $parent) $class->validateLifecycleCallbacks($this->getReflectionService()); // verify inheritance - if ( ! $class->isMappedSuperclass && !$class->isInheritanceTypeNone()) { - if ( ! $parent) { - if (count($class->discriminatorMap) == 0) { + if (! $class->isMappedSuperclass && ! $class->isInheritanceTypeNone()) { + if (! $parent) { + if (count($class->discriminatorMap) === 0) { throw MappingException::missingDiscriminatorMap($class->name); } - if ( ! $class->discriminatorColumn) { + + if (! $class->discriminatorColumn) { throw MappingException::missingDiscriminatorColumn($class->name); } + foreach ($class->subClasses as $subClass) { if ((new ReflectionClass($subClass))->name !== $subClass) { throw MappingException::invalidClassInDiscriminatorMap($subClass, $class->name); } } } - } else if ($class->isMappedSuperclass && $class->name == $class->rootEntityName && (count($class->discriminatorMap) || $class->discriminatorColumn)) { + } elseif ($class->isMappedSuperclass && $class->name === $class->rootEntityName && (count($class->discriminatorMap) || $class->discriminatorColumn)) { // second condition is necessary for mapped superclasses in the middle of an inheritance hierarchy throw MappingException::noInheritanceOnMappedSuperClass($class->name); } @@ -302,15 +298,14 @@ protected function newClassMetadataInstance($className) * Populates the discriminator value of the given metadata (if not set) by iterating over discriminator * map classes and looking for a fitting one. * - * @param ClassMetadata $metadata - * * @return void * * @throws MappingException */ private function resolveDiscriminatorValue(ClassMetadata $metadata) { - if ($metadata->discriminatorValue + if ( + $metadata->discriminatorValue || ! $metadata->discriminatorMap || $metadata->isMappedSuperclass || ! $metadata->reflClass @@ -350,15 +345,13 @@ private function resolveDiscriminatorValue(ClassMetadata $metadata) * The automatically generated discriminator map contains the lowercase short name of * each class as key. * - * @param \Doctrine\ORM\Mapping\ClassMetadata $class - * * @throws MappingException */ private function addDefaultDiscriminatorMap(ClassMetadata $class) { $allClasses = $this->driver->getAllClassNames(); - $fqcn = $class->getName(); - $map = [$this->getShortName($class->name) => $fqcn]; + $fqcn = $class->getName(); + $map = [$this->getShortName($class->name) => $fqcn]; $duplicates = []; foreach ($allClasses as $subClassCandidate) { @@ -389,11 +382,11 @@ private function addDefaultDiscriminatorMap(ClassMetadata $class) */ private function getShortName($className) { - if (strpos($className, "\\") === false) { + if (strpos($className, '\\') === false) { return strtolower($className); } - $parts = explode("\\", $className); + $parts = explode('\\', $className); return strtolower(end($parts)); } @@ -401,9 +394,6 @@ 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) @@ -412,11 +402,14 @@ private function addInheritedFields(ClassMetadata $subClass, ClassMetadata $pare 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; } @@ -425,9 +418,6 @@ private function addInheritedFields(ClassMetadata $subClass, ClassMetadata $pare /** * Adds inherited association mappings to the subclass mapping. * - * @param \Doctrine\ORM\Mapping\ClassMetadata $subClass - * @param \Doctrine\ORM\Mapping\ClassMetadata $parentClass - * * @return void * * @throws MappingException @@ -436,19 +426,22 @@ private function addInheritedRelations(ClassMetadata $subClass, ClassMetadata $p { foreach ($parentClass->associationMappings as $field => $mapping) { if ($parentClass->isMappedSuperclass) { - if ($mapping['type'] & ClassMetadata::TO_MANY && !$mapping['isOwningSide']) { + if ($mapping['type'] & ClassMetadata::TO_MANY && ! $mapping['isOwningSide']) { throw MappingException::illegalToManyAssociationOnMappedSuperclass($parentClass->name, $field); } + $mapping['sourceEntity'] = $subClass->name; } //$subclassMapping = $mapping; - if ( ! isset($mapping['inherited']) && ! $parentClass->isMappedSuperclass) { + if (! isset($mapping['inherited']) && ! $parentClass->isMappedSuperclass) { $mapping['inherited'] = $parentClass->name; } - if ( ! isset($mapping['declared'])) { + + if (! isset($mapping['declared'])) { $mapping['declared'] = $parentClass->name; } + $subClass->addInheritedAssociationMapping($mapping); } } @@ -456,10 +449,11 @@ private function addInheritedRelations(ClassMetadata $subClass, ClassMetadata $p private function addInheritedEmbeddedClasses(ClassMetadata $subClass, ClassMetadata $parentClass) { foreach ($parentClass->embeddedClasses as $field => $embeddedClass) { - if ( ! isset($embeddedClass['inherited']) && ! $parentClass->isMappedSuperclass) { + if (! isset($embeddedClass['inherited']) && ! $parentClass->isMappedSuperclass) { $embeddedClass['inherited'] = $parentClass->name; } - if ( ! isset($embeddedClass['declared'])) { + + if (! isset($embeddedClass['declared'])) { $embeddedClass['declared'] = $parentClass->name; } @@ -500,9 +494,6 @@ private function addNestedEmbeddedClasses(ClassMetadata $subClass, ClassMetadata /** * Copy the table indices from the parent class superclass to the child class * - * @param ClassMetadata $subClass - * @param ClassMetadata $parentClass - * * @return void */ private function addInheritedIndexes(ClassMetadata $subClass, ClassMetadata $parentClass) @@ -527,21 +518,16 @@ private function addInheritedIndexes(ClassMetadata $subClass, ClassMetadata $par /** * 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 */ private function addInheritedNamedQueries(ClassMetadata $subClass, ClassMetadata $parentClass) { foreach ($parentClass->namedQueries as $name => $query) { - if ( ! isset ($subClass->namedQueries[$name])) { + if (! isset($subClass->namedQueries[$name])) { $subClass->addNamedQuery( [ 'name' => $query['name'], - 'query' => $query['query'] + 'query' => $query['query'], ] ); } @@ -551,17 +537,12 @@ private function addInheritedNamedQueries(ClassMetadata $subClass, ClassMetadata /** * Adds inherited named native queries to the subclass mapping. * - * @since 2.3 - * - * @param \Doctrine\ORM\Mapping\ClassMetadata $subClass - * @param \Doctrine\ORM\Mapping\ClassMetadata $parentClass - * * @return void */ private function addInheritedNamedNativeQueries(ClassMetadata $subClass, ClassMetadata $parentClass) { foreach ($parentClass->namedNativeQueries as $name => $query) { - if ( ! isset ($subClass->namedNativeQueries[$name])) { + if (! isset($subClass->namedNativeQueries[$name])) { $subClass->addNamedNativeQuery( [ 'name' => $query['name'], @@ -578,17 +559,12 @@ private function addInheritedNamedNativeQueries(ClassMetadata $subClass, ClassMe /** * Adds inherited sql result set mappings to the subclass mapping. * - * @since 2.3 - * - * @param \Doctrine\ORM\Mapping\ClassMetadata $subClass - * @param \Doctrine\ORM\Mapping\ClassMetadata $parentClass - * * @return void */ private function addInheritedSqlResultSetMappings(ClassMetadata $subClass, ClassMetadata $parentClass) { foreach ($parentClass->sqlResultSetMappings as $name => $mapping) { - if ( ! isset ($subClass->sqlResultSetMappings[$name])) { + if (! isset($subClass->sqlResultSetMappings[$name])) { $entities = []; foreach ($mapping['entities'] as $entity) { $entities[] = [ @@ -614,8 +590,6 @@ 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 - * * @return void * * @throws ORMException @@ -623,10 +597,10 @@ private function addInheritedSqlResultSetMappings(ClassMetadata $subClass, Class private function completeIdGeneratorMapping(ClassMetadataInfo $class) { $idGenType = $class->generatorType; - if ($idGenType == ClassMetadata::GENERATOR_TYPE_AUTO) { + if ($idGenType === ClassMetadata::GENERATOR_TYPE_AUTO) { if ($this->getTargetPlatform()->prefersSequences()) { $class->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_SEQUENCE); - } else if ($this->getTargetPlatform()->prefersIdentityColumns()) { + } elseif ($this->getTargetPlatform()->prefersIdentityColumns()) { $class->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY); } else { $class->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_TABLE); @@ -646,7 +620,7 @@ private function completeIdGeneratorMapping(ClassMetadataInfo $class) $sequencePrefix = $class->getSequencePrefix($this->getTargetPlatform()); $sequenceName = $this->getTargetPlatform()->getIdentitySequenceName($sequencePrefix, $columnName); $definition = [ - 'sequenceName' => $this->getTargetPlatform()->fixSchemaElementName($sequenceName) + 'sequenceName' => $this->getTargetPlatform()->fixSchemaElementName($sequenceName), ]; if ($quoted) { @@ -660,7 +634,7 @@ private function completeIdGeneratorMapping(ClassMetadataInfo $class) ->getSequenceName($definition, $class, $this->getTargetPlatform()); } - $generator = ($fieldName && $class->fieldMappings[$fieldName]['type'] === 'bigint') + $generator = $fieldName && $class->fieldMappings[$fieldName]['type'] === 'bigint' ? new BigIntegerIdentityGenerator($sequenceName) : new IdentityGenerator($sequenceName); @@ -672,10 +646,10 @@ private function completeIdGeneratorMapping(ClassMetadataInfo $class) // 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']); + 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), @@ -690,7 +664,7 @@ private function completeIdGeneratorMapping(ClassMetadataInfo $class) $class->setSequenceGeneratorDefinition($definition); } - $sequenceGenerator = new \Doctrine\ORM\Id\SequenceGenerator( + $sequenceGenerator = new SequenceGenerator( $this->em->getConfiguration()->getQuoteStrategy()->getSequenceName($definition, $class, $this->getTargetPlatform()), $definition['allocationSize'] ); @@ -698,15 +672,16 @@ private function completeIdGeneratorMapping(ClassMetadataInfo $class) break; case ClassMetadata::GENERATOR_TYPE_NONE: - $class->setIdGenerator(new \Doctrine\ORM\Id\AssignedGenerator()); + $class->setIdGenerator(new AssignedGenerator()); break; case ClassMetadata::GENERATOR_TYPE_UUID: - $class->setIdGenerator(new \Doctrine\ORM\Id\UuidGenerator()); + $class->setIdGenerator(new UuidGenerator()); break; case ClassMetadata::GENERATOR_TYPE_TABLE: - throw new ORMException("TableGenerator not yet implemented."); + throw new ORMException('TableGenerator not yet implemented.'); + break; case ClassMetadata::GENERATOR_TYPE_CUSTOM: @@ -714,23 +689,22 @@ private function completeIdGeneratorMapping(ClassMetadataInfo $class) if ($definition === null) { throw new ORMException("Can't instantiate custom generator : no custom generator definition"); } - if ( ! class_exists($definition['class'])) { + + if (! class_exists($definition['class'])) { throw new ORMException("Can't instantiate custom generator : " . $definition['class']); } - $class->setIdGenerator(new $definition['class']); + + $class->setIdGenerator(new $definition['class']()); break; default: - throw new ORMException("Unknown generator type: " . $class->generatorType); + 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) { @@ -754,7 +728,7 @@ private function inheritIdGeneratorMapping(ClassMetadataInfo $class, ClassMetada */ protected function wakeupReflection(ClassMetadataInterface $class, ReflectionService $reflService) { - /* @var $class ClassMetadata */ + /** @var ClassMetadata $class */ $class->wakeupReflection($reflService); } @@ -763,7 +737,7 @@ protected function wakeupReflection(ClassMetadataInterface $class, ReflectionSer */ protected function initializeReflection(ClassMetadataInterface $class, ReflectionService $reflService) { - /* @var $class ClassMetadata */ + /** @var ClassMetadata $class */ $class->initializeReflection($reflService); } @@ -796,7 +770,7 @@ protected function isEntity(ClassMetadataInterface $class) */ private function getTargetPlatform() { - if (!$this->targetPlatform) { + if (! $this->targetPlatform) { $this->targetPlatform = $this->em->getConnection()->getDatabasePlatform(); } diff --git a/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php b/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php index 9890c5956ee..e78b029f95e 100644 --- a/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php +++ b/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php @@ -1,4 +1,5 @@ ClassMetadata instance holds all the object-relational mapping metadata @@ -46,10 +72,6 @@ * 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 { @@ -58,45 +80,45 @@ class ClassMetadataInfo implements ClassMetadata * 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; + public 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; + public 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; + public 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; + public 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; + public 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; + public const GENERATOR_TYPE_SEQUENCE = 2; /** * TABLE means a separate table is used for id generation. * Offers full portability. */ - const GENERATOR_TYPE_TABLE = 3; + public const GENERATOR_TYPE_TABLE = 3; /** * IDENTITY means an identity column is used for id generation. The database @@ -104,24 +126,24 @@ class ClassMetadataInfo implements ClassMetadata * native identity columns may emulate them. Full portability is currently * not guaranteed. */ - const GENERATOR_TYPE_IDENTITY = 4; + public 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; + public 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; + public const GENERATOR_TYPE_UUID = 6; /** * CUSTOM means that customer will use own ID generator that supposedly work */ - const GENERATOR_TYPE_CUSTOM = 7; + public const GENERATOR_TYPE_CUSTOM = 7; /** * DEFERRED_IMPLICIT means that changes of entities are calculated at commit-time @@ -130,84 +152,84 @@ class ClassMetadataInfo implements ClassMetadata * * This is the default change tracking policy. */ - const CHANGETRACKING_DEFERRED_IMPLICIT = 1; + public 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; + public 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; + public const CHANGETRACKING_NOTIFY = 3; /** * Specifies that an association is to be fetched when it is first accessed. */ - const FETCH_LAZY = 2; + public const FETCH_LAZY = 2; /** * Specifies that an association is to be fetched when the owner of the * association is fetched. */ - const FETCH_EAGER = 3; + public 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; + public const FETCH_EXTRA_LAZY = 4; /** * Identifies a one-to-one association. */ - const ONE_TO_ONE = 1; + public const ONE_TO_ONE = 1; /** * Identifies a many-to-one association. */ - const MANY_TO_ONE = 2; + public const MANY_TO_ONE = 2; /** * Identifies a one-to-many association. */ - const ONE_TO_MANY = 4; + public const ONE_TO_MANY = 4; /** * Identifies a many-to-many association. */ - const MANY_TO_MANY = 8; + public const MANY_TO_MANY = 8; /** * Combined bitmask for to-one (single-valued) associations. */ - const TO_ONE = 3; + public const TO_ONE = 3; /** * Combined bitmask for to-many (collection-valued) associations. */ - const TO_MANY = 12; + public 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; + public 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; + public const CACHE_USAGE_NONSTRICT_READ_WRITE = 2; /** * Read Write Attempts to lock the entity before update/delete. */ - const CACHE_USAGE_READ_WRITE = 3; + public const CACHE_USAGE_READ_WRITE = 3; /** * READ-ONLY: The name of the entity class. @@ -220,7 +242,6 @@ class ClassMetadataInfo implements ClassMetadata * READ-ONLY: The namespace the entity class is contained in. * * @var string - * * @todo Not really needed. Usage could be localized. */ public $namespace; @@ -246,7 +267,6 @@ class ClassMetadataInfo implements ClassMetadata * * * @todo Merge with tableGeneratorDefinition into generic generatorDefinition - * * @var array|null */ public $customGeneratorDefinition; @@ -263,14 +283,14 @@ class ClassMetadataInfo implements ClassMetadata /** * READ-ONLY: Whether this class describes the mapping of a mapped superclass. * - * @var boolean + * @var bool */ public $isMappedSuperclass = false; /** * READ-ONLY: Whether this class describes the mapping of an embeddable class. * - * @var boolean + * @var bool */ public $isEmbeddedClass = false; @@ -346,7 +366,7 @@ class ClassMetadataInfo implements ClassMetadata /** * READ-ONLY: The inheritance mapping type used by the class. * - * @var integer + * @var int */ public $inheritanceType = self::INHERITANCE_TYPE_NONE; @@ -397,7 +417,6 @@ class ClassMetadataInfo implements ClassMetadata * Whether a unique constraint should be generated for the column. * * @var array - * * @psalm-var array */ public $fieldMappings = []; @@ -415,9 +434,9 @@ class ClassMetadataInfo implements ClassMetadata * Used to look up column names from field names. * This is the reverse lookup map of $_fieldNames. * - * @var array - * * @deprecated 3.0 Remove this. + * + * @var array */ public $columnNames = []; @@ -427,9 +446,9 @@ class ClassMetadataInfo implements ClassMetadata * This does only apply to the JOINED and SINGLE_TABLE inheritance mapping strategies * where a discriminator column is used. * - * @var mixed - * * @see discriminatorColumn + * + * @var mixed */ public $discriminatorValue; @@ -439,9 +458,9 @@ class ClassMetadataInfo implements ClassMetadata * This does only apply to the JOINED and SINGLE_TABLE inheritance mapping strategies * where a discriminator column is used. * - * @var mixed - * * @see discriminatorColumn + * + * @var mixed */ public $discriminatorMap = []; @@ -540,7 +559,7 @@ class ClassMetadataInfo implements ClassMetadata /** * READ-ONLY: Flag indicating whether the identifier/primary key of the class is composite. * - * @var boolean + * @var bool */ public $isIdentifierComposite = false; @@ -549,15 +568,14 @@ class ClassMetadataInfo implements ClassMetadata * * This flag is necessary because some code blocks require special treatment of this cases. * - * @var boolean + * @var bool */ public $containsForeignIdentifier = false; /** * READ-ONLY: The ID generator used for generating IDs for this class. * - * @var \Doctrine\ORM\Id\AbstractIdGenerator - * + * @var AbstractIdGenerator * @todo Remove! */ public $idGenerator; @@ -576,7 +594,6 @@ class ClassMetadataInfo implements ClassMetadata * * * @var array - * * @todo Merge with tableGeneratorDefinition into generic generatorDefinition */ public $sequenceGeneratorDefinition; @@ -586,7 +603,6 @@ class ClassMetadataInfo implements ClassMetadata * TABLE generation strategy. * * @var array - * * @todo Merge with tableGeneratorDefinition into generic generatorDefinition */ public $tableGeneratorDefinition; @@ -594,7 +610,7 @@ class ClassMetadataInfo implements ClassMetadata /** * READ-ONLY: The policy used for change-tracking on entities of this class. * - * @var integer + * @var int */ public $changeTrackingPolicy = self::CHANGETRACKING_DEFERRED_IMPLICIT; @@ -602,7 +618,7 @@ class ClassMetadataInfo implements ClassMetadata * READ-ONLY: A flag for whether or not instances of this class are to be versioned * with optimistic locking. * - * @var boolean + * @var bool */ public $isVersioned; @@ -613,9 +629,7 @@ class ClassMetadataInfo implements ClassMetadata */ public $versionField; - /** - * @var array - */ + /** @var array */ public $cache = null; /** @@ -639,7 +653,7 @@ class ClassMetadataInfo implements ClassMetadata /** * NamingStrategy determining the default column and table names. * - * @var \Doctrine\ORM\Mapping\NamingStrategy + * @var NamingStrategy */ protected $namingStrategy; @@ -650,21 +664,18 @@ class ClassMetadataInfo implements ClassMetadata */ public $reflFields = []; - /** - * @var \Doctrine\Instantiator\InstantiatorInterface|null - */ + /** @var 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 + * @param string $entityName The name of the entity class the new instance is used for. */ - public function __construct($entityName, NamingStrategy $namingStrategy = null) + public function __construct($entityName, ?NamingStrategy $namingStrategy = null) { - $this->name = $entityName; + $this->name = $entityName; $this->rootEntityName = $entityName; $this->namingStrategy = $namingStrategy ?: new DefaultNamingStrategy(); $this->instantiator = new Instantiator(); @@ -704,7 +715,7 @@ public function getReflectionProperty($name) public function getSingleIdReflectionProperty() { if ($this->isIdentifierComposite) { - throw new BadMethodCallException("Class " . $this->name . " has a composite identifier."); + throw new BadMethodCallException('Class ' . $this->name . ' has a composite identifier.'); } return $this->reflFields[$this->identifier[0]]; @@ -728,7 +739,7 @@ public function getIdentifierValues($entity) foreach ($this->identifier as $idField) { $value = $this->reflFields[$idField]->getValue($entity); - if (null !== $value) { + if ($value !== null) { $id[$idField] = $value; } } @@ -736,10 +747,10 @@ public function getIdentifierValues($entity) return $id; } - $id = $this->identifier[0]; + $id = $this->identifier[0]; $value = $this->reflFields[$id]->getValue($entity); - if (null === $value) { + if ($value === null) { return []; } @@ -799,7 +810,7 @@ public function getFieldValue($entity, $field) */ public function __toString() { - return __CLASS__ . '@' . spl_object_hash($this); + return self::class . '@' . spl_object_hash($this); } /** @@ -834,7 +845,7 @@ public function __sleep() ]; // The rest of the metadata is only serialized if necessary. - if ($this->changeTrackingPolicy != self::CHANGETRACKING_DEFERRED_IMPLICIT) { + if ($this->changeTrackingPolicy !== self::CHANGETRACKING_DEFERRED_IMPLICIT) { $serialized[] = 'changeTrackingPolicy'; } @@ -842,7 +853,7 @@ public function __sleep() $serialized[] = 'customRepositoryClassName'; } - if ($this->inheritanceType != self::INHERITANCE_TYPE_NONE) { + if ($this->inheritanceType !== self::INHERITANCE_TYPE_NONE) { $serialized[] = 'inheritanceType'; $serialized[] = 'discriminatorColumn'; $serialized[] = 'discriminatorValue'; @@ -851,9 +862,9 @@ public function __sleep() $serialized[] = 'subClasses'; } - if ($this->generatorType != self::GENERATOR_TYPE_NONE) { + if ($this->generatorType !== self::GENERATOR_TYPE_NONE) { $serialized[] = 'generatorType'; - if ($this->generatorType == self::GENERATOR_TYPE_SEQUENCE) { + if ($this->generatorType === self::GENERATOR_TYPE_SEQUENCE) { $serialized[] = 'sequenceGeneratorDefinition'; } } @@ -900,7 +911,7 @@ public function __sleep() } if ($this->customGeneratorDefinition) { - $serialized[] = "customGeneratorDefinition"; + $serialized[] = 'customGeneratorDefinition'; } if ($this->cache) { @@ -1014,7 +1025,7 @@ public function validateIdentifier() } // Verify & complete identifier mapping - if ( ! $this->identifier) { + if (! $this->identifier) { throw MappingException::identifierRequired($this->name); } @@ -1056,7 +1067,7 @@ public function validateLifecycleCallbacks($reflService) { foreach ($this->lifecycleCallbacks as $callbacks) { foreach ($callbacks as $callbackFuncName) { - if ( ! $reflService->hasPublicMethod($this->name, $callbackFuncName)) { + if (! $reflService->hasPublicMethod($this->name, $callbackFuncName)) { throw MappingException::lifecycleCallbackMethodNotFound($this->name, $callbackFuncName); } } @@ -1078,11 +1089,11 @@ public function getReflectionClass() */ public function enableCache(array $cache) { - if ( ! isset($cache['usage'])) { + if (! isset($cache['usage'])) { $cache['usage'] = self::CACHE_USAGE_READ_ONLY; } - if ( ! isset($cache['region'])) { + if (! isset($cache['region'])) { $cache['region'] = strtolower(str_replace('\\', '_', $this->rootEntityName)); } @@ -1111,13 +1122,11 @@ public function enableAssociationCache($fieldName, array $cache) */ 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['usage'])) { + $cache['usage'] = $this->cache['usage'] ?? self::CACHE_USAGE_READ_ONLY; } - if ( ! isset($cache['region'])) { + if (! isset($cache['region'])) { $cache['region'] = strtolower(str_replace('\\', '_', $this->rootEntityName)) . '__' . $fieldName; } @@ -1127,7 +1136,7 @@ public function getAssociationCacheDefaults($fieldName, array $cache) /** * Sets the change tracking policy used by this class. * - * @param integer $policy + * @param int $policy * * @return void */ @@ -1139,31 +1148,31 @@ public function setChangeTrackingPolicy($policy) /** * Whether the change tracking policy of this class is "deferred explicit". * - * @return boolean + * @return bool */ public function isChangeTrackingDeferredExplicit() { - return self::CHANGETRACKING_DEFERRED_EXPLICIT === $this->changeTrackingPolicy; + return $this->changeTrackingPolicy === self::CHANGETRACKING_DEFERRED_EXPLICIT; } /** * Whether the change tracking policy of this class is "deferred implicit". * - * @return boolean + * @return bool */ public function isChangeTrackingDeferredImplicit() { - return self::CHANGETRACKING_DEFERRED_IMPLICIT === $this->changeTrackingPolicy; + return $this->changeTrackingPolicy === self::CHANGETRACKING_DEFERRED_IMPLICIT; } /** * Whether the change tracking policy of this class is "notify". * - * @return boolean + * @return bool */ public function isChangeTrackingNotify() { - return self::CHANGETRACKING_NOTIFY === $this->changeTrackingPolicy; + return $this->changeTrackingPolicy === self::CHANGETRACKING_NOTIFY; } /** @@ -1171,16 +1180,16 @@ public function isChangeTrackingNotify() * * @param string $fieldName The field name. * - * @return boolean TRUE if the field is part of the table identifier/primary key field(s), - * FALSE otherwise. + * @return bool TRUE if the field is part of the table identifier/primary key field(s), + * FALSE otherwise. */ public function isIdentifier($fieldName) { - if ( ! $this->identifier) { + if (! $this->identifier) { return false; } - if ( ! $this->isIdentifierComposite) { + if (! $this->isIdentifierComposite) { return $fieldName === $this->identifier[0]; } @@ -1192,13 +1201,13 @@ public function isIdentifier($fieldName) * * @param string $fieldName The field name. * - * @return boolean TRUE if the field is unique, FALSE otherwise. + * @return bool TRUE if the field is unique, FALSE otherwise. */ public function isUniqueField($fieldName) { $mapping = $this->getFieldMapping($fieldName); - return false !== $mapping && isset($mapping['unique']) && $mapping['unique']; + return $mapping !== false && isset($mapping['unique']) && $mapping['unique']; } /** @@ -1206,13 +1215,13 @@ public function isUniqueField($fieldName) * * @param string $fieldName The field name. * - * @return boolean TRUE if the field is not null, FALSE otherwise. + * @return bool 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']; + return $mapping !== false && isset($mapping['nullable']) && $mapping['nullable']; } /** @@ -1226,9 +1235,7 @@ public function isNullable($fieldName) */ public function getColumnName($fieldName) { - return isset($this->columnNames[$fieldName]) - ? $this->columnNames[$fieldName] - : $fieldName; + return $this->columnNames[$fieldName] ?? $fieldName; } /** @@ -1243,7 +1250,7 @@ public function getColumnName($fieldName) */ public function getFieldMapping($fieldName) { - if ( ! isset($this->fieldMappings[$fieldName])) { + if (! isset($this->fieldMappings[$fieldName])) { throw MappingException::mappingNotFound($this->name, $fieldName); } @@ -1264,7 +1271,7 @@ public function getFieldMapping($fieldName) */ public function getAssociationMapping($fieldName) { - if ( ! isset($this->associationMappings[$fieldName])) { + if (! isset($this->associationMappings[$fieldName])) { throw MappingException::mappingNotFound($this->name, $fieldName); } @@ -1291,9 +1298,7 @@ public function getAssociationMappings() */ public function getFieldName($columnName) { - return isset($this->fieldNames[$columnName]) - ? $this->fieldNames[$columnName] - : $columnName; + return $this->fieldNames[$columnName] ?? $columnName; } /** @@ -1309,7 +1314,7 @@ public function getFieldName($columnName) */ public function getNamedQuery($queryName) { - if ( ! isset($this->namedQueries[$queryName])) { + if (! isset($this->namedQueries[$queryName])) { throw MappingException::queryNotFound($this->name, $queryName); } @@ -1339,7 +1344,7 @@ public function getNamedQueries() */ public function getNamedNativeQuery($queryName) { - if ( ! isset($this->namedNativeQueries[$queryName])) { + if (! isset($this->namedNativeQueries[$queryName])) { throw MappingException::queryNotFound($this->name, $queryName); } @@ -1369,7 +1374,7 @@ public function getNamedNativeQueries() */ public function getSqlResultSetMapping($name) { - if ( ! isset($this->sqlResultSetMappings[$name])) { + if (! isset($this->sqlResultSetMappings[$name])) { throw MappingException::resultMappingNotFound($this->name, $name); } @@ -1398,23 +1403,23 @@ public function getSqlResultSetMappings() protected function _validateAndCompleteFieldMapping(array &$mapping) { // Check mandatory fields - if ( ! isset($mapping['fieldName']) || !$mapping['fieldName']) { + if (! isset($mapping['fieldName']) || ! $mapping['fieldName']) { throw MappingException::missingFieldName($this->name); } - if ( ! isset($mapping['type'])) { + if (! isset($mapping['type'])) { // Default to string $mapping['type'] = 'string'; } // Complete fieldName and columnName mapping - if ( ! isset($mapping['columnName'])) { + 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; + if ($mapping['columnName'][0] === '`') { + $mapping['columnName'] = trim($mapping['columnName'], '`'); + $mapping['quoted'] = true; } $this->columnNames[$mapping['fieldName']] = $mapping['columnName']; @@ -1426,23 +1431,23 @@ protected function _validateAndCompleteFieldMapping(array &$mapping) $this->fieldNames[$mapping['columnName']] = $mapping['fieldName']; // Complete id mapping - if (isset($mapping['id']) && true === $mapping['id']) { - if ($this->versionField == $mapping['fieldName']) { + if (isset($mapping['id']) && $mapping['id'] === true) { + if ($this->versionField === $mapping['fieldName']) { throw MappingException::cannotVersionIdField($this->name, $mapping['fieldName']); } - if ( ! in_array($mapping['fieldName'], $this->identifier)) { + if (! in_array($mapping['fieldName'], $this->identifier)) { $this->identifier[] = $mapping['fieldName']; } // Check for composite key - if ( ! $this->isIdentifierComposite && count($this->identifier) > 1) { + 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']) { + if (isset($mapping['id']) && $mapping['id'] === true) { throw MappingException::sqlConversionNotAllowedForIdentifiers($this->name, $mapping['fieldName'], $mapping['type']); } @@ -1478,11 +1483,11 @@ protected function _validateAndCompleteFieldMapping(array &$mapping) */ protected function _validateAndCompleteAssociationMapping(array $mapping) { - if ( ! isset($mapping['mappedBy'])) { + if (! isset($mapping['mappedBy'])) { $mapping['mappedBy'] = null; } - if ( ! isset($mapping['inversedBy'])) { + if (! isset($mapping['inversedBy'])) { $mapping['inversedBy'] = null; } @@ -1506,44 +1511,46 @@ protected function _validateAndCompleteAssociationMapping(array $mapping) } // Complete id mapping - if (isset($mapping['id']) && true === $mapping['id']) { + if (isset($mapping['id']) && $mapping['id'] === true) { if (isset($mapping['orphanRemoval']) && $mapping['orphanRemoval']) { throw MappingException::illegalOrphanRemovalOnIdentifierAssociation($this->name, $mapping['fieldName']); } - if ( ! in_array($mapping['fieldName'], $this->identifier)) { + if (! in_array($mapping['fieldName'], $this->identifier)) { if (isset($mapping['joinColumns']) && count($mapping['joinColumns']) >= 2) { throw MappingException::cannotMapCompositePrimaryKeyEntitiesAsForeignId( - $mapping['targetEntity'], $this->name, $mapping['fieldName'] + $mapping['targetEntity'], + $this->name, + $mapping['fieldName'] ); } - $this->identifier[] = $mapping['fieldName']; + $this->identifier[] = $mapping['fieldName']; $this->containsForeignIdentifier = true; } // Check for composite key - if ( ! $this->isIdentifierComposite && count($this->identifier) > 1) { + if (! $this->isIdentifierComposite && count($this->identifier) > 1) { $this->isIdentifierComposite = true; } - if ($this->cache && !isset($mapping['cache'])) { + 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']) { + if (! isset($mapping['fieldName']) || ! $mapping['fieldName']) { throw MappingException::missingFieldName($this->name); } - if ( ! isset($mapping['targetEntity'])) { + if (! isset($mapping['targetEntity'])) { throw MappingException::missingTargetEntity($mapping['fieldName']); } // Mandatory and optional attributes for either side - if ( ! $mapping['mappedBy']) { + 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'], '`'); @@ -1554,12 +1561,12 @@ protected function _validateAndCompleteAssociationMapping(array $mapping) $mapping['isOwningSide'] = false; } - if (isset($mapping['id']) && true === $mapping['id'] && $mapping['type'] & self::TO_MANY) { + if (isset($mapping['id']) && $mapping['id'] === true && $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'])) { + if (! isset($mapping['fetch'])) { $mapping['fetch'] = self::FETCH_LAZY; } @@ -1577,7 +1584,7 @@ protected function _validateAndCompleteAssociationMapping(array $mapping) ); } - $mapping['cascade'] = $cascades; + $mapping['cascade'] = $cascades; $mapping['isCascadeRemove'] = in_array('remove', $cascades); $mapping['isCascadePersist'] = in_array('persist', $cascades); $mapping['isCascadeRefresh'] = in_array('refresh', $cascades); @@ -1613,8 +1620,8 @@ protected function _validateAndCompleteOneToOneMapping(array $mapping) $mapping['joinColumns'] = [ [ 'name' => $this->namingStrategy->joinColumnName($mapping['fieldName'], $this->name), - 'referencedColumnName' => $this->namingStrategy->referenceColumnName() - ] + 'referencedColumnName' => $this->namingStrategy->referenceColumnName(), + ], ]; } @@ -1650,17 +1657,15 @@ protected function _validateAndCompleteOneToOneMapping(array $mapping) } $mapping['sourceToTargetKeyColumns'][$joinColumn['name']] = $joinColumn['referencedColumnName']; - $mapping['joinColumnFieldNames'][$joinColumn['name']] = $joinColumn['fieldName'] ?? $joinColumn['name']; + $mapping['joinColumnFieldNames'][$joinColumn['name']] = $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."); + 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 - ]; + $this->table['uniqueConstraints'][$mapping['fieldName'] . '_uniq'] = ['columns' => $uniqueConstraintColumns]; } $mapping['targetToSourceKeyColumns'] = array_flip($mapping['sourceToTargetKeyColumns']); @@ -1673,7 +1678,7 @@ protected function _validateAndCompleteOneToOneMapping(array $mapping) unset($mapping['unique']); } - if (isset($mapping['id']) && $mapping['id'] === true && !$mapping['isOwningSide']) { + if (isset($mapping['id']) && $mapping['id'] === true && ! $mapping['isOwningSide']) { throw MappingException::illegalInverseIdentifierAssociation($this->name, $mapping['fieldName']); } @@ -1712,7 +1717,7 @@ protected function _validateAndCompleteOneToManyMapping(array $mapping) $mapping = $this->_validateAndCompleteAssociationMapping($mapping); // OneToMany-side MUST be inverse (must have mappedBy) - if ( ! isset($mapping['mappedBy'])) { + if (! isset($mapping['mappedBy'])) { throw MappingException::oneToManyRequiresMappedBy($mapping['fieldName']); } @@ -1731,7 +1736,7 @@ protected function _validateAndCompleteOneToManyMapping(array $mapping) * * @return mixed[] The validated & completed mapping. * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException * * @psalm-return array{isOwningSide: mixed, orphanRemoval: bool} */ @@ -1741,30 +1746,30 @@ protected function _validateAndCompleteManyToManyMapping(array $mapping) if ($mapping['isOwningSide']) { // owning side MUST have a join table - if ( ! isset($mapping['joinTable']['name'])) { + if (! isset($mapping['joinTable']['name'])) { $mapping['joinTable']['name'] = $this->namingStrategy->joinTableName($mapping['sourceEntity'], $mapping['targetEntity'], $mapping['fieldName']); } - $selfReferencingEntityWithoutJoinColumns = $mapping['sourceEntity'] == $mapping['targetEntity'] + $selfReferencingEntityWithoutJoinColumns = $mapping['sourceEntity'] === $mapping['targetEntity'] && (! (isset($mapping['joinTable']['joinColumns']) || isset($mapping['joinTable']['inverseJoinColumns']))); - if ( ! isset($mapping['joinTable']['joinColumns'])) { + if (! isset($mapping['joinTable']['joinColumns'])) { $mapping['joinTable']['joinColumns'] = [ [ 'name' => $this->namingStrategy->joinKeyColumnName($mapping['sourceEntity'], $selfReferencingEntityWithoutJoinColumns ? 'source' : null), 'referencedColumnName' => $this->namingStrategy->referenceColumnName(), - 'onDelete' => 'CASCADE' - ] + 'onDelete' => 'CASCADE', + ], ]; } - if ( ! isset($mapping['joinTable']['inverseJoinColumns'])) { + if (! isset($mapping['joinTable']['inverseJoinColumns'])) { $mapping['joinTable']['inverseJoinColumns'] = [ [ 'name' => $this->namingStrategy->joinKeyColumnName($mapping['targetEntity'], $selfReferencingEntityWithoutJoinColumns ? 'target' : null), 'referencedColumnName' => $this->namingStrategy->referenceColumnName(), - 'onDelete' => 'CASCADE' - ] + 'onDelete' => 'CASCADE', + ], ]; } @@ -1789,12 +1794,12 @@ protected function _validateAndCompleteManyToManyMapping(array $mapping) $joinColumn['quoted'] = true; } - if (isset($joinColumn['onDelete']) && strtolower($joinColumn['onDelete']) == 'cascade') { + if (isset($joinColumn['onDelete']) && strtolower($joinColumn['onDelete']) === 'cascade') { $mapping['isOnDeleteCascade'] = true; } $mapping['relationToSourceKeyColumns'][$joinColumn['name']] = $joinColumn['referencedColumnName']; - $mapping['joinTableColumns'][] = $joinColumn['name']; + $mapping['joinTableColumns'][] = $joinColumn['name']; } foreach ($mapping['joinTable']['inverseJoinColumns'] as &$inverseJoinColumn) { @@ -1812,16 +1817,16 @@ protected function _validateAndCompleteManyToManyMapping(array $mapping) } if ($inverseJoinColumn['referencedColumnName'][0] === '`') { - $inverseJoinColumn['referencedColumnName'] = trim($inverseJoinColumn['referencedColumnName'], '`'); - $inverseJoinColumn['quoted'] = true; + $inverseJoinColumn['referencedColumnName'] = trim($inverseJoinColumn['referencedColumnName'], '`'); + $inverseJoinColumn['quoted'] = true; } - if (isset($inverseJoinColumn['onDelete']) && strtolower($inverseJoinColumn['onDelete']) == 'cascade') { + if (isset($inverseJoinColumn['onDelete']) && strtolower($inverseJoinColumn['onDelete']) === 'cascade') { $mapping['isOnDeleteCascade'] = true; } $mapping['relationToTargetKeyColumns'][$inverseJoinColumn['name']] = $inverseJoinColumn['referencedColumnName']; - $mapping['joinTableColumns'][] = $inverseJoinColumn['name']; + $mapping['joinTableColumns'][] = $inverseJoinColumn['name']; } } @@ -1854,7 +1859,7 @@ public function getSingleIdentifierFieldName() throw MappingException::singleIdNotAllowedOnCompositePrimaryKey($this->name); } - if ( ! isset($this->identifier[0])) { + if (! isset($this->identifier[0])) { throw MappingException::noIdDefined($this->name); } @@ -1885,7 +1890,7 @@ public function getSingleIdentifierColumnName() */ public function setIdentifier(array $identifier) { - $this->identifier = $identifier; + $this->identifier = $identifier; $this->isIdentifierComposite = (count($this->identifier) > 1); } @@ -1914,9 +1919,9 @@ public function hasField($fieldName) * * @psalm-return list */ - public function getColumnNames(array $fieldNames = null) + public function getColumnNames(?array $fieldNames = null) { - if (null === $fieldNames) { + if ($fieldNames === null) { return array_keys($this->fieldNames); } @@ -1941,7 +1946,9 @@ public function getIdentifierColumnNames() // Association defined as Id field $joinColumns = $this->associationMappings[$idProperty]['joinColumns']; - $assocColumnNames = array_map(function ($joinColumn) { return $joinColumn['name']; }, $joinColumns); + $assocColumnNames = array_map(static function ($joinColumn) { + return $joinColumn['name']; + }, $joinColumns); $columnNames = array_merge($columnNames, $assocColumnNames); } @@ -1964,103 +1971,103 @@ public function setIdGeneratorType($generatorType) /** * Checks whether the mapped class uses an Id generator. * - * @return boolean TRUE if the mapped class uses an Id generator, FALSE otherwise. + * @return bool TRUE if the mapped class uses an Id generator, FALSE otherwise. */ public function usesIdGenerator() { - return $this->generatorType != self::GENERATOR_TYPE_NONE; + return $this->generatorType !== self::GENERATOR_TYPE_NONE; } /** - * @return boolean + * @return bool */ public function isInheritanceTypeNone() { - return $this->inheritanceType == self::INHERITANCE_TYPE_NONE; + 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. + * @return bool TRUE if the class participates in a JOINED inheritance mapping, + * FALSE otherwise. */ public function isInheritanceTypeJoined() { - return $this->inheritanceType == self::INHERITANCE_TYPE_JOINED; + 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. + * @return bool TRUE if the class participates in a SINGLE_TABLE inheritance mapping, + * FALSE otherwise. */ public function isInheritanceTypeSingleTable() { - return $this->inheritanceType == self::INHERITANCE_TYPE_SINGLE_TABLE; + 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. + * @return bool 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; + 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. + * @return bool TRUE if the class uses the IDENTITY generator, FALSE otherwise. */ public function isIdGeneratorIdentity() { - return $this->generatorType == self::GENERATOR_TYPE_IDENTITY; + 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. + * @return bool TRUE if the class uses the SEQUENCE generator, FALSE otherwise. */ public function isIdGeneratorSequence() { - return $this->generatorType == self::GENERATOR_TYPE_SEQUENCE; + 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. + * @return bool TRUE if the class uses the TABLE generator, FALSE otherwise. */ public function isIdGeneratorTable() { - return $this->generatorType == self::GENERATOR_TYPE_TABLE; + 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 + * @return bool */ public function isIdentifierNatural() { - return $this->generatorType == self::GENERATOR_TYPE_NONE; + return $this->generatorType === self::GENERATOR_TYPE_NONE; } /** * Checks whether the class use a UUID for id generation. * - * @return boolean + * @return bool */ public function isIdentifierUuid() { - return $this->generatorType == self::GENERATOR_TYPE_UUID; + return $this->generatorType === self::GENERATOR_TYPE_UUID; } /** @@ -2082,12 +2089,12 @@ public function getTypeOfField($fieldName) /** * Gets the type of a column. * + * @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. + * * @param string $columnName * * @return 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) { @@ -2111,7 +2118,7 @@ public function getTableName() */ public function getSchemaName() { - return isset($this->table['schema']) ? $this->table['schema'] : null; + return $this->table['schema'] ?? null; } /** @@ -2160,7 +2167,7 @@ public function setParentClasses(array $classNames) /** * Sets the inheritance type used by the class and its subclasses. * - * @param integer $type + * @param int $type * * @return void * @@ -2168,7 +2175,7 @@ public function setParentClasses(array $classNames) */ public function setInheritanceType($type) { - if ( ! $this->_isInheritanceType($type)) { + if (! $this->_isInheritanceType($type)) { throw MappingException::invalidInheritanceType($this->name, $type); } @@ -2187,7 +2194,7 @@ public function setInheritanceType($type) */ public function setAssociationOverride($fieldName, array $overrideMapping) { - if ( ! isset($this->associationMappings[$fieldName])) { + if (! isset($this->associationMappings[$fieldName])) { throw MappingException::invalidOverrideFieldName($this->name, $fieldName); } @@ -2216,11 +2223,11 @@ public function setAssociationOverride($fieldName, array $overrideMapping) $mapping['fetch'] = $overrideMapping['fetch']; } - $mapping['joinColumnFieldNames'] = null; - $mapping['joinTableColumns'] = null; - $mapping['sourceToTargetKeyColumns'] = null; - $mapping['relationToSourceKeyColumns'] = null; - $mapping['relationToTargetKeyColumns'] = null; + $mapping['joinColumnFieldNames'] = null; + $mapping['joinTableColumns'] = null; + $mapping['sourceToTargetKeyColumns'] = null; + $mapping['relationToSourceKeyColumns'] = null; + $mapping['relationToTargetKeyColumns'] = null; switch ($mapping['type']) { case self::ONE_TO_ONE: @@ -2252,7 +2259,7 @@ public function setAssociationOverride($fieldName, array $overrideMapping) */ public function setAttributeOverride($fieldName, array $overrideMapping) { - if ( ! isset($this->fieldMappings[$fieldName])) { + if (! isset($this->fieldMappings[$fieldName])) { throw MappingException::invalidOverrideFieldName($this->name, $fieldName); } @@ -2267,11 +2274,11 @@ public function setAttributeOverride($fieldName, array $overrideMapping) $overrideMapping['id'] = $mapping['id']; } - if ( ! isset($overrideMapping['type'])) { + if (! isset($overrideMapping['type'])) { $overrideMapping['type'] = $mapping['type']; } - if ( ! isset($overrideMapping['fieldName'])) { + if (! isset($overrideMapping['fieldName'])) { $overrideMapping['fieldName'] = $mapping['fieldName']; } @@ -2307,7 +2314,7 @@ public function isInheritedField($fieldName) */ public function isRootEntity() { - return $this->name == $this->rootEntityName; + return $this->name === $this->rootEntityName; } /** @@ -2315,7 +2322,7 @@ public function isRootEntity() * * @param string $fieldName * - * @return boolean TRUE if the field is inherited, FALSE otherwise. + * @return bool TRUE if the field is inherited, FALSE otherwise. */ public function isInheritedAssociation($fieldName) { @@ -2330,11 +2337,11 @@ public function isInheritedEmbeddedClass($fieldName) /** * Sets the name of the primary table the class is mapped to. * + * @deprecated Use {@link setPrimaryTable}. + * * @param string $tableName The table name. * * @return void - * - * @deprecated Use {@link setPrimaryTable}. */ public function setTableName($tableName) { @@ -2364,8 +2371,8 @@ public function setPrimaryTable(array $table) } if ($table['name'][0] === '`') { - $table['name'] = trim($table['name'], '`'); - $this->table['quoted'] = true; + $table['name'] = trim($table['name'], '`'); + $this->table['quoted'] = true; } $this->table['name'] = $table['name']; @@ -2395,16 +2402,16 @@ public function setPrimaryTable(array $table) /** * Checks whether the given type identifies an inheritance type. * - * @param integer $type + * @param int $type * - * @return boolean TRUE if the given type identifies an inheritance type, FALSe otherwise. + * @return bool 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; + return $type === self::INHERITANCE_TYPE_NONE || + $type === self::INHERITANCE_TYPE_SINGLE_TABLE || + $type === self::INHERITANCE_TYPE_JOINED || + $type === self::INHERITANCE_TYPE_TABLE_PER_CLASS; } /** @@ -2440,6 +2447,7 @@ public function addInheritedAssociationMapping(array $mapping/*, $owningClassNam if (isset($this->associationMappings[$mapping['fieldName']])) { throw MappingException::duplicateAssociationMapping($this->name, $mapping['fieldName']); } + $this->associationMappings[$mapping['fieldName']] = $mapping; } @@ -2455,8 +2463,8 @@ public function addInheritedAssociationMapping(array $mapping/*, $owningClassNam public function addInheritedFieldMapping(array $fieldMapping) { $this->fieldMappings[$fieldMapping['fieldName']] = $fieldMapping; - $this->columnNames[$fieldMapping['fieldName']] = $fieldMapping['columnName']; - $this->fieldNames[$fieldMapping['columnName']] = $fieldMapping['fieldName']; + $this->columnNames[$fieldMapping['fieldName']] = $fieldMapping['columnName']; + $this->fieldNames[$fieldMapping['columnName']] = $fieldMapping['fieldName']; } /** @@ -2471,7 +2479,7 @@ public function addInheritedFieldMapping(array $fieldMapping) */ public function addNamedQuery(array $queryMapping) { - if (!isset($queryMapping['name'])) { + if (! isset($queryMapping['name'])) { throw MappingException::nameIsMandatoryForQueryMapping($this->name); } @@ -2479,13 +2487,13 @@ public function addNamedQuery(array $queryMapping) throw MappingException::duplicateQueryMapping($this->name, $queryMapping['name']); } - if (!isset($queryMapping['query'])) { + if (! isset($queryMapping['query'])) { throw MappingException::emptyQueryMapping($this->name, $queryMapping['name']); } - $name = $queryMapping['name']; - $query = $queryMapping['query']; - $dql = str_replace('__CLASS__', $this->name, $query); + $name = $queryMapping['name']; + $query = $queryMapping['query']; + $dql = str_replace('__CLASS__', $this->name, $query); $this->namedQueries[$name] = [ 'name' => $name, @@ -2506,7 +2514,7 @@ public function addNamedQuery(array $queryMapping) */ public function addNamedNativeQuery(array $queryMapping) { - if (!isset($queryMapping['name'])) { + if (! isset($queryMapping['name'])) { throw MappingException::nameIsMandatoryForQueryMapping($this->name); } @@ -2514,11 +2522,11 @@ public function addNamedNativeQuery(array $queryMapping) throw MappingException::duplicateQueryMapping($this->name, $queryMapping['name']); } - if (!isset($queryMapping['query'])) { + if (! isset($queryMapping['query'])) { throw MappingException::emptyQueryMapping($this->name, $queryMapping['name']); } - if (!isset($queryMapping['resultClass']) && !isset($queryMapping['resultSetMapping'])) { + if (! isset($queryMapping['resultClass']) && ! isset($queryMapping['resultSetMapping'])) { throw MappingException::missingQueryMapping($this->name, $queryMapping['name']); } @@ -2526,7 +2534,6 @@ public function addNamedNativeQuery(array $queryMapping) if (isset($queryMapping['resultClass'])) { if ($queryMapping['resultClass'] === '__CLASS__') { - $queryMapping['isSelfClass'] = true; $queryMapping['resultClass'] = $this->name; } @@ -2550,7 +2557,7 @@ public function addNamedNativeQuery(array $queryMapping) */ public function addSqlResultSetMapping(array $resultMapping) { - if (!isset($resultMapping['name'])) { + if (! isset($resultMapping['name'])) { throw MappingException::nameIsMandatoryForSqlResultSetMapping($this->name); } @@ -2560,16 +2567,14 @@ public function addSqlResultSetMapping(array $resultMapping) if (isset($resultMapping['entities'])) { foreach ($resultMapping['entities'] as $key => $entityResult) { - if (!isset($entityResult['entityClass'])) { + 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']); @@ -2579,11 +2584,11 @@ public function addSqlResultSetMapping(array $resultMapping) if (isset($entityResult['fields'])) { foreach ($entityResult['fields'] as $k => $field) { - if (!isset($field['name'])) { + if (! isset($field['name'])) { throw MappingException::missingResultSetMappingFieldName($this->name, $resultMapping['name']); } - if (!isset($field['column'])) { + if (! isset($field['column'])) { $fieldName = $field['name']; if (strpos($fieldName, '.')) { [, $fieldName] = explode('.', $fieldName); @@ -2719,7 +2724,7 @@ public function invokeLifecycleCallbacks($lifecycleEvent, $entity) * * @param string $lifecycleEvent * - * @return boolean + * @return bool */ public function hasLifecycleCallbacks($lifecycleEvent) { @@ -2735,7 +2740,7 @@ public function hasLifecycleCallbacks($lifecycleEvent) */ public function getLifecycleCallbacks($event) { - return isset($this->lifecycleCallbacks[$event]) ? $this->lifecycleCallbacks[$event] : []; + return $this->lifecycleCallbacks[$event] ?? []; } /** @@ -2775,22 +2780,22 @@ public function setLifecycleCallbacks(array $callbacks) * @param string $class The listener class. * @param string $method The listener callback method. * - * @throws \Doctrine\ORM\Mapping\MappingException + * @throws MappingException */ public function addEntityListener($eventName, $class, $method) { - $class = $this->fullyQualifiedClassName($class); + $class = $this->fullyQualifiedClassName($class); $listener = [ 'class' => $class, 'method' => $method, ]; - if ( ! class_exists($class)) { + if (! class_exists($class)) { throw MappingException::entityListenerClassNotFound($class, $this->name); } - if ( ! method_exists($class, $method)) { + if (! method_exists($class, $method)) { throw MappingException::entityListenerMethodNotFound($class, $method, $this->name); } @@ -2804,18 +2809,18 @@ public function addEntityListener($eventName, $class, $method) /** * Sets the discriminator column definition. * + * @see getDiscriminatorColumn() + * * @param array $columnDef * * @return void * * @throws MappingException - * - * @see getDiscriminatorColumn() */ public function setDiscriminatorColumn($columnDef) { if ($columnDef !== null) { - if ( ! isset($columnDef['name'])) { + if (! isset($columnDef['name'])) { throw MappingException::nameIsMandatoryForDiscriminatorColumns($this->name); } @@ -2823,15 +2828,15 @@ public function setDiscriminatorColumn($columnDef) throw MappingException::duplicateColumnName($this->name, $columnDef['name']); } - if ( ! isset($columnDef['fieldName'])) { + if (! isset($columnDef['fieldName'])) { $columnDef['fieldName'] = $columnDef['name']; } - if ( ! isset($columnDef['type'])) { - $columnDef['type'] = "string"; + if (! isset($columnDef['type'])) { + $columnDef['type'] = 'string'; } - if (in_array($columnDef['type'], ["boolean", "array", "object", "datetime", "time", "date"])) { + if (in_array($columnDef['type'], ['boolean', 'array', 'object', 'datetime', 'time', 'date'])) { throw MappingException::invalidDiscriminatorColumnType($this->name, $columnDef['type']); } @@ -2877,7 +2882,7 @@ public function addDiscriminatorMapClass($name, $className) return; } - if ( ! (class_exists($className) || interface_exists($className))) { + if (! (class_exists($className) || interface_exists($className))) { throw MappingException::invalidClassInDiscriminatorMap($className, $this->name); } @@ -2891,7 +2896,7 @@ public function addDiscriminatorMapClass($name, $className) * * @param string $queryName * - * @return boolean + * @return bool */ public function hasNamedQuery($queryName) { @@ -2903,7 +2908,7 @@ public function hasNamedQuery($queryName) * * @param string $queryName * - * @return boolean + * @return bool */ public function hasNamedNativeQuery($queryName) { @@ -2915,7 +2920,7 @@ public function hasNamedNativeQuery($queryName) * * @param string $name * - * @return boolean + * @return bool */ public function hasSqlResultSetMapping($name) { @@ -2973,7 +2978,7 @@ public function isAssociationWithSingleJoinColumn($fieldName) */ public function getSingleAssociationJoinColumnName($fieldName) { - if ( ! $this->isAssociationWithSingleJoinColumn($fieldName)) { + if (! $this->isAssociationWithSingleJoinColumn($fieldName)) { throw MappingException::noSingleAssociationJoinColumnFound($this->name, $fieldName); } @@ -2991,7 +2996,7 @@ public function getSingleAssociationJoinColumnName($fieldName) */ public function getSingleAssociationReferencedJoinColumnName($fieldName) { - if ( ! $this->isAssociationWithSingleJoinColumn($fieldName)) { + if (! $this->isAssociationWithSingleJoinColumn($fieldName)) { throw MappingException::noSingleAssociationJoinColumnFound($this->name, $fieldName); } @@ -3016,9 +3021,10 @@ public function getFieldForColumn($columnName) } foreach ($this->associationMappings as $assocName => $mapping) { - if ($this->isAssociationWithSingleJoinColumn($assocName) && - $this->associationMappings[$assocName]['joinColumns'][0]['name'] == $columnName) { - + if ( + $this->isAssociationWithSingleJoinColumn($assocName) && + $this->associationMappings[$assocName]['joinColumns'][0]['name'] === $columnName + ) { return $assocName; } } @@ -3029,7 +3035,7 @@ public function getFieldForColumn($columnName) /** * Sets the ID generator used to generate IDs for instances of this class. * - * @param \Doctrine\ORM\Id\AbstractIdGenerator $generator + * @param AbstractIdGenerator $generator * * @return void */ @@ -3071,20 +3077,20 @@ public function setCustomGeneratorDefinition(array $definition) */ public function setSequenceGeneratorDefinition(array $definition) { - if ( ! isset($definition['sequenceName']) || trim($definition['sequenceName']) === '') { + if (! isset($definition['sequenceName']) || trim($definition['sequenceName']) === '') { throw MappingException::missingSequenceName($this->name); } - if ($definition['sequenceName'][0] == '`') { - $definition['sequenceName'] = trim($definition['sequenceName'], '`'); - $definition['quoted'] = true; + if ($definition['sequenceName'][0] === '`') { + $definition['sequenceName'] = trim($definition['sequenceName'], '`'); + $definition['quoted'] = true; } - if ( ! isset($definition['allocationSize']) || trim($definition['allocationSize']) === '') { + if (! isset($definition['allocationSize']) || trim($definition['allocationSize']) === '') { $definition['allocationSize'] = '1'; } - if ( ! isset($definition['initialValue']) || trim($definition['initialValue']) === '') { + if (! isset($definition['initialValue']) || trim($definition['initialValue']) === '') { $definition['initialValue'] = '1'; } @@ -3103,13 +3109,13 @@ public function setSequenceGeneratorDefinition(array $definition) */ public function setVersionMapping(array &$mapping) { - $this->isVersioned = true; + $this->isVersioned = true; $this->versionField = $mapping['fieldName']; - if ( ! isset($mapping['default'])) { + if (! isset($mapping['default'])) { if (in_array($mapping['type'], ['integer', 'bigint', 'smallint'])) { $mapping['default'] = 1; - } else if ($mapping['type'] == 'datetime') { + } elseif ($mapping['type'] === 'datetime') { $mapping['default'] = 'CURRENT_TIMESTAMP'; } else { throw MappingException::unsupportedOptimisticLockingType($this->name, $mapping['fieldName'], $mapping['type']); @@ -3120,7 +3126,7 @@ public function setVersionMapping(array &$mapping) /** * Sets whether this class is to be versioned for optimistic locking. * - * @param boolean $bool + * @param bool $bool * * @return void */ @@ -3175,8 +3181,8 @@ public function getAssociationNames() */ public function getAssociationTargetClass($assocName) { - if ( ! isset($this->associationMappings[$assocName])) { - throw new InvalidArgumentException("Association name expected, '" . $assocName ."' is not an association."); + if (! isset($this->associationMappings[$assocName])) { + throw new InvalidArgumentException("Association name expected, '" . $assocName . "' is not an association."); } return $this->associationMappings[$assocName]['targetEntity']; @@ -3195,7 +3201,7 @@ public function getName() * * @deprecated Deprecated since version 2.3 in favor of \Doctrine\ORM\Mapping\QuoteStrategy * - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform + * @param AbstractPlatform $platform * * @return array */ @@ -3215,7 +3221,7 @@ public function getQuotedIdentifierColumnNames($platform) // Association defined as Id field $joinColumns = $this->associationMappings[$idProperty]['joinColumns']; $assocQuotedColumnNames = array_map( - function ($joinColumn) use ($platform) { + static function ($joinColumn) use ($platform) { return isset($joinColumn['quoted']) ? $platform->quoteIdentifier($joinColumn['name']) : $joinColumn['name']; @@ -3234,8 +3240,8 @@ function ($joinColumn) use ($platform) { * * @deprecated Deprecated since version 2.3 in favor of \Doctrine\ORM\Mapping\QuoteStrategy * - * @param string $field - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform + * @param string $field + * @param AbstractPlatform $platform * * @return string */ @@ -3251,7 +3257,7 @@ public function getQuotedColumnName($field, $platform) * * @deprecated Deprecated since version 2.3 in favor of \Doctrine\ORM\Mapping\QuoteStrategy * - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform + * @param AbstractPlatform $platform * * @return string */ @@ -3267,8 +3273,8 @@ public function getQuotedTableName($platform) * * @deprecated Deprecated since version 2.3 in favor of \Doctrine\ORM\Mapping\QuoteStrategy * - * @param array $assoc - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform + * @param array $assoc + * @param AbstractPlatform $platform * * @return string */ @@ -3306,7 +3312,7 @@ public function getAssociationsByTargetClass($targetClass) $relations = []; foreach ($this->associationMappings as $mapping) { - if ($mapping['targetEntity'] == $targetClass) { + if ($mapping['targetEntity'] === $targetClass) { $relations[$mapping['fieldName']] = $mapping; } } @@ -3341,7 +3347,6 @@ public function fullyQualifiedClassName($className) */ public function getMetadataValue($name) { - if (isset($this->$name)) { return $this->$name; } @@ -3354,8 +3359,9 @@ public function getMetadataValue($name) * * @param array $mapping * - * @throws MappingException * @return void + * + * @throws MappingException */ public function mapEmbedded(array $mapping) { @@ -3372,8 +3378,7 @@ public function mapEmbedded(array $mapping) /** * Inline the embeddable class * - * @param string $property - * @param ClassMetadataInfo $embeddable + * @param string $property */ public function inlineEmbeddable($property, ClassMetadataInfo $embeddable) { @@ -3383,7 +3388,7 @@ public function inlineEmbeddable($property, ClassMetadataInfo $embeddable) ? $property . '.' . $fieldMapping['declaredField'] : $property; $fieldMapping['originalField'] = $fieldMapping['originalField'] ?? $fieldMapping['fieldName']; - $fieldMapping['fieldName'] = $property . "." . $fieldMapping['fieldName']; + $fieldMapping['fieldName'] = $property . '.' . $fieldMapping['fieldName']; if (! empty($this->embeddedClasses[$property]['columnPrefix'])) { $fieldMapping['columnName'] = $this->embeddedClasses[$property]['columnPrefix'] . $fieldMapping['columnName']; @@ -3403,14 +3408,16 @@ public function inlineEmbeddable($property, ClassMetadataInfo $embeddable) /** * @param string $fieldName + * * @throws MappingException */ private function assertFieldNotMapped($fieldName) { - if (isset($this->fieldMappings[$fieldName]) || + if ( + isset($this->fieldMappings[$fieldName]) || isset($this->associationMappings[$fieldName]) || - isset($this->embeddedClasses[$fieldName])) { - + isset($this->embeddedClasses[$fieldName]) + ) { throw MappingException::duplicateFieldMapping($this->name, $fieldName); } } @@ -3418,7 +3425,6 @@ private function assertFieldNotMapped($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 @@ -3427,15 +3433,13 @@ public function getSequenceName(AbstractPlatform $platform) { $sequencePrefix = $this->getSequencePrefix($platform); $columnName = $this->getSingleIdentifierColumnName(); - $sequenceName = $sequencePrefix . '_' . $columnName . '_seq'; - return $sequenceName; + return $sequencePrefix . '_' . $columnName . '_seq'; } /** * 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 @@ -3449,7 +3453,7 @@ public function getSequencePrefix(AbstractPlatform $platform) if ($schemaName = $this->getSchemaName()) { $sequencePrefix = $schemaName . '.' . $tableName; - if ( ! $platform->supportsSchemas() && $platform->canEmulateSchemas()) { + if (! $platform->supportsSchemas() && $platform->canEmulateSchemas()) { $sequencePrefix = $schemaName . '__' . $tableName; } } @@ -3462,7 +3466,7 @@ public function getSequencePrefix(AbstractPlatform $platform) */ private function assertMappingOrderBy(array $mapping) { - if (isset($mapping['orderBy']) && !is_array($mapping['orderBy'])) { + 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 index 711590be672..06a367c4c44 100644 --- a/lib/Doctrine/ORM/Mapping/Column.php +++ b/lib/Doctrine/ORM/Mapping/Column.php @@ -1,4 +1,5 @@ - * @since 2.3 - * * @Annotation * @Target("ANNOTATION") */ diff --git a/lib/Doctrine/ORM/Mapping/CustomIdGenerator.php b/lib/Doctrine/ORM/Mapping/CustomIdGenerator.php index 41e200e12a7..c59706efacf 100644 --- a/lib/Doctrine/ORM/Mapping/CustomIdGenerator.php +++ b/lib/Doctrine/ORM/Mapping/CustomIdGenerator.php @@ -1,4 +1,5 @@ */ class DefaultEntityListenerResolver implements EntityListenerResolver { /** * @var array Map to store entity listener instances. - * * @psalm-var array */ private $instances = []; @@ -56,8 +60,8 @@ public function clear($className = null) */ public function register($object) { - if ( ! is_object($object)) { - throw new \InvalidArgumentException(sprintf('An object was expected, but got "%s".', gettype($object))); + if (! is_object($object)) { + throw new InvalidArgumentException(sprintf('An object was expected, but got "%s".', gettype($object))); } $this->instances[get_class($object)] = $object; @@ -69,7 +73,7 @@ public function register($object) public function resolve($className) { if (isset($this->instances[$className = trim($className, '\\')])) { - return $this->instances[$className]; + return $this->instances[$className]; } return $this->instances[$className] = new $className(); diff --git a/lib/Doctrine/ORM/Mapping/DefaultNamingStrategy.php b/lib/Doctrine/ORM/Mapping/DefaultNamingStrategy.php index ef7f76b1e92..631f643bd20 100644 --- a/lib/Doctrine/ORM/Mapping/DefaultNamingStrategy.php +++ b/lib/Doctrine/ORM/Mapping/DefaultNamingStrategy.php @@ -20,13 +20,15 @@ namespace Doctrine\ORM\Mapping; +use function strpos; +use function strrpos; +use function strtolower; +use function substr; + /** * The default NamingStrategy * - * * @link www.doctrine-project.org - * @since 2.3 - * @author Fabio B. Silva */ class DefaultNamingStrategy implements NamingStrategy { @@ -55,7 +57,7 @@ public function propertyToColumnName($propertyName, $className = null) */ public function embeddedFieldToColumnName($propertyName, $embeddedColumnName, $className = null, $embeddedClassName = null) { - return $propertyName.'_'.$embeddedColumnName; + return $propertyName . '_' . $embeddedColumnName; } /** diff --git a/lib/Doctrine/ORM/Mapping/DefaultQuoteStrategy.php b/lib/Doctrine/ORM/Mapping/DefaultQuoteStrategy.php index ade44a0624c..15d135298d3 100644 --- a/lib/Doctrine/ORM/Mapping/DefaultQuoteStrategy.php +++ b/lib/Doctrine/ORM/Mapping/DefaultQuoteStrategy.php @@ -1,4 +1,5 @@ */ class DefaultQuoteStrategy implements QuoteStrategy { @@ -48,10 +52,10 @@ public function getTableName(ClassMetadata $class, AbstractPlatform $platform) { $tableName = $class->table['name']; - if ( ! empty($class->table['schema'])) { + if (! empty($class->table['schema'])) { $tableName = $class->table['schema'] . '.' . $class->table['name']; - if ( ! $platform->supportsSchemas() && $platform->canEmulateSchemas()) { + if (! $platform->supportsSchemas() && $platform->canEmulateSchemas()) { $tableName = $class->table['schema'] . '__' . $class->table['name']; } } @@ -129,8 +133,7 @@ public function getIdentifierColumnNames(ClassMetadata $class, AbstractPlatform // Association defined as Id field $joinColumns = $class->associationMappings[$fieldName]['joinColumns']; $assocQuotedColumnNames = array_map( - function ($joinColumn) use ($platform) - { + static function ($joinColumn) use ($platform) { return isset($joinColumn['quoted']) ? $platform->quoteIdentifier($joinColumn['name']) : $joinColumn['name']; @@ -147,17 +150,17 @@ function ($joinColumn) use ($platform) /** * {@inheritdoc} */ - public function getColumnAlias($columnName, $counter, AbstractPlatform $platform, ClassMetadata $class = null) + 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; + $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 index 97ca7e9b577..dc016b12657 100644 --- a/lib/Doctrine/ORM/Mapping/DiscriminatorColumn.php +++ b/lib/Doctrine/ORM/Mapping/DiscriminatorColumn.php @@ -1,4 +1,5 @@ - */ + /** @var array */ public $value; } diff --git a/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php b/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php index 39c50af3409..307fb52c4bf 100644 --- a/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php +++ b/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan H. Wage - * @author Roman Borschel */ class AnnotationDriver extends AbstractAnnotationDriver { @@ -53,20 +58,20 @@ class AnnotationDriver extends AbstractAnnotationDriver */ public function loadMetadataForClass($className, ClassMetadata $metadata) { - /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadataInfo */ + /** @var ClassMetadataInfo $metadata */ $class = $metadata->getReflectionClass(); - if ( ! $class) { + 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); + $class = new ReflectionClass($metadata->name); } $classAnnotations = $this->reader->getClassAnnotations($class); if ($classAnnotations) { foreach ($classAnnotations as $key => $annot) { - if ( ! is_numeric($key)) { + if (! is_numeric($key)) { continue; } @@ -84,12 +89,12 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) if ($entityAnnot->readOnly) { $metadata->markReadOnly(); } - } else if (isset($classAnnotations[Mapping\MappedSuperclass::class])) { + } elseif (isset($classAnnotations[Mapping\MappedSuperclass::class])) { $mappedSuperclassAnnot = $classAnnotations[Mapping\MappedSuperclass::class]; $metadata->setCustomRepositoryClass($mappedSuperclassAnnot->repositoryClass); $metadata->isMappedSuperclass = true; - } else if (isset($classAnnotations[Mapping\Embeddable::class])) { + } elseif (isset($classAnnotations[Mapping\Embeddable::class])) { $metadata->isEmbeddedClass = true; } else { throw MappingException::classIsNotAValidEntityOrMappedSuperClass($className); @@ -100,22 +105,22 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $tableAnnot = $classAnnotations[Mapping\Table::class]; $primaryTable = [ 'name' => $tableAnnot->name, - 'schema' => $tableAnnot->schema + 'schema' => $tableAnnot->schema, ]; if ($tableAnnot->indexes !== null) { foreach ($tableAnnot->indexes as $indexAnnot) { $index = ['columns' => $indexAnnot->columns]; - if ( ! empty($indexAnnot->flags)) { + if (! empty($indexAnnot->flags)) { $index['flags'] = $indexAnnot->flags; } - if ( ! empty($indexAnnot->options)) { + if (! empty($indexAnnot->options)) { $index['options'] = $indexAnnot->options; } - if ( ! empty($indexAnnot->name)) { + if (! empty($indexAnnot->name)) { $primaryTable['indexes'][$indexAnnot->name] = $index; } else { $primaryTable['indexes'][] = $index; @@ -127,11 +132,11 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) foreach ($tableAnnot->uniqueConstraints as $uniqueConstraintAnnot) { $uniqueConstraint = ['columns' => $uniqueConstraintAnnot->columns]; - if ( ! empty($uniqueConstraintAnnot->options)) { + if (! empty($uniqueConstraintAnnot->options)) { $uniqueConstraint['options'] = $uniqueConstraintAnnot->options; } - if ( ! empty($uniqueConstraintAnnot->name)) { + if (! empty($uniqueConstraintAnnot->name)) { $primaryTable['uniqueConstraints'][$uniqueConstraintAnnot->name] = $uniqueConstraint; } else { $primaryTable['uniqueConstraints'][] = $uniqueConstraint; @@ -190,7 +195,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) foreach ($entityResultAnnot->fields as $fieldResultAnnot) { $entityResult['fields'][] = [ 'name' => $fieldResultAnnot->name, - 'column' => $fieldResultAnnot->column + 'column' => $fieldResultAnnot->column, ]; } @@ -207,7 +212,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) [ 'name' => $resultSetMapping->name, 'entities' => $entities, - 'columns' => $columns + 'columns' => $columns, ] ); } @@ -217,18 +222,19 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) if (isset($classAnnotations[Mapping\NamedQueries::class])) { $namedQueriesAnnot = $classAnnotations[Mapping\NamedQueries::class]; - if ( ! is_array($namedQueriesAnnot->value)) { - throw new \UnexpectedValueException("@NamedQueries should contain an array of @NamedQuery annotations."); + if (! is_array($namedQueriesAnnot->value)) { + throw new UnexpectedValueException('@NamedQueries should contain an array of @NamedQuery annotations.'); } foreach ($namedQueriesAnnot->value as $namedQuery) { - if ( ! ($namedQuery instanceof Mapping\NamedQuery)) { - throw new \UnexpectedValueException("@NamedQueries should contain an array of @NamedQuery annotations."); + if (! ($namedQuery instanceof Mapping\NamedQuery)) { + throw new UnexpectedValueException('@NamedQueries should contain an array of @NamedQuery annotations.'); } + $metadata->addNamedQuery( [ 'name' => $namedQuery->name, - 'query' => $namedQuery->query + 'query' => $namedQuery->query, ] ); } @@ -242,7 +248,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) constant('Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_' . $inheritanceTypeAnnot->value) ); - if ($metadata->inheritanceType != Mapping\ClassMetadata::INHERITANCE_TYPE_NONE) { + if ($metadata->inheritanceType !== Mapping\ClassMetadata::INHERITANCE_TYPE_NONE) { // Evaluate DiscriminatorColumn annotation if (isset($classAnnotations[Mapping\DiscriminatorColumn::class])) { $discrColumnAnnot = $classAnnotations[Mapping\DiscriminatorColumn::class]; @@ -267,7 +273,6 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } } - // Evaluate DoctrineChangeTrackingPolicy annotation if (isset($classAnnotations[Mapping\ChangeTrackingPolicy::class])) { $changeTrackingAnnot = $classAnnotations[Mapping\ChangeTrackingPolicy::class]; @@ -276,17 +281,19 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Evaluate annotations on properties/fields foreach ($class->getProperties() as $property) { - if ($metadata->isMappedSuperclass && ! $property->isPrivate() + if ( + $metadata->isMappedSuperclass && ! $property->isPrivate() || $metadata->isInheritedField($property->name) || $metadata->isInheritedAssociation($property->name) || - $metadata->isInheritedEmbeddedClass($property->name)) { + $metadata->isInheritedEmbeddedClass($property->name) + ) { continue; } - $mapping = []; + $mapping = []; $mapping['fieldName'] = $property->getName(); // Evaluate @Cache annotation @@ -299,12 +306,13 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) ] ); } + // 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)) { + } elseif ($joinColumnsAnnot = $this->reader->getPropertyAnnotation($property, Mapping\JoinColumns::class)) { foreach ($joinColumnsAnnot->value as $joinColumn) { $joinColumns[] = $this->joinColumnToArray($joinColumn); } @@ -313,7 +321,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // 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) { + if ($columnAnnot->type === null) { throw MappingException::propertyTypeIsRequired($className, $property->getName()); } @@ -339,62 +347,62 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) [ 'sequenceName' => $seqGeneratorAnnot->sequenceName, 'allocationSize' => $seqGeneratorAnnot->allocationSize, - 'initialValue' => $seqGeneratorAnnot->initialValue + 'initialValue' => $seqGeneratorAnnot->initialValue, ] ); } elseif ($this->reader->getPropertyAnnotation($property, 'Doctrine\ORM\Id\TableGenerator')) { throw MappingException::tableIdGeneratorNotImplemented($className); - } else if ($customGeneratorAnnot = $this->reader->getPropertyAnnotation($property, Mapping\CustomIdGenerator::class)) { + } elseif ($customGeneratorAnnot = $this->reader->getPropertyAnnotation($property, Mapping\CustomIdGenerator::class)) { $metadata->setCustomGeneratorDefinition( [ - 'class' => $customGeneratorAnnot->class + 'class' => $customGeneratorAnnot->class, ] ); } - } else if ($oneToOneAnnot = $this->reader->getPropertyAnnotation($property, Mapping\OneToOne::class)) { + } elseif ($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['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); + $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; + } elseif ($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); + $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)) { + } elseif ($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['joinColumns'] = $joinColumns; + $mapping['cascade'] = $manyToOneAnnot->cascade; + $mapping['inversedBy'] = $manyToOneAnnot->inversedBy; $mapping['targetEntity'] = $manyToOneAnnot->targetEntity; - $mapping['fetch'] = $this->getFetchMode($className, $manyToOneAnnot->fetch); + $mapping['fetch'] = $this->getFetchMode($className, $manyToOneAnnot->fetch); $metadata->mapManyToOne($mapping); - } else if ($manyToManyAnnot = $this->reader->getPropertyAnnotation($property, Mapping\ManyToMany::class)) { + } elseif ($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 + 'schema' => $joinTableAnnot->schema, ]; foreach ($joinTableAnnot->joinColumns as $joinColumn) { @@ -406,22 +414,22 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } } - $mapping['joinTable'] = $joinTable; - $mapping['targetEntity'] = $manyToManyAnnot->targetEntity; - $mapping['mappedBy'] = $manyToManyAnnot->mappedBy; - $mapping['inversedBy'] = $manyToManyAnnot->inversedBy; - $mapping['cascade'] = $manyToManyAnnot->cascade; - $mapping['indexBy'] = $manyToManyAnnot->indexBy; + $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); + $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; + } elseif ($embeddedAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Embedded::class)) { + $mapping['class'] = $embeddedAnnot->class; $mapping['columnPrefix'] = $embeddedAnnot->columnPrefix; $metadata->mapEmbedded($mapping); @@ -433,8 +441,8 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $associationOverridesAnnot = $classAnnotations[Mapping\AssociationOverrides::class]; foreach ($associationOverridesAnnot->value as $associationOverride) { - $override = []; - $fieldName = $associationOverride->name; + $override = []; + $fieldName = $associationOverride->name; // Check for JoinColumn/JoinColumns annotations if ($associationOverride->joinColumns) { @@ -452,7 +460,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $joinTableAnnot = $associationOverride->joinTable; $joinTable = [ 'name' => $joinTableAnnot->name, - 'schema' => $joinTableAnnot->schema + 'schema' => $joinTableAnnot->schema, ]; foreach ($joinTableAnnot->joinColumns as $joinColumn) { @@ -498,17 +506,17 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) foreach ($entityListenersAnnot->value as $item) { $listenerClassName = $metadata->fullyQualifiedClassName($item); - if ( ! class_exists($listenerClassName)) { + if (! class_exists($listenerClassName)) { throw MappingException::entityListenerClassNotFound($listenerClassName, $className); } - $hasMapping = false; - $listenerClass = new \ReflectionClass($listenerClassName); + $hasMapping = false; + $listenerClass = new ReflectionClass($listenerClassName); - foreach ($listenerClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { + foreach ($listenerClass->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { // find method callbacks. $callbacks = $this->getMethodCallbacks($method); - $hasMapping = $hasMapping ?: ( ! empty($callbacks)); + $hasMapping = $hasMapping ?: ! empty($callbacks); foreach ($callbacks as $value) { $metadata->addEntityListener($value[1], $listenerClassName, $value[0]); @@ -516,7 +524,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } // Evaluate the listener using naming convention. - if ( ! $hasMapping ) { + if (! $hasMapping) { EntityListenerBuilder::bindEntityListener($metadata, $listenerClassName); } } @@ -524,7 +532,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Evaluate @HasLifecycleCallbacks annotation if (isset($classAnnotations[Mapping\HasLifecycleCallbacks::class])) { - foreach ($class->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { + foreach ($class->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { foreach ($this->getMethodCallbacks($method) as $value) { $metadata->addLifecycleCallback($value[0], $value[1]); } @@ -538,13 +546,13 @@ 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 int The fetch mode as defined in ClassMetadata. * * @throws MappingException If the fetch mode is not valid. */ private function getFetchMode($className, $fetchMode) { - if ( ! defined('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . $fetchMode)) { + if (! defined('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . $fetchMode)) { throw MappingException::invalidFetchMode($className, $fetchMode); } @@ -554,11 +562,9 @@ private function getFetchMode($className, $fetchMode) /** * Parses the given method. * - * @param \ReflectionMethod $method - * * @return callable[] */ - private function getMethodCallbacks(\ReflectionMethod $method) + private function getMethodCallbacks(ReflectionMethod $method) { $callbacks = []; $annotations = $this->reader->getMethodAnnotations($method); @@ -603,8 +609,6 @@ private function getMethodCallbacks(\ReflectionMethod $method) /** * Parse the given JoinColumn as array * - * @param Mapping\JoinColumn $joinColumn - * * @return mixed[] * * @psalm-return array{ @@ -632,7 +636,6 @@ private function joinColumnToArray(Mapping\JoinColumn $joinColumn) * Parse the given Column as array * * @param string $fieldName - * @param Mapping\Column $column * * @return mixed[] * @@ -658,7 +661,7 @@ private function columnToArray($fieldName, Mapping\Column $column) 'length' => $column->length, 'unique' => $column->unique, 'nullable' => $column->nullable, - 'precision' => $column->precision + 'precision' => $column->precision, ]; if ($column->options) { @@ -679,14 +682,13 @@ private function columnToArray($fieldName, Mapping\Column $column) /** * Factory method for the Annotation Driver. * - * @param array|string $paths - * @param AnnotationReader|null $reader + * @param array|string $paths * * @return AnnotationDriver */ - static public function create($paths = [], AnnotationReader $reader = null) + public static function create($paths = [], ?AnnotationReader $reader = null) { - if ($reader == null) { + if ($reader === null) { $reader = new AnnotationReader(); } diff --git a/lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php b/lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php index 6e0df1f16bf..23c16a6673d 100644 --- a/lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php +++ b/lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Benjamin Eberlei */ class DatabaseDriver implements MappingDriver { - /** - * @var AbstractSchemaManager - */ + /** @var AbstractSchemaManager */ private $_sm; - /** - * @var array|null - */ + /** @var array|null */ private $tables = null; - /** - * @var array - */ + /** @var array */ private $classToTableNames = []; - /** - * @var array - */ + /** @var array */ private $manyToManyTables = []; - /** - * @var array - */ + /** @var array */ private $classNamesForTables = []; - /** - * @var array - */ + /** @var array */ private $fieldNamesForColumns = []; /** @@ -86,12 +79,9 @@ class DatabaseDriver implements MappingDriver /** @var Inflector */ private $inflector; - /** - * @param AbstractSchemaManager $schemaManager - */ public function __construct(AbstractSchemaManager $schemaManager) { - $this->_sm = $schemaManager; + $this->_sm = $schemaManager; $this->inflector = InflectorFactory::create()->build(); } @@ -168,7 +158,7 @@ public function setTables($entityTables, $manyToManyTables) $className = $this->getClassNameForTable($table->getName()); $this->classToTableNames[$className] = $table->getName(); - $this->tables[$table->getName()] = $table; + $this->tables[$table->getName()] = $table; } foreach ($manyToManyTables as $table) { @@ -176,7 +166,7 @@ public function setTables($entityTables, $manyToManyTables) } } - public function setInflector(Inflector $inflector) : void + public function setInflector(Inflector $inflector): void { $this->inflector = $inflector; } @@ -188,13 +178,13 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) { $this->reverseEngineerMappingFromDatabase(); - if ( ! isset($this->classToTableNames[$className])) { - throw new \InvalidArgumentException("Unknown class " . $className); + if (! isset($this->classToTableNames[$className])) { + throw new InvalidArgumentException('Unknown class ' . $className); } $tableName = $this->classToTableNames[$className]; - $metadata->name = $className; + $metadata->name = $className; $metadata->table['name'] = $tableName; $this->buildIndexes($metadata); @@ -204,21 +194,21 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) 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 (! (strtolower($tableName) === strtolower($foreignKey->getForeignTableName()))) { continue; } - $myFk = $foreignKey; + $myFk = $foreignKey; $otherFk = null; foreach ($manyTable->getForeignKeys() as $foreignKey) { - if ($foreignKey != $myFk) { + if ($foreignKey !== $myFk) { $otherFk = $foreignKey; break; } } - if ( ! $otherFk) { + if (! $otherFk) { // the definition of this many to many table does not contain // enough foreign key information to continue reverse engineering. continue; @@ -226,20 +216,20 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $localColumn = current($myFk->getColumns()); - $associationMapping = []; - $associationMapping['fieldName'] = $this->getFieldNameForColumn($manyTable->getName(), current($otherFk->getColumns()), true); + $associationMapping = []; + $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'] = [ + $associationMapping['joinTable'] = [ 'name' => strtolower($manyTable->getName()), 'joinColumns' => [], 'inverseJoinColumns' => [], ]; $fkCols = $myFk->getForeignColumns(); - $cols = $myFk->getColumns(); + $cols = $myFk->getColumns(); for ($i = 0, $colsCount = count($cols); $i < $colsCount; $i++) { $associationMapping['joinTable']['joinColumns'][] = [ @@ -249,7 +239,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } $fkCols = $otherFk->getForeignColumns(); - $cols = $otherFk->getColumns(); + $cols = $otherFk->getColumns(); for ($i = 0, $colsCount = count($cols); $i < $colsCount; $i++) { $associationMapping['joinTable']['inverseJoinColumns'][] = [ @@ -271,7 +261,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) /** * @return void * - * @throws \Doctrine\ORM\Mapping\MappingException + * @throws MappingException */ private function reverseEngineerMappingFromDatabase() { @@ -288,7 +278,7 @@ private function reverseEngineerMappingFromDatabase() $this->tables = $this->manyToManyTables = $this->classToTableNames = []; foreach ($tables as $tableName => $table) { - $foreignKeys = ($this->_sm->getDatabasePlatform()->supportsForeignKeyConstraints()) + $foreignKeys = $this->_sm->getDatabasePlatform()->supportsForeignKeyConstraints() ? $table->getForeignKeys() : []; @@ -298,9 +288,9 @@ private function reverseEngineerMappingFromDatabase() $allForeignKeyColumns = array_merge($allForeignKeyColumns, $foreignKey->getLocalColumns()); } - if ( ! $table->hasPrimaryKey()) { + if (! $table->hasPrimaryKey()) { throw new MappingException( - "Table " . $table->getName() . " has no primary key. Doctrine does not ". + 'Table ' . $table->getName() . ' has no primary key. Doctrine does not ' . "support reverse engineering from tables that don't have a primary key." ); } @@ -310,14 +300,14 @@ private function reverseEngineerMappingFromDatabase() sort($pkColumns); sort($allForeignKeyColumns); - if ($pkColumns == $allForeignKeyColumns && count($foreignKeys) == 2) { + if ($pkColumns === $allForeignKeyColumns && count($foreignKeys) === 2) { $this->manyToManyTables[$tableName] = $table; } else { // lower-casing is necessary because of Oracle Uppercase Tablenames, // assumption is lower-case + underscore separated. $className = $this->getClassNameForTable($tableName); - $this->tables[$tableName] = $table; + $this->tables[$tableName] = $table; $this->classToTableNames[$className] = $tableName; } } @@ -325,8 +315,6 @@ private function reverseEngineerMappingFromDatabase() /** * Build indexes from a class metadata. - * - * @param \Doctrine\ORM\Mapping\ClassMetadataInfo $metadata */ private function buildIndexes(ClassMetadataInfo $metadata) { @@ -350,8 +338,6 @@ private function buildIndexes(ClassMetadataInfo $metadata) /** * Build field mapping from class metadata. - * - * @param \Doctrine\ORM\Mapping\ClassMetadataInfo $metadata */ private function buildFieldMappings(ClassMetadataInfo $metadata) { @@ -377,14 +363,14 @@ private function buildFieldMappings(ClassMetadataInfo $metadata) if ($primaryKeys && in_array($column->getName(), $primaryKeys)) { $fieldMapping['id'] = true; - $ids[] = $fieldMapping; + $ids[] = $fieldMapping; } $fieldMappings[] = $fieldMapping; } // We need to check for the columns here, because we might have associations as id as well. - if ($ids && count($primaryKeys) == 1) { + if ($ids && count($primaryKeys) === 1) { $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); } @@ -396,8 +382,7 @@ private function buildFieldMappings(ClassMetadataInfo $metadata) /** * Build field mapping from a schema column definition * - * @param string $tableName - * @param \Doctrine\DBAL\Schema\Column $column + * @param string $tableName * * @return array * @@ -423,7 +408,7 @@ private function buildFieldMapping($tableName, Column $column) 'fieldName' => $this->getFieldNameForColumn($tableName, $column->getName(), false), 'columnName' => $column->getName(), 'type' => $column->getType()->getName(), - 'nullable' => ( ! $column->getNotnull()), + 'nullable' => ! $column->getNotnull(), ]; // Type specific elements @@ -436,8 +421,8 @@ 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(); + $fieldMapping['length'] = $column->getLength(); + $fieldMapping['options']['fixed'] = $column->getFixed(); break; case Type::DECIMAL: @@ -468,8 +453,6 @@ private function buildFieldMapping($tableName, Column $column) /** * Build to one (one to one, many to one) association mapping from class metadata. - * - * @param \Doctrine\ORM\Mapping\ClassMetadataInfo $metadata */ private function buildToOneAssociationMappings(ClassMetadataInfo $metadata) { @@ -503,7 +486,7 @@ private function buildToOneAssociationMappings(ClassMetadataInfo $metadata) } // Here we need to check if $fkColumns are the same as $primaryKeys - if ( ! array_diff($fkColumns, $primaryKeys)) { + if (! array_diff($fkColumns, $primaryKeys)) { $metadata->mapOneToOne($associationMapping); } else { $metadata->mapManyToOne($associationMapping); @@ -514,15 +497,13 @@ private function buildToOneAssociationMappings(ClassMetadataInfo $metadata) /** * Retrieve schema table definition foreign keys. * - * @param \Doctrine\DBAL\Schema\Table $table - * * @return ForeignKeyConstraint[] * * @psalm-return array */ private function getTableForeignKeys(Table $table) { - return ($this->_sm->getDatabasePlatform()->supportsForeignKeyConstraints()) + return $this->_sm->getDatabasePlatform()->supportsForeignKeyConstraints() ? $table->getForeignKeys() : []; } @@ -530,8 +511,6 @@ private function getTableForeignKeys(Table $table) /** * Retrieve schema table definition primary keys. * - * @param \Doctrine\DBAL\Schema\Table $table - * * @return string[] */ private function getTablePrimaryKeys(Table $table) @@ -564,9 +543,9 @@ private function getClassNameForTable($tableName) /** * Return the mapped field name for a column, if it exists. Otherwise return camelized version. * - * @param string $tableName - * @param string $columnName - * @param boolean $fk Whether the column is a foreignkey or not. + * @param string $tableName + * @param string $columnName + * @param bool $fk Whether the column is a foreignkey or not. * * @return string */ diff --git a/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php b/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php index 8f4a34c0ef4..c2c06b3e786 100644 --- a/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php +++ b/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php @@ -1,4 +1,5 @@ . */ -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'; +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 ed9c2be728e..0f94958f294 100644 --- a/lib/Doctrine/ORM/Mapping/Driver/DriverChain.php +++ b/lib/Doctrine/ORM/Mapping/Driver/DriverChain.php @@ -1,4 +1,5 @@ - * @author Benjamin Eberlei - * @license MIT */ class SimplifiedXmlDriver extends XmlDriver { - const DEFAULT_FILE_EXTENSION = '.orm.xml'; + public const DEFAULT_FILE_EXTENSION = '.orm.xml'; /** * {@inheritDoc} diff --git a/lib/Doctrine/ORM/Mapping/Driver/SimplifiedYamlDriver.php b/lib/Doctrine/ORM/Mapping/Driver/SimplifiedYamlDriver.php index d766d5dabf8..efae7c5731f 100644 --- a/lib/Doctrine/ORM/Mapping/Driver/SimplifiedYamlDriver.php +++ b/lib/Doctrine/ORM/Mapping/Driver/SimplifiedYamlDriver.php @@ -1,4 +1,5 @@ - * @author Benjamin Eberlei - * @license MIT */ class SimplifiedYamlDriver extends YamlDriver { - const DEFAULT_FILE_EXTENSION = '.orm.yml'; + public const DEFAULT_FILE_EXTENSION = '.orm.yml'; /** * {@inheritDoc} diff --git a/lib/Doctrine/ORM/Mapping/Driver/StaticPHPDriver.php b/lib/Doctrine/ORM/Mapping/Driver/StaticPHPDriver.php index 62079f3fa51..4e86b0b5e61 100644 --- a/lib/Doctrine/ORM/Mapping/Driver/StaticPHPDriver.php +++ b/lib/Doctrine/ORM/Mapping/Driver/StaticPHPDriver.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan H. Wage - * @author Roman Borschel + * @link www.doctrine-project.org */ class XmlDriver extends FileDriver { - const DEFAULT_FILE_EXTENSION = '.dcm.xml'; + public const DEFAULT_FILE_EXTENSION = '.dcm.xml'; /** * {@inheritDoc} @@ -56,23 +63,24 @@ public function __construct($locator, $fileExtension = self::DEFAULT_FILE_EXTENS */ public function loadMetadataForClass($className, ClassMetadata $metadata) { - /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadataInfo */ - /* @var $xmlRoot SimpleXMLElement */ + /** @var ClassMetadataInfo $metadata */ $xmlRoot = $this->getElement($className); + assert($xmlRoot instanceof SimpleXMLElement); - if ($xmlRoot->getName() == 'entity') { + if ($xmlRoot->getName() === 'entity') { if (isset($xmlRoot['repository-class'])) { $metadata->setCustomRepositoryClass((string) $xmlRoot['repository-class']); } + if (isset($xmlRoot['read-only']) && $this->evaluateBoolean($xmlRoot['read-only'])) { $metadata->markReadOnly(); } - } else if ($xmlRoot->getName() == 'mapped-superclass') { + } elseif ($xmlRoot->getName() === 'mapped-superclass') { $metadata->setCustomRepositoryClass( isset($xmlRoot['repository-class']) ? (string) $xmlRoot['repository-class'] : null ); $metadata->isMappedSuperclass = true; - } else if ($xmlRoot->getName() == 'embeddable') { + } elseif ($xmlRoot->getName() === 'embeddable') { $metadata->isEmbeddedClass = true; } else { throw MappingException::classIsNotAValidEntityOrMappedSuperClass($className); @@ -102,7 +110,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $metadata->addNamedQuery( [ 'name' => (string) $namedQueryElement['name'], - 'query' => (string) $namedQueryElement['query'] + 'query' => (string) $namedQueryElement['query'], ] ); } @@ -125,8 +133,8 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Evaluate sql result set mapping if (isset($xmlRoot->{'sql-result-set-mappings'})) { foreach ($xmlRoot->{'sql-result-set-mappings'}->{'sql-result-set-mapping'} as $rsmElement) { - $entities = []; - $columns = []; + $entities = []; + $columns = []; foreach ($rsmElement as $entityElement) { // if (isset($entityElement['entity-class'])) { @@ -158,7 +166,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) [ 'name' => (string) $rsmElement['name'], 'entities' => $entities, - 'columns' => $columns + 'columns' => $columns, ] ); } @@ -168,7 +176,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $inheritanceType = (string) $xmlRoot['inheritance-type']; $metadata->setInheritanceType(constant('Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_' . $inheritanceType)); - if ($metadata->inheritanceType != Metadata::INHERITANCE_TYPE_NONE) { + if ($metadata->inheritanceType !== Metadata::INHERITANCE_TYPE_NONE) { // Evaluate if (isset($xmlRoot->{'discriminator-column'})) { $discrColumn = $xmlRoot->{'discriminator-column'}; @@ -177,7 +185,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) '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 + 'columnDefinition' => isset($discrColumn['column-definition']) ? (string) $discrColumn['column-definition'] : null, ] ); } else { @@ -190,12 +198,12 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) foreach ($xmlRoot->{'discriminator-map'}->{'discriminator-mapping'} as $discrMapElement) { $map[(string) $discrMapElement['value']] = (string) $discrMapElement['class']; } + $metadata->setDiscriminatorMap($map); } } } - // Evaluate if (isset($xmlRoot['change-tracking-policy'])) { $metadata->setChangeTrackingPolicy(constant('Doctrine\ORM\Mapping\ClassMetadata::CHANGETRACKING_' @@ -276,7 +284,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $mapping = [ 'fieldName' => (string) $embeddedMapping['name'], 'class' => (string) $embeddedMapping['class'], - 'columnPrefix' => $useColumnPrefix ? $columnPrefix : false + 'columnPrefix' => $useColumnPrefix ? $columnPrefix : false, ]; $metadata->mapEmbedded($mapping); @@ -301,7 +309,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $mapping = [ 'id' => true, - 'fieldName' => (string) $idElement['name'] + 'fieldName' => (string) $idElement['name'], ]; if (isset($idElement['type'])) { @@ -340,17 +348,17 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) [ 'sequenceName' => (string) $seqGenerator['sequence-name'], 'allocationSize' => (string) $seqGenerator['allocation-size'], - 'initialValue' => (string) $seqGenerator['initial-value'] + 'initialValue' => (string) $seqGenerator['initial-value'], ] ); - } else if (isset($idElement->{'custom-id-generator'})) { + } elseif (isset($idElement->{'custom-id-generator'})) { $customGenerator = $idElement->{'custom-id-generator'}; $metadata->setCustomGeneratorDefinition( [ - 'class' => (string) $customGenerator['class'] + 'class' => (string) $customGenerator['class'], ] ); - } else if (isset($idElement->{'table-generator'})) { + } elseif (isset($idElement->{'table-generator'})) { throw MappingException::tableIdGeneratorNotImplemented($className); } } @@ -360,7 +368,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) foreach ($xmlRoot->{'one-to-one'} as $oneToOneElement) { $mapping = [ 'fieldName' => (string) $oneToOneElement['field'], - 'targetEntity' => (string) $oneToOneElement['target-entity'] + 'targetEntity' => (string) $oneToOneElement['target-entity'], ]; if (isset($associationIds[$mapping['fieldName']])) { @@ -377,11 +385,12 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) if (isset($oneToOneElement['inversed-by'])) { $mapping['inversedBy'] = (string) $oneToOneElement['inversed-by']; } + $joinColumns = []; if (isset($oneToOneElement->{'join-column'})) { $joinColumns[] = $this->joinColumnToArray($oneToOneElement->{'join-column'}); - } else if (isset($oneToOneElement->{'join-columns'})) { + } elseif (isset($oneToOneElement->{'join-columns'})) { foreach ($oneToOneElement->{'join-columns'}->{'join-column'} as $joinColumnElement) { $joinColumns[] = $this->joinColumnToArray($joinColumnElement); } @@ -413,7 +422,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $mapping = [ 'fieldName' => (string) $oneToManyElement['field'], 'targetEntity' => (string) $oneToManyElement['target-entity'], - 'mappedBy' => (string) $oneToManyElement['mapped-by'] + 'mappedBy' => (string) $oneToManyElement['mapped-by'], ]; if (isset($oneToManyElement['fetch'])) { @@ -433,16 +442,16 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) foreach ($oneToManyElement->{'order-by'}->{'order-by-field'} as $orderByField) { $orderBy[(string) $orderByField['name']] = isset($orderByField['direction']) ? (string) $orderByField['direction'] - : Criteria::ASC - ; + : Criteria::ASC; } + $mapping['orderBy'] = $orderBy; } if (isset($oneToManyElement['index-by'])) { $mapping['indexBy'] = (string) $oneToManyElement['index-by']; - } else if (isset($oneToManyElement->{'index-by'})) { - throw new \InvalidArgumentException(" is not a valid tag"); + } elseif (isset($oneToManyElement->{'index-by'})) { + throw new InvalidArgumentException(' is not a valid tag'); } // Evaluate second level cache @@ -459,7 +468,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) foreach ($xmlRoot->{'many-to-one'} as $manyToOneElement) { $mapping = [ 'fieldName' => (string) $manyToOneElement['field'], - 'targetEntity' => (string) $manyToOneElement['target-entity'] + 'targetEntity' => (string) $manyToOneElement['target-entity'], ]; if (isset($associationIds[$mapping['fieldName']])) { @@ -478,7 +487,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) if (isset($manyToOneElement->{'join-column'})) { $joinColumns[] = $this->joinColumnToArray($manyToOneElement->{'join-column'}); - } else if (isset($manyToOneElement->{'join-columns'})) { + } elseif (isset($manyToOneElement->{'join-columns'})) { foreach ($manyToOneElement->{'join-columns'}->{'join-column'} as $joinColumnElement) { $joinColumns[] = $this->joinColumnToArray($joinColumnElement); } @@ -496,7 +505,6 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } $metadata->mapManyToOne($mapping); - } } @@ -505,7 +513,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) foreach ($xmlRoot->{'many-to-many'} as $manyToManyElement) { $mapping = [ 'fieldName' => (string) $manyToManyElement['field'], - 'targetEntity' => (string) $manyToManyElement['target-entity'] + 'targetEntity' => (string) $manyToManyElement['target-entity'], ]; if (isset($manyToManyElement['fetch'])) { @@ -518,14 +526,14 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) if (isset($manyToManyElement['mapped-by'])) { $mapping['mappedBy'] = (string) $manyToManyElement['mapped-by']; - } else if (isset($manyToManyElement->{'join-table'})) { + } elseif (isset($manyToManyElement->{'join-table'})) { if (isset($manyToManyElement['inversed-by'])) { $mapping['inversedBy'] = (string) $manyToManyElement['inversed-by']; } $joinTableElement = $manyToManyElement->{'join-table'}; - $joinTable = [ - 'name' => (string) $joinTableElement['name'] + $joinTable = [ + 'name' => (string) $joinTableElement['name'], ]; if (isset($joinTableElement['schema'])) { @@ -554,13 +562,14 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) ? (string) $orderByField['direction'] : Criteria::ASC; } + $mapping['orderBy'] = $orderBy; } if (isset($manyToManyElement['index-by'])) { $mapping['indexBy'] = (string) $manyToManyElement['index-by']; - } else if (isset($manyToManyElement->{'index-by'})) { - throw new \InvalidArgumentException(" is not a valid tag"); + } elseif (isset($manyToManyElement->{'index-by'})) { + throw new InvalidArgumentException(' is not a valid tag'); } // Evaluate second level cache @@ -577,7 +586,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) foreach ($xmlRoot->{'attribute-overrides'}->{'attribute-override'} as $overrideElement) { $fieldName = (string) $overrideElement['name']; foreach ($overrideElement->field as $field) { - $mapping = $this->columnToArray($field); + $mapping = $this->columnToArray($field); $mapping['fieldName'] = $fieldName; $metadata->setAttributeOverride($fieldName, $mapping); } @@ -587,8 +596,8 @@ 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']; + $override = []; // Check for join-columns if (isset($overrideElement->{'join-columns'})) { @@ -596,17 +605,18 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) foreach ($overrideElement->{'join-columns'}->{'join-column'} as $joinColumnElement) { $joinColumns[] = $this->joinColumnToArray($joinColumnElement); } + $override['joinColumns'] = $joinColumns; } // Check for join-table if ($overrideElement->{'join-table'}) { - $joinTable = null; - $joinTableElement = $overrideElement->{'join-table'}; + $joinTable = null; + $joinTableElement = $overrideElement->{'join-table'}; $joinTable = [ 'name' => (string) $joinTableElement['name'], - 'schema' => (string) $joinTableElement['schema'] + 'schema' => (string) $joinTableElement['schema'], ]; if (isset($joinTableElement->{'join-columns'})) { @@ -657,8 +667,8 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } foreach ($listenerElement as $callbackElement) { - $eventName = (string) $callbackElement['type']; - $methodName = (string) $callbackElement['method']; + $eventName = (string) $callbackElement['type']; + $methodName = (string) $callbackElement['method']; $metadata->addEntityListener($eventName, $className, $methodName); } @@ -687,7 +697,7 @@ private function _parseOptions(SimpleXMLElement $options) $attributes = $option->attributes(); if (isset($attributes->name)) { - $nameAttribute = (string) $attributes->name; + $nameAttribute = (string) $attributes->name; $array[$nameAttribute] = in_array($nameAttribute, ['unsigned', 'fixed']) ? $this->evaluateBoolean($value) : $value; @@ -720,7 +730,7 @@ private function joinColumnToArray(SimpleXMLElement $joinColumnElement) { $joinColumn = [ 'name' => (string) $joinColumnElement['name'], - 'referencedColumnName' => (string) $joinColumnElement['referenced-column-name'] + 'referencedColumnName' => (string) $joinColumnElement['referenced-column-name'], ]; if (isset($joinColumnElement['unique'])) { @@ -813,8 +823,6 @@ private function columnToArray(SimpleXMLElement $fieldMapping) /** * Parse / Normalize the cache configuration * - * @param SimpleXMLElement $cacheMapping - * * @return mixed[] * * @psalm-return array{usage: mixed, region: string|null} @@ -825,7 +833,7 @@ private function cacheToArray(SimpleXMLElement $cacheMapping) $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)); + throw new InvalidArgumentException(sprintf('Invalid cache usage "%s"', $usage)); } if ($usage) { @@ -873,17 +881,17 @@ protected function loadMappingFile($file) if (isset($xmlElement->entity)) { foreach ($xmlElement->entity as $entityElement) { - $entityName = (string) $entityElement['name']; + $entityName = (string) $entityElement['name']; $result[$entityName] = $entityElement; } - } else if (isset($xmlElement->{'mapped-superclass'})) { + } elseif (isset($xmlElement->{'mapped-superclass'})) { foreach ($xmlElement->{'mapped-superclass'} as $mappedSuperClass) { - $className = (string) $mappedSuperClass['name']; + $className = (string) $mappedSuperClass['name']; $result[$className] = $mappedSuperClass; } - } else if (isset($xmlElement->embeddable)) { + } elseif (isset($xmlElement->embeddable)) { foreach ($xmlElement->embeddable as $embeddableElement) { - $embeddableName = (string) $embeddableElement['name']; + $embeddableName = (string) $embeddableElement['name']; $result[$embeddableName] = $embeddableElement; } } @@ -900,6 +908,6 @@ protected function evaluateBoolean($element) { $flag = (string) $element; - return ($flag == "true" || $flag == "1"); + return $flag === 'true' || $flag === '1'; } } diff --git a/lib/Doctrine/ORM/Mapping/Driver/YamlDriver.php b/lib/Doctrine/ORM/Mapping/Driver/YamlDriver.php index 4061846710e..89af90a1031 100644 --- a/lib/Doctrine/ORM/Mapping/Driver/YamlDriver.php +++ b/lib/Doctrine/ORM/Mapping/Driver/YamlDriver.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan H. Wage - * @author Roman Borschel - * * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement */ class YamlDriver extends FileDriver { - const DEFAULT_FILE_EXTENSION = '.dcm.yml'; + public const DEFAULT_FILE_EXTENSION = '.dcm.yml'; /** * {@inheritDoc} @@ -61,22 +71,23 @@ public function __construct($locator, $fileExtension = self::DEFAULT_FILE_EXTENS */ public function loadMetadataForClass($className, ClassMetadata $metadata) { - /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadataInfo */ + /** @var ClassMetadataInfo $metadata */ $element = $this->getElement($className); - if ($element['type'] == 'entity') { + if ($element['type'] === 'entity') { if (isset($element['repositoryClass'])) { $metadata->setCustomRepositoryClass($element['repositoryClass']); } - if (isset($element['readOnly']) && $element['readOnly'] == true) { + + if (isset($element['readOnly']) && $element['readOnly'] === true) { $metadata->markReadOnly(); } - } else if ($element['type'] == 'mappedSuperclass') { + } elseif ($element['type'] === 'mappedSuperclass') { $metadata->setCustomRepositoryClass( $element['repositoryClass'] ?? null ); $metadata->isMappedSuperclass = true; - } else if ($element['type'] == 'embeddable') { + } elseif ($element['type'] === 'embeddable') { $metadata->isEmbeddedClass = true; } else { throw MappingException::classIsNotAValidEntityOrMappedSuperClass($className); @@ -107,7 +118,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $queryMapping = ['query' => $queryMapping]; } - if ( ! isset($queryMapping['name'])) { + if (! isset($queryMapping['name'])) { $queryMapping['name'] = $name; } @@ -118,9 +129,10 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Evaluate named native queries if (isset($element['namedNativeQueries'])) { foreach ($element['namedNativeQueries'] as $name => $mappingElement) { - if (!isset($mappingElement['name'])) { + if (! isset($mappingElement['name'])) { $mappingElement['name'] = $name; } + $metadata->addNamedNativeQuery( [ 'name' => $mappingElement['name'], @@ -135,7 +147,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Evaluate sql result set mappings if (isset($element['sqlResultSetMappings'])) { foreach ($element['sqlResultSetMappings'] as $name => $resultSetMapping) { - if (!isset($resultSetMapping['name'])) { + if (! isset($resultSetMapping['name'])) { $resultSetMapping['name'] = $name; } @@ -162,7 +174,6 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } } - if (isset($resultSetMapping['columnResult'])) { foreach ($resultSetMapping['columnResult'] as $columnResultAnnot) { $columns[] = [ @@ -175,7 +186,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) [ 'name' => $resultSetMapping['name'], 'entities' => $entities, - 'columns' => $columns + 'columns' => $columns, ] ); } @@ -184,7 +195,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) if (isset($element['inheritanceType'])) { $metadata->setInheritanceType(constant('Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_' . strtoupper($element['inheritanceType']))); - if ($metadata->inheritanceType != Metadata::INHERITANCE_TYPE_NONE) { + if ($metadata->inheritanceType !== Metadata::INHERITANCE_TYPE_NONE) { // Evaluate discriminatorColumn if (isset($element['discriminatorColumn'])) { $discrColumn = $element['discriminatorColumn']; @@ -193,7 +204,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) '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 + 'columnDefinition' => isset($discrColumn['columnDefinition']) ? (string) $discrColumn['columnDefinition'] : null, ] ); } else { @@ -207,7 +218,6 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } } - // Evaluate changeTrackingPolicy if (isset($element['changeTrackingPolicy'])) { $metadata->setChangeTrackingPolicy(constant('Doctrine\ORM\Mapping\ClassMetadata::CHANGETRACKING_' @@ -217,7 +227,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Evaluate indexes if (isset($element['indexes'])) { foreach ($element['indexes'] as $name => $indexYml) { - if ( ! isset($indexYml['name'])) { + if (! isset($indexYml['name'])) { $indexYml['name'] = $name; } @@ -246,7 +256,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Evaluate uniqueConstraints if (isset($element['uniqueConstraints'])) { foreach ($element['uniqueConstraints'] as $name => $uniqueYml) { - if ( ! isset($uniqueYml['name'])) { + if (! isset($uniqueYml['name'])) { $uniqueYml['name'] = $name; } @@ -272,14 +282,14 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) if (isset($element['id'])) { // Evaluate identifier settings foreach ($element['id'] as $name => $idElement) { - if (isset($idElement['associationKey']) && $idElement['associationKey'] == true) { + if (isset($idElement['associationKey']) && $idElement['associationKey'] === true) { $associationIds[$name] = true; continue; } $mapping = [ 'id' => true, - 'fieldName' => $name + 'fieldName' => $name, ]; if (isset($idElement['type'])) { @@ -308,17 +318,18 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $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'])) { + } elseif (isset($idElement['customIdGenerator'])) { $customGenerator = $idElement['customIdGenerator']; $metadata->setCustomGeneratorDefinition( [ - 'class' => (string) $customGenerator['class'] + 'class' => (string) $customGenerator['class'], ] ); - } else if (isset($idElement['tableGenerator'])) { + } elseif (isset($idElement['tableGenerator'])) { throw MappingException::tableIdGeneratorNotImplemented($className); } } @@ -327,7 +338,6 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Evaluate fields if (isset($element['fields'])) { foreach ($element['fields'] as $name => $fieldMapping) { - $mapping = $this->columnToArray($name, $fieldMapping); if (isset($fieldMapping['id'])) { @@ -363,7 +373,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) foreach ($element['oneToOne'] as $name => $oneToOneElement) { $mapping = [ 'fieldName' => $name, - 'targetEntity' => $oneToOneElement['targetEntity'] + 'targetEntity' => $oneToOneElement['targetEntity'], ]; if (isset($associationIds[$mapping['fieldName']])) { @@ -385,9 +395,9 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) if (isset($oneToOneElement['joinColumn'])) { $joinColumns[] = $this->joinColumnToArray($oneToOneElement['joinColumn']); - } else if (isset($oneToOneElement['joinColumns'])) { + } elseif (isset($oneToOneElement['joinColumns'])) { foreach ($oneToOneElement['joinColumns'] as $joinColumnName => $joinColumnElement) { - if ( ! isset($joinColumnElement['name'])) { + if (! isset($joinColumnElement['name'])) { $joinColumnElement['name'] = $joinColumnName; } @@ -421,7 +431,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $mapping = [ 'fieldName' => $name, 'targetEntity' => $oneToManyElement['targetEntity'], - 'mappedBy' => $oneToManyElement['mappedBy'] + 'mappedBy' => $oneToManyElement['mappedBy'], ]; if (isset($oneToManyElement['fetch'])) { @@ -444,7 +454,6 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $mapping['indexBy'] = $oneToManyElement['indexBy']; } - // Evaluate second level cache if (isset($oneToManyElement['cache'])) { $mapping['cache'] = $metadata->getAssociationCacheDefaults($mapping['fieldName'], $this->cacheToArray($oneToManyElement['cache'])); @@ -459,7 +468,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) foreach ($element['manyToOne'] as $name => $manyToOneElement) { $mapping = [ 'fieldName' => $name, - 'targetEntity' => $manyToOneElement['targetEntity'] + 'targetEntity' => $manyToOneElement['targetEntity'], ]; if (isset($associationIds[$mapping['fieldName']])) { @@ -478,9 +487,9 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) if (isset($manyToOneElement['joinColumn'])) { $joinColumns[] = $this->joinColumnToArray($manyToOneElement['joinColumn']); - } else if (isset($manyToOneElement['joinColumns'])) { + } elseif (isset($manyToOneElement['joinColumns'])) { foreach ($manyToOneElement['joinColumns'] as $joinColumnName => $joinColumnElement) { - if ( ! isset($joinColumnElement['name'])) { + if (! isset($joinColumnElement['name'])) { $joinColumnElement['name'] = $joinColumnName; } @@ -508,7 +517,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) foreach ($element['manyToMany'] as $name => $manyToManyElement) { $mapping = [ 'fieldName' => $name, - 'targetEntity' => $manyToManyElement['targetEntity'] + 'targetEntity' => $manyToManyElement['targetEntity'], ]; if (isset($manyToManyElement['fetch'])) { @@ -517,11 +526,10 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) if (isset($manyToManyElement['mappedBy'])) { $mapping['mappedBy'] = $manyToManyElement['mappedBy']; - } else if (isset($manyToManyElement['joinTable'])) { - + } elseif (isset($manyToManyElement['joinTable'])) { $joinTableElement = $manyToManyElement['joinTable']; - $joinTable = [ - 'name' => $joinTableElement['name'] + $joinTable = [ + 'name' => $joinTableElement['name'], ]; if (isset($joinTableElement['schema'])) { @@ -530,18 +538,20 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) if (isset($joinTableElement['joinColumns'])) { foreach ($joinTableElement['joinColumns'] as $joinColumnName => $joinColumnElement) { - if ( ! isset($joinColumnElement['name'])) { + 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'])) { + if (! isset($joinColumnElement['name'])) { $joinColumnElement['name'] = $joinColumnName; } + $joinTable['inverseJoinColumns'][] = $this->joinColumnToArray($joinColumnElement); } } @@ -580,28 +590,28 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Evaluate associationOverride if (isset($element['associationOverride']) && is_array($element['associationOverride'])) { - foreach ($element['associationOverride'] as $fieldName => $associationOverrideElement) { - $override = []; + $override = []; // Check for joinColumn if (isset($associationOverrideElement['joinColumn'])) { $joinColumns = []; foreach ($associationOverrideElement['joinColumn'] as $name => $joinColumnElement) { - if ( ! isset($joinColumnElement['name'])) { + 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'] + $joinTableElement = $associationOverrideElement['joinTable']; + $joinTable = [ + 'name' => $joinTableElement['name'], ]; if (isset($joinTableElement['schema'])) { @@ -609,7 +619,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } foreach ($joinTableElement['joinColumns'] as $name => $joinColumnElement) { - if ( ! isset($joinColumnElement['name'])) { + if (! isset($joinColumnElement['name'])) { $joinColumnElement['name'] = $name; } @@ -617,7 +627,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } foreach ($joinTableElement['inverseJoinColumns'] as $name => $joinColumnElement) { - if ( ! isset($joinColumnElement['name'])) { + if (! isset($joinColumnElement['name'])) { $joinColumnElement['name'] = $name; } @@ -643,7 +653,6 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // 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); @@ -754,9 +763,7 @@ private function joinColumnToArray($joinColumnElement) */ private function columnToArray($fieldName, $column) { - $mapping = [ - 'fieldName' => $fieldName - ]; + $mapping = ['fieldName' => $fieldName]; if (isset($column['type'])) { $params = explode('(', $column['type']); @@ -765,7 +772,7 @@ private function columnToArray($fieldName, $column) $mapping['type'] = $column['type']; if (isset($params[1])) { - $column['length'] = (integer) substr($params[1], 0, strlen($params[1]) - 1); + $column['length'] = (int) substr($params[1], 0, strlen($params[1]) - 1); } } @@ -815,8 +822,8 @@ private function columnToArray($fieldName, $column) * * @return mixed[] * - * @psalm-param array{usage: mixed, region: null|string} $cacheMapping - * @psalm-return array{usage: mixed, region: null|string} + * @psalm-param array{usage: mixed, region: (string|null)} $cacheMapping + * @psalm-return array{usage: mixed, region: (string|null)} */ private function cacheToArray($cacheMapping) { @@ -824,7 +831,7 @@ private function cacheToArray($cacheMapping) $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)); + throw new InvalidArgumentException(sprintf('Invalid cache usage "%s"', $usage)); } if ($usage) { diff --git a/lib/Doctrine/ORM/Mapping/Embeddable.php b/lib/Doctrine/ORM/Mapping/Embeddable.php index f14bfac82a6..49489c431ed 100644 --- a/lib/Doctrine/ORM/Mapping/Embeddable.php +++ b/lib/Doctrine/ORM/Mapping/Embeddable.php @@ -1,4 +1,5 @@ */ interface EntityListenerResolver { diff --git a/lib/Doctrine/ORM/Mapping/EntityListeners.php b/lib/Doctrine/ORM/Mapping/EntityListeners.php index ae6c9126bd7..8a795378ca7 100644 --- a/lib/Doctrine/ORM/Mapping/EntityListeners.php +++ b/lib/Doctrine/ORM/Mapping/EntityListeners.php @@ -24,9 +24,6 @@ * 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") */ diff --git a/lib/Doctrine/ORM/Mapping/EntityResult.php b/lib/Doctrine/ORM/Mapping/EntityResult.php index d8b05730ae5..371fe07ab05 100644 --- a/lib/Doctrine/ORM/Mapping/EntityResult.php +++ b/lib/Doctrine/ORM/Mapping/EntityResult.php @@ -1,4 +1,5 @@ - * @since 2.3 - * * @Annotation * @Target("ANNOTATION") */ diff --git a/lib/Doctrine/ORM/Mapping/FieldResult.php b/lib/Doctrine/ORM/Mapping/FieldResult.php index 5e8aa0cd3e0..d838a941437 100644 --- a/lib/Doctrine/ORM/Mapping/FieldResult.php +++ b/lib/Doctrine/ORM/Mapping/FieldResult.php @@ -1,4 +1,5 @@ - * @since 2.3 - * * @Annotation * @Target("ANNOTATION") */ diff --git a/lib/Doctrine/ORM/Mapping/GeneratedValue.php b/lib/Doctrine/ORM/Mapping/GeneratedValue.php index 27c03d4bee7..e0f8c88357d 100644 --- a/lib/Doctrine/ORM/Mapping/GeneratedValue.php +++ b/lib/Doctrine/ORM/Mapping/GeneratedValue.php @@ -1,4 +1,5 @@ - */ + /** @var array */ public $columns; - /** - * @var array - */ + /** @var array */ public $flags; - /** - * @var array - */ + /** @var array */ public $options; } diff --git a/lib/Doctrine/ORM/Mapping/InheritanceType.php b/lib/Doctrine/ORM/Mapping/InheritanceType.php index de803369a30..6a29ad765d3 100644 --- a/lib/Doctrine/ORM/Mapping/InheritanceType.php +++ b/lib/Doctrine/ORM/Mapping/InheritanceType.php @@ -1,4 +1,5 @@ - */ + /** @var array<\Doctrine\ORM\Mapping\JoinColumn> */ public $value; } diff --git a/lib/Doctrine/ORM/Mapping/JoinTable.php b/lib/Doctrine/ORM/Mapping/JoinTable.php index 879316a2874..657467a3e72 100644 --- a/lib/Doctrine/ORM/Mapping/JoinTable.php +++ b/lib/Doctrine/ORM/Mapping/JoinTable.php @@ -1,4 +1,5 @@ - */ + /** @var array<\Doctrine\ORM\Mapping\JoinColumn> */ public $joinColumns = []; - /** - * @var array<\Doctrine\ORM\Mapping\JoinColumn> - */ + /** @var array<\Doctrine\ORM\Mapping\JoinColumn> */ public $inverseJoinColumns = []; } diff --git a/lib/Doctrine/ORM/Mapping/ManyToMany.php b/lib/Doctrine/ORM/Mapping/ManyToMany.php index ca2f53c9eea..a5e8f5956a6 100644 --- a/lib/Doctrine/ORM/Mapping/ManyToMany.php +++ b/lib/Doctrine/ORM/Mapping/ManyToMany.php @@ -1,4 +1,5 @@ - */ + /** @var array */ public $cascade; /** * The fetching strategy to use for the association. * * @var string - * * @Enum({"LAZY", "EAGER", "EXTRA_LAZY"}) */ public $fetch = 'LAZY'; - /** - * @var boolean - */ + /** @var bool */ public $orphanRemoval = false; - /** - * @var string - */ + /** @var string */ public $indexBy; } diff --git a/lib/Doctrine/ORM/Mapping/ManyToOne.php b/lib/Doctrine/ORM/Mapping/ManyToOne.php index d3414e6a956..15023bf57ab 100644 --- a/lib/Doctrine/ORM/Mapping/ManyToOne.php +++ b/lib/Doctrine/ORM/Mapping/ManyToOne.php @@ -1,4 +1,5 @@ - */ + /** @var array */ public $cascade; /** * The fetching strategy to use for the association. * * @var string - * * @Enum({"LAZY", "EAGER", "EXTRA_LAZY"}) */ public $fetch = 'LAZY'; - /** - * @var string - */ + /** @var string */ public $inversedBy; } diff --git a/lib/Doctrine/ORM/Mapping/MappedSuperclass.php b/lib/Doctrine/ORM/Mapping/MappedSuperclass.php index 74588107d89..874ea239341 100644 --- a/lib/Doctrine/ORM/Mapping/MappedSuperclass.php +++ b/lib/Doctrine/ORM/Mapping/MappedSuperclass.php @@ -1,4 +1,5 @@ - * @since 2.3 - * * @Annotation * @Target("CLASS") */ diff --git a/lib/Doctrine/ORM/Mapping/NamedNativeQuery.php b/lib/Doctrine/ORM/Mapping/NamedNativeQuery.php index f336c99171d..2236af09159 100644 --- a/lib/Doctrine/ORM/Mapping/NamedNativeQuery.php +++ b/lib/Doctrine/ORM/Mapping/NamedNativeQuery.php @@ -1,4 +1,5 @@ - * @since 2.3 - * * @Annotation * @Target("ANNOTATION") */ @@ -41,7 +39,7 @@ final class NamedNativeQuery implements Annotation /** * The SQL query string. * - * @var string + * @var string */ public $query; @@ -54,7 +52,7 @@ final class NamedNativeQuery implements Annotation /** * 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 index 5fce0727b28..bd7488b09c6 100644 --- a/lib/Doctrine/ORM/Mapping/NamedQueries.php +++ b/lib/Doctrine/ORM/Mapping/NamedQueries.php @@ -1,4 +1,5 @@ - */ + /** @var array<\Doctrine\ORM\Mapping\NamedQuery> */ public $value; } diff --git a/lib/Doctrine/ORM/Mapping/NamedQuery.php b/lib/Doctrine/ORM/Mapping/NamedQuery.php index c4e6cd528fb..59ce305c868 100644 --- a/lib/Doctrine/ORM/Mapping/NamedQuery.php +++ b/lib/Doctrine/ORM/Mapping/NamedQuery.php @@ -1,4 +1,5 @@ */ interface NamingStrategy { @@ -52,10 +49,10 @@ function propertyToColumnName($propertyName, $className = null); /** * Returns a column name for an embedded property. * - * @param string $propertyName - * @param string $embeddedColumnName - * @param string $className - * @param string $embeddedClassName + * @param string $propertyName + * @param string $embeddedColumnName + * @param string $className + * @param string $embeddedClassName * * @return string */ diff --git a/lib/Doctrine/ORM/Mapping/OneToMany.php b/lib/Doctrine/ORM/Mapping/OneToMany.php index 4b2465718e1..9d15a76a975 100644 --- a/lib/Doctrine/ORM/Mapping/OneToMany.php +++ b/lib/Doctrine/ORM/Mapping/OneToMany.php @@ -1,4 +1,5 @@ - */ + /** @var array */ public $cascade; /** * The fetching strategy to use for the association. * * @var string - * * @Enum({"LAZY", "EAGER", "EXTRA_LAZY"}) */ public $fetch = 'LAZY'; - /** - * @var boolean - */ + /** @var bool */ public $orphanRemoval = false; - /** - * @var string - */ + /** @var string */ public $indexBy; } diff --git a/lib/Doctrine/ORM/Mapping/OneToOne.php b/lib/Doctrine/ORM/Mapping/OneToOne.php index b2ab81f88d9..8dc5070e000 100644 --- a/lib/Doctrine/ORM/Mapping/OneToOne.php +++ b/lib/Doctrine/ORM/Mapping/OneToOne.php @@ -1,4 +1,5 @@ - */ + /** @var array */ public $cascade; /** * The fetching strategy to use for the association. * * @var string - * * @Enum({"LAZY", "EAGER", "EXTRA_LAZY"}) */ public $fetch = 'LAZY'; - /** - * @var boolean - */ + /** @var bool */ public $orphanRemoval = false; } diff --git a/lib/Doctrine/ORM/Mapping/OrderBy.php b/lib/Doctrine/ORM/Mapping/OrderBy.php index ad1b7a8f714..457de6966e7 100644 --- a/lib/Doctrine/ORM/Mapping/OrderBy.php +++ b/lib/Doctrine/ORM/Mapping/OrderBy.php @@ -1,4 +1,5 @@ - */ + /** @var array */ public $value; } diff --git a/lib/Doctrine/ORM/Mapping/PostLoad.php b/lib/Doctrine/ORM/Mapping/PostLoad.php index 2f8e9932e35..ded549d19d4 100644 --- a/lib/Doctrine/ORM/Mapping/PostLoad.php +++ b/lib/Doctrine/ORM/Mapping/PostLoad.php @@ -1,4 +1,5 @@ */ interface QuoteStrategy { /** * Gets the (possibly quoted) column name for safe use in an SQL statement. * - * @param string $fieldName - * @param ClassMetadata $class - * @param AbstractPlatform $platform + * @param string $fieldName * * @return string */ @@ -43,9 +39,6 @@ function getColumnName($fieldName, ClassMetadata $class, AbstractPlatform $platf /** * 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); @@ -53,9 +46,7 @@ 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 + * @param array $definition * * @return string */ @@ -64,9 +55,7 @@ function getSequenceName(array $definition, ClassMetadata $class, AbstractPlatfo /** * Gets the (possibly quoted) name of the join table. * - * @param array $association - * @param ClassMetadata $class - * @param AbstractPlatform $platform + * @param array $association * * @return string */ @@ -75,9 +64,7 @@ function getJoinTableName(array $association, ClassMetadata $class, AbstractPlat /** * Gets the (possibly quoted) join column name. * - * @param array $joinColumn - * @param ClassMetadata $class - * @param AbstractPlatform $platform + * @param array $joinColumn * * @return string */ @@ -86,9 +73,7 @@ function getJoinColumnName(array $joinColumn, ClassMetadata $class, AbstractPlat /** * Gets the (possibly quoted) join column name. * - * @param array $joinColumn - * @param ClassMetadata $class - * @param AbstractPlatform $platform + * @param array $joinColumn * * @return string */ @@ -97,9 +82,6 @@ function getReferencedJoinColumnName(array $joinColumn, ClassMetadata $class, Ab /** * 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); @@ -107,13 +89,10 @@ function getIdentifierColumnNames(ClassMetadata $class, AbstractPlatform $platfo /** * Gets the column alias. * - * @param string $columnName - * @param integer $counter - * @param AbstractPlatform $platform - * @param ClassMetadata|null $class + * @param string $columnName + * @param int $counter * * @return string */ - function getColumnAlias($columnName, $counter, AbstractPlatform $platform, ClassMetadata $class = null); - + 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 index dff9e19eb39..da28defce3f 100644 --- a/lib/Doctrine/ORM/Mapping/Reflection/ReflectionPropertiesGetter.php +++ b/lib/Doctrine/ORM/Mapping/Reflection/ReflectionPropertiesGetter.php @@ -1,4 +1,5 @@ */ final class ReflectionPropertiesGetter { - /** - * @var ReflectionProperty[][] indexed by class name and property internal name - */ + /** @var ReflectionProperty[][] indexed by class name and property internal name */ private $properties = []; - /** - * @var ReflectionService - */ + /** @var ReflectionService */ private $reflectionService; - /** - * @param ReflectionService $reflectionService - */ public function __construct(ReflectionService $reflectionService) { $this->reflectionService = $reflectionService; @@ -84,7 +82,7 @@ public function getProperties($className) * * @psalm-return list */ - private function getHierarchyClasses($className) : array + private function getHierarchyClasses($className): array { $classes = []; $parentClassName = $className; @@ -102,14 +100,13 @@ private function getHierarchyClasses($className) : array } // phpcs:disable SlevomatCodingStandard.Classes.UnusedPrivateElements.UnusedMethod + /** - * @param ReflectionClass $reflectionClass - * * @return ReflectionProperty[] * * @psalm-return array */ - private function getClassProperties(ReflectionClass $reflectionClass) : array + private function getClassProperties(ReflectionClass $reflectionClass): array { // phpcs:enable SlevomatCodingStandard.Classes.UnusedPrivateElements.UnusedMethod $properties = $reflectionClass->getProperties(); @@ -127,8 +124,6 @@ private function getClassProperties(ReflectionClass $reflectionClass) : array } /** - * @param ReflectionProperty $reflectionProperty - * * @return bool */ private function isInstanceProperty(ReflectionProperty $reflectionProperty) @@ -137,9 +132,7 @@ private function isInstanceProperty(ReflectionProperty $reflectionProperty) } /** - * @param ReflectionProperty $property - * - * @return null|ReflectionProperty + * @return ReflectionProperty|null */ private function getAccessibleProperty(ReflectionProperty $property) { @@ -150,8 +143,6 @@ private function getAccessibleProperty(ReflectionProperty $property) } /** - * @param ReflectionProperty $property - * * @return string */ private function getLogicalName(ReflectionProperty $property) diff --git a/lib/Doctrine/ORM/Mapping/ReflectionEmbeddedProperty.php b/lib/Doctrine/ORM/Mapping/ReflectionEmbeddedProperty.php index b224fff4eb5..49a2ab2b064 100644 --- a/lib/Doctrine/ORM/Mapping/ReflectionEmbeddedProperty.php +++ b/lib/Doctrine/ORM/Mapping/ReflectionEmbeddedProperty.php @@ -1,4 +1,5 @@ parentProperty = $parentProperty; - $this->childProperty = $childProperty; - $this->embeddedClass = (string) $embeddedClass; + $this->parentProperty = $parentProperty; + $this->childProperty = $childProperty; + $this->embeddedClass = (string) $embeddedClass; parent::__construct($childProperty->getDeclaringClass()->getName(), $childProperty->getName()); } @@ -74,7 +65,7 @@ public function getValue($object = null) { $embeddedObject = $this->parentProperty->getValue($object); - if (null === $embeddedObject) { + if ($embeddedObject === null) { return null; } @@ -88,7 +79,7 @@ public function setValue($object, $value = null) { $embeddedObject = $this->parentProperty->getValue($object); - if (null === $embeddedObject) { + if ($embeddedObject === null) { $this->instantiator = $this->instantiator ?: new Instantiator(); $embeddedObject = $this->instantiator->instantiate($this->embeddedClass); diff --git a/lib/Doctrine/ORM/Mapping/SequenceGenerator.php b/lib/Doctrine/ORM/Mapping/SequenceGenerator.php index ba1c45b6425..a2c9fde4aab 100644 --- a/lib/Doctrine/ORM/Mapping/SequenceGenerator.php +++ b/lib/Doctrine/ORM/Mapping/SequenceGenerator.php @@ -1,4 +1,5 @@ - * @since 2.3 - * * @Annotation * @Target("ANNOTATION") */ diff --git a/lib/Doctrine/ORM/Mapping/SqlResultSetMappings.php b/lib/Doctrine/ORM/Mapping/SqlResultSetMappings.php index 0b74f2d9598..477effcb9ab 100644 --- a/lib/Doctrine/ORM/Mapping/SqlResultSetMappings.php +++ b/lib/Doctrine/ORM/Mapping/SqlResultSetMappings.php @@ -1,4 +1,5 @@ - * @since 2.3 - * * @Annotation * @Target("CLASS") */ diff --git a/lib/Doctrine/ORM/Mapping/Table.php b/lib/Doctrine/ORM/Mapping/Table.php index 6ed703750be..76d8f3ade3e 100644 --- a/lib/Doctrine/ORM/Mapping/Table.php +++ b/lib/Doctrine/ORM/Mapping/Table.php @@ -1,4 +1,5 @@ - */ + /** @var array<\Doctrine\ORM\Mapping\Index> */ public $indexes; - /** - * @var array<\Doctrine\ORM\Mapping\UniqueConstraint> - */ + /** @var array<\Doctrine\ORM\Mapping\UniqueConstraint> */ public $uniqueConstraints; - /** - * @var array - */ + /** @var array */ public $options = []; } diff --git a/lib/Doctrine/ORM/Mapping/UnderscoreNamingStrategy.php b/lib/Doctrine/ORM/Mapping/UnderscoreNamingStrategy.php index 177b390f4fe..2abdb5a0c44 100644 --- a/lib/Doctrine/ORM/Mapping/UnderscoreNamingStrategy.php +++ b/lib/Doctrine/ORM/Mapping/UnderscoreNamingStrategy.php @@ -20,9 +20,6 @@ namespace Doctrine\ORM\Mapping; -use const CASE_LOWER; -use const CASE_UPPER; -use const E_USER_DEPRECATED; use function preg_replace; use function strpos; use function strrpos; @@ -31,23 +28,22 @@ use function substr; use function trigger_error; +use const CASE_LOWER; +use const CASE_UPPER; +use const E_USER_DEPRECATED; + /** * Naming strategy implementing the underscore naming convention. * Converts 'MyEntity' to 'my_entity' or 'MY_ENTITY'. * - * * @link www.doctrine-project.org - * @since 2.3 - * @author Fabio B. Silva */ class UnderscoreNamingStrategy implements NamingStrategy { private const DEFAULT_PATTERN = '/(?<=[a-z])([A-Z])/'; private const NUMBER_AWARE_PATTERN = '/(?<=[a-z0-9])([A-Z])/'; - /** - * @var integer - */ + /** @var int */ private $case; /** @var string */ @@ -72,7 +68,7 @@ public function __construct($case = CASE_LOWER, bool $numberAware = false) } /** - * @return integer CASE_LOWER | CASE_UPPER + * @return int CASE_LOWER | CASE_UPPER */ public function getCase() { @@ -83,7 +79,7 @@ public function getCase() * Sets string case CASE_LOWER | CASE_UPPER. * Alphabetic characters converted to lowercase or uppercase. * - * @param integer $case + * @param int $case * * @return void */ @@ -117,7 +113,7 @@ public function propertyToColumnName($propertyName, $className = null) */ public function embeddedFieldToColumnName($propertyName, $embeddedColumnName, $className = null, $embeddedClassName = null) { - return $this->underscore($propertyName).'_'.$embeddedColumnName; + return $this->underscore($propertyName) . '_' . $embeddedColumnName; } /** @@ -153,7 +149,7 @@ public function joinKeyColumnName($entityName, $referencedColumnName = null) ($referencedColumnName ?: $this->referenceColumnName()); } - private function underscore(string $string) : string + private function underscore(string $string): string { $string = preg_replace($this->pattern, '_$1', $string); diff --git a/lib/Doctrine/ORM/Mapping/UniqueConstraint.php b/lib/Doctrine/ORM/Mapping/UniqueConstraint.php index f117d1873e8..3be8c52b5ff 100644 --- a/lib/Doctrine/ORM/Mapping/UniqueConstraint.php +++ b/lib/Doctrine/ORM/Mapping/UniqueConstraint.php @@ -1,4 +1,5 @@ - */ + /** @var array */ public $columns; - /** - * @var array - */ + /** @var array */ public $options; } diff --git a/lib/Doctrine/ORM/Mapping/Version.php b/lib/Doctrine/ORM/Mapping/Version.php index a2377027950..be0805758c5 100644 --- a/lib/Doctrine/ORM/Mapping/Version.php +++ b/lib/Doctrine/ORM/Mapping/Version.php @@ -1,4 +1,5 @@ - * @since 2.0 */ final class NativeQuery extends AbstractQuery { - /** - * @var string - */ + /** @var string */ private $_sql; /** @@ -39,7 +40,7 @@ final class NativeQuery extends AbstractQuery * * @return self This query instance. */ - public function setSQL($sql) : self + public function setSQL($sql): self { $this->_sql = $sql; @@ -69,7 +70,7 @@ protected function _doExecute() foreach ($this->getParameters() as $parameter) { $name = $parameter->getName(); $value = $this->processParameterValue($parameter->getValue()); - $type = ($parameter->getValue() === $value) + $type = $parameter->getValue() === $value ? $parameter->getType() : Query\ParameterTypeInferer::inferType($value); @@ -86,7 +87,10 @@ protected function _doExecute() } return $this->_em->getConnection()->executeQuery( - $this->_sql, $parameters, $types, $this->_queryCacheProfile + $this->_sql, + $parameters, + $types, + $this->_queryCacheProfile ); } } diff --git a/lib/Doctrine/ORM/NoResultException.php b/lib/Doctrine/ORM/NoResultException.php index 2cbac8e9d95..72a49910d22 100644 --- a/lib/Doctrine/ORM/NoResultException.php +++ b/lib/Doctrine/ORM/NoResultException.php @@ -1,4 +1,5 @@ - * @since 2.0 */ class ORMException extends Exception { @@ -37,8 +38,8 @@ class ORMException extends Exception */ public static function missingMappingDriverImpl() { - return new self("It's a requirement to specify a Metadata Driver and pass it ". - "to Doctrine\\ORM\\Configuration::setMetadataDriverImpl()."); + return new self("It's a requirement to specify a Metadata Driver and pass it " . + 'to Doctrine\\ORM\\Configuration::setMetadataDriverImpl().'); } /** @@ -70,11 +71,11 @@ public static function namedNativeQueryNotFound($nativeQueryName) public static function entityMissingForeignAssignedId($entity, $relatedEntity) { return new self( - "Entity of type " . get_class($entity) . " has identity through a foreign entity " . get_class($relatedEntity) . ", " . - "however this entity has no identity itself. You have to call EntityManager#persist() on the related entity " . + 'Entity of type ' . get_class($entity) . ' has identity through a foreign entity ' . get_class($relatedEntity) . ', ' . + 'however this entity has no identity itself. You have to call EntityManager#persist() on the related entity ' . "and make sure that an identifier was generated before trying to persist '" . get_class($entity) . "'. In case " . - "of Post Insert ID Generation (such as MySQL Auto-Increment) this means you have to call " . - "EntityManager#flush() between both persist operations." + 'of Post Insert ID Generation (such as MySQL Auto-Increment) this means you have to call ' . + 'EntityManager#flush() between both persist operations.' ); } @@ -86,11 +87,10 @@ public static function entityMissingForeignAssignedId($entity, $relatedEntity) */ public static function entityMissingAssignedIdForField($entity, $field) { - return new self("Entity of type " . get_class($entity) . " is missing an assigned ID for field '" . $field . "'. " . - "The identifier generation strategy for this entity requires the ID field to be populated before ". - "EntityManager#persist() is called. If you want automatically generated identifiers instead " . - "you need to adjust the metadata mapping accordingly." - ); + return new self('Entity of type ' . get_class($entity) . " is missing an assigned ID for field '" . $field . "'. " . + 'The identifier generation strategy for this entity requires the ID field to be populated before ' . + 'EntityManager#persist() is called. If you want automatically generated identifiers instead ' . + 'you need to adjust the metadata mapping accordingly.'); } /** @@ -104,13 +104,12 @@ public static function unrecognizedField($field) } /** - * * @param string $class * @param string $association * @param string $given * @param string $expected * - * @return \Doctrine\ORM\ORMException + * @return ORMException */ public static function unexpectedAssociationValue($class, $association, $given, $expected) { @@ -125,7 +124,7 @@ public static function unexpectedAssociationValue($class, $association, $given, */ public static function invalidOrientation($className, $field) { - return new self("Invalid order by orientation specified for " . $className . "#" . $field); + return new self('Invalid order by orientation specified for ' . $className . '#' . $field); } /** @@ -143,7 +142,7 @@ public static function invalidFlushMode($mode) */ public static function entityManagerClosed() { - return new self("The EntityManager is closed."); + return new self('The EntityManager is closed.'); } /** @@ -161,7 +160,7 @@ public static function invalidHydrationMode($mode) */ public static function mismatchedEventManager() { - return new self("Cannot use different EventManager instances for EntityManager and Connection."); + return new self('Cannot use different EventManager instances for EntityManager and Connection.'); } /** @@ -171,7 +170,7 @@ public static function mismatchedEventManager() */ public static function findByRequiresParameter($methodName) { - return new self("You need to pass a parameter to '".$methodName."'"); + return new self("You need to pass a parameter to '" . $methodName . "'"); } /** @@ -184,8 +183,8 @@ public static function findByRequiresParameter($methodName) public static function invalidFindByCall($entityName, $fieldName, $method) { return new self( - "Entity '".$entityName."' has no field '".$fieldName."'. ". - "You can therefore not call '".$method."' on the entities' repository" + "Entity '" . $entityName . "' has no field '" . $fieldName . "'. " . + "You can therefore not call '" . $method . "' on the entities' repository" ); } @@ -199,8 +198,8 @@ public static function invalidFindByCall($entityName, $fieldName, $method) public static function invalidMagicCall($entityName, $fieldName, $method) { return new self( - "Entity '".$entityName."' has no field '".$fieldName."'. ". - "You can therefore not call '".$method."' on the entities' repository" + "Entity '" . $entityName . "' has no field '" . $fieldName . "'. " . + "You can therefore not call '" . $method . "' on the entities' repository" ); } @@ -213,8 +212,8 @@ public static function invalidMagicCall($entityName, $fieldName, $method) public static function invalidFindByInverseAssociation($entityName, $associationFieldName) { return new self( - "You cannot search for the association field '".$entityName."#".$associationFieldName."', ". - "because it is the inverse side of an association. Find methods only work on owning side associations." + "You cannot search for the association field '" . $entityName . '#' . $associationFieldName . "', " . + 'because it is the inverse side of an association. Find methods only work on owning side associations.' ); } @@ -223,7 +222,7 @@ public static function invalidFindByInverseAssociation($entityName, $association */ public static function invalidResultCacheDriver() { - return new self("Invalid result cache driver; it must implement Doctrine\\Common\\Cache\\Cache."); + return new self('Invalid result cache driver; it must implement Doctrine\\Common\\Cache\\Cache.'); } /** @@ -231,7 +230,7 @@ public static function invalidResultCacheDriver() */ public static function notSupported() { - return new self("This behaviour is (currently) not supported by Doctrine 2"); + return new self('This behaviour is (currently) not supported by Doctrine 2'); } /** @@ -251,8 +250,6 @@ public static function metadataCacheNotConfigured() } /** - * @param \Doctrine\Common\Cache\Cache $cache - * * @return ORMException */ public static function queryCacheUsesNonPersistentCache(CacheDriver $cache) @@ -261,8 +258,6 @@ public static function queryCacheUsesNonPersistentCache(CacheDriver $cache) } /** - * @param \Doctrine\Common\Cache\Cache $cache - * * @return ORMException */ public static function metadataCacheUsesNonPersistentCache(CacheDriver $cache) @@ -316,7 +311,7 @@ public static function missingIdentifierField($className, $fieldName) } /** - * @param string $className + * @param string $className * @param string[] $fieldNames * * @return ORMException diff --git a/lib/Doctrine/ORM/ORMInvalidArgumentException.php b/lib/Doctrine/ORM/ORMInvalidArgumentException.php index 68bb6f91dff..d9be7fc5b34 100644 --- a/lib/Doctrine/ORM/ORMInvalidArgumentException.php +++ b/lib/Doctrine/ORM/ORMInvalidArgumentException.php @@ -1,4 +1,5 @@ */ -class ORMInvalidArgumentException extends \InvalidArgumentException +class ORMInvalidArgumentException extends InvalidArgumentException { /** * @param object $entity * * @return ORMInvalidArgumentException */ - static public function scheduleInsertForManagedEntity($entity) + public static function scheduleInsertForManagedEntity($entity) { - return new self("A managed+dirty entity " . self::objToStr($entity) . " can not be scheduled for insertion."); + return new self('A managed+dirty entity ' . self::objToStr($entity) . ' can not be scheduled for insertion.'); } /** @@ -42,9 +54,9 @@ static public function scheduleInsertForManagedEntity($entity) * * @return ORMInvalidArgumentException */ - static public function scheduleInsertForRemovedEntity($entity) + public static function scheduleInsertForRemovedEntity($entity) { - return new self("Removed entity " . self::objToStr($entity) . " can not be scheduled for insertion."); + return new self('Removed entity ' . self::objToStr($entity) . ' can not be scheduled for insertion.'); } /** @@ -52,9 +64,9 @@ static public function scheduleInsertForRemovedEntity($entity) * * @return ORMInvalidArgumentException */ - static public function scheduleInsertTwice($entity) + public static function scheduleInsertTwice($entity) { - return new self("Entity " . self::objToStr($entity) . " can not be scheduled for insertion twice."); + return new self('Entity ' . self::objToStr($entity) . ' can not be scheduled for insertion twice.'); } /** @@ -63,11 +75,11 @@ static public function scheduleInsertTwice($entity) * * @return ORMInvalidArgumentException */ - static public function entityWithoutIdentity($className, $entity) + public static function entityWithoutIdentity($className, $entity) { return new self( - "The given entity of type '" . $className . "' (".self::objToStr($entity).") has no identity/no " . - "id values set. It cannot be added to the identity map." + "The given entity of type '" . $className . "' (" . self::objToStr($entity) . ') has no identity/no ' . + 'id values set. It cannot be added to the identity map.' ); } @@ -76,21 +88,21 @@ static public function entityWithoutIdentity($className, $entity) * * @return ORMInvalidArgumentException */ - static public function readOnlyRequiresManagedEntity($entity) + public static function readOnlyRequiresManagedEntity($entity) { - return new self("Only managed entities can be marked or checked as read only. But " . self::objToStr($entity) . " is not"); + return new self('Only managed entities can be marked or checked as read only. But ' . self::objToStr($entity) . ' is not'); } /** * @param array[][]|object[][] $newEntitiesWithAssociations non-empty an array - * of [array $associationMapping, object $entity] pairs + * of [array $associationMapping, object $entity] pairs * * @return ORMInvalidArgumentException */ - static public function newEntitiesFoundThroughRelationships($newEntitiesWithAssociations) + public static function newEntitiesFoundThroughRelationships($newEntitiesWithAssociations) { $errorMessages = array_map( - function (array $newEntityWithAssociation) : string { + static function (array $newEntityWithAssociation): string { [$associationMapping, $entity] = $newEntityWithAssociation; return self::newEntityFoundThroughRelationshipMessage($associationMapping, $entity); @@ -98,7 +110,7 @@ function (array $newEntityWithAssociation) : string { $newEntitiesWithAssociations ); - if (1 === count($errorMessages)) { + if (count($errorMessages) === 1) { return new self(reset($errorMessages)); } @@ -115,7 +127,7 @@ function (array $newEntityWithAssociation) : string { * * @return ORMInvalidArgumentException */ - static public function newEntityFoundThroughRelationship(array $associationMapping, $entry) + public static function newEntityFoundThroughRelationship(array $associationMapping, $entry) { return new self(self::newEntityFoundThroughRelationshipMessage($associationMapping, $entry)); } @@ -126,11 +138,11 @@ static public function newEntityFoundThroughRelationship(array $associationMappi * * @return ORMInvalidArgumentException */ - static public function detachedEntityFoundThroughRelationship(array $assoc, $entry) + public static function detachedEntityFoundThroughRelationship(array $assoc, $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."); + 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.'); } /** @@ -138,10 +150,10 @@ static public function detachedEntityFoundThroughRelationship(array $assoc, $ent * * @return ORMInvalidArgumentException */ - static public function entityNotManaged($entity) + public static function entityNotManaged($entity) { - return new self("Entity " . self::objToStr($entity) . " is not managed. An entity is managed if its fetched " . - "from the database or registered as new through EntityManager#persist"); + return new self('Entity ' . self::objToStr($entity) . ' is not managed. An entity is managed if its fetched ' . + 'from the database or registered as new through EntityManager#persist'); } /** @@ -150,9 +162,9 @@ static public function entityNotManaged($entity) * * @return ORMInvalidArgumentException */ - static public function entityHasNoIdentity($entity, $operation) + public static function entityHasNoIdentity($entity, $operation) { - return new self("Entity has no identity, therefore " . $operation ." cannot be performed. " . self::objToStr($entity)); + return new self('Entity has no identity, therefore ' . $operation . ' cannot be performed. ' . self::objToStr($entity)); } /** @@ -161,9 +173,9 @@ static public function entityHasNoIdentity($entity, $operation) * * @return ORMInvalidArgumentException */ - static public function entityIsRemoved($entity, $operation) + public static function entityIsRemoved($entity, $operation) { - return new self("Entity is removed, therefore " . $operation ." cannot be performed. " . self::objToStr($entity)); + return new self('Entity is removed, therefore ' . $operation . ' cannot be performed. ' . self::objToStr($entity)); } /** @@ -172,9 +184,9 @@ static public function entityIsRemoved($entity, $operation) * * @return ORMInvalidArgumentException */ - static public function detachedEntityCannot($entity, $operation) + public static function detachedEntityCannot($entity, $operation) { - return new self("Detached entity " . self::objToStr($entity) . " cannot be " . $operation); + return new self('Detached entity ' . self::objToStr($entity) . ' cannot be ' . $operation); } /** @@ -187,7 +199,7 @@ static public function detachedEntityCannot($entity, $operation) public static function invalidObject($context, $given, $parameterIndex = 1) { return new self($context . ' expects parameter ' . $parameterIndex . - ' to be an entity object, '. gettype($given) . ' given.'); + ' to be an entity object, ' . gettype($given) . ' given.'); } /** @@ -195,8 +207,8 @@ public static function invalidObject($context, $given, $parameterIndex = 1) */ public static function invalidCompositeIdentifier() { - return new self("Binding an entity with a composite primary key to a query is not supported. " . - "You should split the parameter into the explicit fields and bind them separately."); + return new self('Binding an entity with a composite primary key to a query is not supported. ' . + 'You should split the parameter into the explicit fields and bind them separately.'); } /** @@ -204,13 +216,12 @@ public static function invalidCompositeIdentifier() */ public static function invalidIdentifierBindingEntity() { - return new self("Binding entities to query parameters only allowed for entities that have an identifier."); + return new self('Binding entities to query parameters only allowed for entities that have an identifier.'); } /** - * @param ClassMetadata $targetClass - * @param array $assoc - * @param mixed $actualValue + * @param array $assoc + * @param mixed $actualValue * * @return self */ @@ -243,19 +254,17 @@ public static function invalidEntityName($entityName) * Helper method to show an object as string. * * @param object $obj - * - * @return string */ - private static function objToStr($obj) : string + private static function objToStr($obj): string { - return method_exists($obj, '__toString') ? (string) $obj : get_class($obj).'@'.spl_object_hash($obj); + return method_exists($obj, '__toString') ? (string) $obj : get_class($obj) . '@' . spl_object_hash($obj); } /** * @param array $associationMapping * @param object $entity */ - private static function newEntityFoundThroughRelationshipMessage(array $associationMapping, $entity) : string + private static function newEntityFoundThroughRelationshipMessage(array $associationMapping, $entity): string { return 'A new entity was found through the relationship \'' . $associationMapping['sourceEntity'] . '#' . $associationMapping['fieldName'] . '\' that was not' diff --git a/lib/Doctrine/ORM/OptimisticLockException.php b/lib/Doctrine/ORM/OptimisticLockException.php index 23af9bb7802..cd00ef4d34e 100644 --- a/lib/Doctrine/ORM/OptimisticLockException.php +++ b/lib/Doctrine/ORM/OptimisticLockException.php @@ -1,4 +1,5 @@ - * @author Benjamin Eberlei - * @since 2.0 */ class OptimisticLockException extends ORMException { - /** - * @var object|null - */ + /** @var object|null */ private $entity; /** - * @param string $msg + * @param string $msg * @param object|null $entity */ public function __construct($msg, $entity) @@ -61,7 +58,7 @@ public function getEntity() */ public static function lockFailed($entity) { - return new self("The optimistic lock on an entity failed.", $entity); + return new self('The optimistic lock on an entity failed.', $entity); } /** @@ -73,10 +70,10 @@ public static function lockFailed($entity) */ public static function lockFailedVersionMismatch($entity, $expectedLockVersion, $actualLockVersion) { - $expectedLockVersion = ($expectedLockVersion instanceof \DateTime) ? $expectedLockVersion->getTimestamp() : $expectedLockVersion; - $actualLockVersion = ($actualLockVersion instanceof \DateTime) ? $actualLockVersion->getTimestamp() : $actualLockVersion; + $expectedLockVersion = $expectedLockVersion instanceof DateTime ? $expectedLockVersion->getTimestamp() : $expectedLockVersion; + $actualLockVersion = $actualLockVersion instanceof DateTime ? $actualLockVersion->getTimestamp() : $actualLockVersion; - return new self("The optimistic lock failed, version " . $expectedLockVersion . " was expected, but is actually ".$actualLockVersion, $entity); + return new self('The optimistic lock failed, version ' . $expectedLockVersion . ' was expected, but is actually ' . $actualLockVersion, $entity); } /** @@ -86,6 +83,6 @@ public static function lockFailedVersionMismatch($entity, $expectedLockVersion, */ public static function notVersioned($entityName) { - return new self("Cannot obtain optimistic lock on unversioned entity " . $entityName, null); + return new self('Cannot obtain optimistic lock on unversioned entity ' . $entityName, null); } } diff --git a/lib/Doctrine/ORM/PersistentCollection.php b/lib/Doctrine/ORM/PersistentCollection.php index 96bdc1a9764..eaa2aeb1f5f 100644 --- a/lib/Doctrine/ORM/PersistentCollection.php +++ b/lib/Doctrine/ORM/PersistentCollection.php @@ -1,4 +1,5 @@ - * @author Roman Borschel - * @author Giorgio Sironi - * @author Stefano Rodriguez */ final class PersistentCollection extends AbstractLazyCollection implements Selectable { @@ -70,7 +74,7 @@ final class PersistentCollection extends AbstractLazyCollection implements Selec /** * The EntityManager that manages the persistence of the collection. * - * @var \Doctrine\ORM\EntityManagerInterface + * @var EntityManagerInterface */ private $em; @@ -93,7 +97,7 @@ final class PersistentCollection extends AbstractLazyCollection implements Selec * Whether the collection is dirty and needs to be synchronized with the database * when the UnitOfWork that manages its persistent state commits. * - * @var boolean + * @var bool */ private $isDirty = false; @@ -166,11 +170,14 @@ public function hydrateAdd($element) if ($this->backRefFieldName && $this->association['type'] === ClassMetadata::ONE_TO_MANY) { // Set back reference to owner $this->typeClass->reflFields[$this->backRefFieldName]->setValue( - $element, $this->owner + $element, + $this->owner ); $this->em->getUnitOfWork()->setOriginalEntityProperty( - spl_object_hash($element), $this->backRefFieldName, $this->owner + spl_object_hash($element), + $this->backRefFieldName, + $this->owner ); } } @@ -193,7 +200,8 @@ public function hydrateSet($key, $element) if ($this->backRefFieldName && $this->association['type'] === ClassMetadata::ONE_TO_MANY) { // Set back reference to owner $this->typeClass->reflFields[$this->backRefFieldName]->setValue( - $element, $this->owner + $element, + $this->owner ); } } @@ -249,7 +257,9 @@ public function getDeleteDiff() return array_udiff_assoc( $this->snapshot, $this->collection->toArray(), - function($a, $b) { return $a === $b ? 0 : 1; } + static function ($a, $b) { + return $a === $b ? 0 : 1; + } ); } @@ -264,7 +274,9 @@ public function getInsertDiff() return array_udiff_assoc( $this->collection->toArray(), $this->snapshot, - function($a, $b) { return $a === $b ? 0 : 1; } + static function ($a, $b) { + return $a === $b ? 0 : 1; + } ); } @@ -291,11 +303,13 @@ private function changed() $this->isDirty = true; - if ($this->association !== null && + if ( + $this->association !== null && $this->association['isOwningSide'] && $this->association['type'] === ClassMetadata::MANY_TO_MANY && $this->owner && - $this->em->getClassMetadata(get_class($this->owner))->isChangeTrackingNotify()) { + $this->em->getClassMetadata(get_class($this->owner))->isChangeTrackingNotify() + ) { $this->em->getUnitOfWork()->scheduleForDirtyCheck($this->owner); } } @@ -304,7 +318,7 @@ private function changed() * Gets a boolean flag indicating whether this collection is dirty which means * its state needs to be synchronized with the database. * - * @return boolean TRUE if the collection is dirty, FALSE otherwise. + * @return bool TRUE if the collection is dirty, FALSE otherwise. */ public function isDirty() { @@ -314,7 +328,7 @@ public function isDirty() /** * Sets a boolean flag, indicating whether this collection is dirty. * - * @param boolean $dirty Whether the collection should be marked dirty or not. + * @param bool $dirty Whether the collection should be marked dirty or not. * * @return void */ @@ -326,7 +340,7 @@ public function setDirty($dirty) /** * Sets the initialized flag of the collection, forcing it into that state. * - * @param boolean $bool + * @param bool $bool * * @return void */ @@ -348,16 +362,18 @@ public function remove($key) // association (table). Without initializing the collection. $removed = parent::remove($key); - if ( ! $removed) { + if (! $removed) { return $removed; } $this->changed(); - if ($this->association !== null && + if ( + $this->association !== null && $this->association['type'] & ClassMetadata::TO_MANY && $this->owner && - $this->association['orphanRemoval']) { + $this->association['orphanRemoval'] + ) { $this->em->getUnitOfWork()->scheduleOrphanRemoval($removed); } @@ -371,16 +387,18 @@ public function removeElement($element) { $removed = parent::removeElement($element); - if ( ! $removed) { + if (! $removed) { return $removed; } $this->changed(); - if ($this->association !== null && + if ( + $this->association !== null && $this->association['type'] & ClassMetadata::TO_MANY && $this->owner && - $this->association['orphanRemoval']) { + $this->association['orphanRemoval'] + ) { $this->em->getUnitOfWork()->scheduleOrphanRemoval($element); } @@ -392,8 +410,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['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY + && isset($this->association['indexBy']) + ) { $persister = $this->em->getUnitOfWork()->getCollectionPersister($this->association); return $this->collection->containsKey($key) || $persister->containsKey($this, $key); @@ -407,7 +427,7 @@ public function containsKey($key) */ public function contains($element) { - if ( ! $this->initialized && $this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY) { + if (! $this->initialized && $this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY) { $persister = $this->em->getUnitOfWork()->getCollectionPersister($this->association); return $this->collection->contains($element) || $persister->contains($this, $element); @@ -421,11 +441,12 @@ public function contains($element) */ public function get($key) { - if ( ! $this->initialized + if ( + ! $this->initialized && $this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY && isset($this->association['indexBy']) ) { - if (!$this->typeClass->isIdentifierComposite && $this->typeClass->isIdentifier($this->association['indexBy'])) { + if (! $this->typeClass->isIdentifierComposite && $this->typeClass->isIdentifier($this->association['indexBy'])) { return $this->em->find($this->typeClass->name, $key); } @@ -502,8 +523,9 @@ public function offsetGet($offset) */ public function offsetSet($offset, $value) { - if ( ! isset($offset)) { + if (! isset($offset)) { $this->add($value); + return; } @@ -541,9 +563,11 @@ public function clear() $uow = $this->em->getUnitOfWork(); - if ($this->association['type'] & ClassMetadata::TO_MANY && + if ( + $this->association['type'] & ClassMetadata::TO_MANY && $this->association['orphanRemoval'] && - $this->owner) { + $this->owner + ) { // we need to initialize here, as orphan removal acts like implicit cascadeRemove, // hence for event listeners we need the objects in memory. $this->initialize(); @@ -577,7 +601,7 @@ public function clear() * * @psalm-return array{0: string, 1: string} */ - public function __sleep() : array + public function __sleep(): array { return ['collection', 'initialized']; } @@ -596,7 +620,7 @@ public function __sleep() : array */ 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['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY) { $persister = $this->em->getUnitOfWork()->getCollectionPersister($this->association); return $persister->slice($this, $offset, $length); @@ -636,11 +660,9 @@ public function __clone() * Selects all elements from a selectable that match the expression and * return a new collection containing these elements. * - * @param \Doctrine\Common\Collections\Criteria $criteria - * * @return Collection * - * @throws \RuntimeException + * @throws RuntimeException */ public function matching(Criteria $criteria) { @@ -669,7 +691,7 @@ public function matching(Criteria $criteria) $persister = $this->em->getUnitOfWork()->getEntityPersister($this->association['targetEntity']); - return ($this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY) + return $this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY ? new LazyCriteriaCollection($persister, $criteria) : new ArrayCollection($persister->loadCriteria($criteria)); } @@ -677,7 +699,7 @@ public function matching(Criteria $criteria) /** * Retrieves the wrapped Collection instance. * - * @return \Doctrine\Common\Collections\Collection + * @return Collection */ public function unwrap() { @@ -713,16 +735,16 @@ protected function doInitialize() * high overhead (complexity of O(n^2)). `array_diff_key()` performs the operation in * core, which is faster than using a callback for comparisons */ - private function restoreNewObjectsInDirtyCollection(array $newObjects) : void + private function restoreNewObjectsInDirtyCollection(array $newObjects): void { $loadedObjects = $this->collection->toArray(); - $newObjectsByOid = \array_combine(\array_map('spl_object_hash', $newObjects), $newObjects); - $loadedObjectsByOid = \array_combine(\array_map('spl_object_hash', $loadedObjects), $loadedObjects); - $newObjectsThatWereNotLoaded = \array_diff_key($newObjectsByOid, $loadedObjectsByOid); + $newObjectsByOid = array_combine(array_map('spl_object_hash', $newObjects), $newObjects); + $loadedObjectsByOid = array_combine(array_map('spl_object_hash', $loadedObjects), $loadedObjects); + $newObjectsThatWereNotLoaded = array_diff_key($newObjectsByOid, $loadedObjectsByOid); if ($newObjectsThatWereNotLoaded) { // Reattach NEW objects added through add(), if any. - \array_walk($newObjectsThatWereNotLoaded, [$this->collection, 'add']); + array_walk($newObjectsThatWereNotLoaded, [$this->collection, 'add']); $this->isDirty = true; } diff --git a/lib/Doctrine/ORM/Persisters/Collection/AbstractCollectionPersister.php b/lib/Doctrine/ORM/Persisters/Collection/AbstractCollectionPersister.php index 2e85b67f3b2..47b96d93943 100644 --- a/lib/Doctrine/ORM/Persisters/Collection/AbstractCollectionPersister.php +++ b/lib/Doctrine/ORM/Persisters/Collection/AbstractCollectionPersister.php @@ -1,4 +1,5 @@ */ abstract class AbstractCollectionPersister implements CollectionPersister { - /** - * @var EntityManagerInterface - */ + /** @var EntityManagerInterface */ protected $em; - /** - * @var \Doctrine\DBAL\Connection - */ + /** @var Connection */ protected $conn; - /** - * @var UnitOfWork - */ + /** @var UnitOfWork */ protected $uow; /** * The database platform. * - * @var \Doctrine\DBAL\Platforms\AbstractPlatform + * @var AbstractPlatform */ protected $platform; /** * The quote strategy. * - * @var \Doctrine\ORM\Mapping\QuoteStrategy + * @var QuoteStrategy */ protected $quoteStrategy; /** * Initializes a new instance of a class derived from AbstractCollectionPersister. - * - * @param EntityManagerInterface $em */ 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(); + $this->quoteStrategy = $em->getConfiguration()->getQuoteStrategy(); } /** diff --git a/lib/Doctrine/ORM/Persisters/Collection/CollectionPersister.php b/lib/Doctrine/ORM/Persisters/Collection/CollectionPersister.php index 3a30c990380..7a447849764 100644 --- a/lib/Doctrine/ORM/Persisters/Collection/CollectionPersister.php +++ b/lib/Doctrine/ORM/Persisters/Collection/CollectionPersister.php @@ -1,4 +1,5 @@ - * @since 2.5 */ interface CollectionPersister { /** * Deletes the persistent state represented by the given collection. * - * @param \Doctrine\ORM\PersistentCollection $collection - * * @return void */ public function delete(PersistentCollection $collection); @@ -44,8 +40,6 @@ public function delete(PersistentCollection $collection); * Updates the given collection, synchronizing its state with the database * by inserting, updating and deleting individual elements. * - * @param \Doctrine\ORM\PersistentCollection $collection - * * @return void */ public function update(PersistentCollection $collection); @@ -53,18 +47,15 @@ public function update(PersistentCollection $collection); /** * Counts the size of this persistent collection. * - * @param \Doctrine\ORM\PersistentCollection $collection - * - * @return integer + * @return int */ public function count(PersistentCollection $collection); /** * Slices elements. * - * @param \Doctrine\ORM\PersistentCollection $collection - * @param integer $offset - * @param integer $length + * @param int $offset + * @param int $length * * @return array */ @@ -73,28 +64,25 @@ public function slice(PersistentCollection $collection, $offset, $length = null) /** * Checks for existence of an element. * - * @param \Doctrine\ORM\PersistentCollection $collection - * @param object $element + * @param object $element * - * @return boolean + * @return bool */ public function contains(PersistentCollection $collection, $element); /** * Checks for existence of a key. * - * @param \Doctrine\ORM\PersistentCollection $collection - * @param mixed $key + * @param mixed $key * - * @return boolean + * @return bool */ public function containsKey(PersistentCollection $collection, $key); /** * Gets an element by key. * - * @param \Doctrine\ORM\PersistentCollection $collection - * @param mixed $index + * @param mixed $index * * @return mixed */ @@ -103,9 +91,6 @@ public function get(PersistentCollection $collection, $index); /** * Loads association entities matching the given Criteria object. * - * @param \Doctrine\ORM\PersistentCollection $collection - * @param \Doctrine\Common\Collections\Criteria $criteria - * * @return array */ public function loadCriteria(PersistentCollection $collection, Criteria $criteria); diff --git a/lib/Doctrine/ORM/Persisters/Collection/ManyToManyPersister.php b/lib/Doctrine/ORM/Persisters/Collection/ManyToManyPersister.php index 2cd6c3f6f22..ec42fae5723 100644 --- a/lib/Doctrine/ORM/Persisters/Collection/ManyToManyPersister.php +++ b/lib/Doctrine/ORM/Persisters/Collection/ManyToManyPersister.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Alexander - * @since 2.0 */ class ManyToManyPersister extends AbstractCollectionPersister { @@ -43,7 +50,7 @@ public function delete(PersistentCollection $collection) { $mapping = $collection->getMapping(); - if ( ! $mapping['isOwningSide']) { + if (! $mapping['isOwningSide']) { return; // ignore inverse side } @@ -64,7 +71,7 @@ public function update(PersistentCollection $collection) { $mapping = $collection->getMapping(); - if ( ! $mapping['isOwningSide']) { + if (! $mapping['isOwningSide']) { return; // ignore inverse side } @@ -95,8 +102,8 @@ public function get(PersistentCollection $collection, $index) { $mapping = $collection->getMapping(); - if ( ! isset($mapping['indexBy'])) { - throw new \BadMethodCallException("Selecting a collection by index is only supported on indexed collections."); + if (! isset($mapping['indexBy'])) { + throw new BadMethodCallException('Selecting a collection by index is only supported on indexed collections.'); } $persister = $this->uow->getEntityPersister($mapping['targetEntity']); @@ -112,19 +119,19 @@ 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']) + $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']) + $joinTableName = $this->quoteStrategy->getJoinTableName($association, $sourceClass, $this->platform); + $joinColumns = ! $mapping['isOwningSide'] ? $association['joinTable']['inverseJoinColumns'] : $association['joinTable']['joinColumns']; @@ -144,7 +151,6 @@ public function count(PersistentCollection $collection) // If there is a provided criteria, make part of conditions // @todo Fix this. Current SQL returns something like: - // /*if ($criteria && ($expression = $criteria->getWhereExpression()) !== null) { // A join is needed on the target entity $targetTableName = $this->quoteStrategy->getTableName($targetClass, $this->platform); @@ -177,6 +183,7 @@ public function slice(PersistentCollection $collection, $offset, $length = null) return $persister->getManyToManyCollection($mapping, $collection->getOwner(), $offset, $length); } + /** * {@inheritdoc} */ @@ -184,8 +191,8 @@ public function containsKey(PersistentCollection $collection, $key) { $mapping = $collection->getMapping(); - if ( ! isset($mapping['indexBy'])) { - throw new \BadMethodCallException("Selecting a collection by index is only supported on indexed collections."); + if (! isset($mapping['indexBy'])) { + throw new BadMethodCallException('Selecting a collection by index is only supported on indexed collections.'); } [$quotedJoinTable, $whereClauses, $params, $types] = $this->getJoinTableRestrictionsWithKey( @@ -204,7 +211,7 @@ public function containsKey(PersistentCollection $collection, $key) */ public function contains(PersistentCollection $collection, $element) { - if ( ! $this->isValidEntityState($element)) { + if (! $this->isValidEntityState($element)) { return false; } @@ -232,18 +239,18 @@ public function loadCriteria(PersistentCollection $collection, Criteria $criteri $onConditions = $this->getOnConditionSQL($mapping); $whereClauses = $params = []; - if ( ! $mapping['isOwningSide']) { + if (! $mapping['isOwningSide']) { $associationSourceClass = $targetClass; - $mapping = $targetClass->associationMappings[$mapping['mappedBy']]; - $sourceRelationMode = 'relationToTargetKeyColumns'; + $mapping = $targetClass->associationMappings[$mapping['mappedBy']]; + $sourceRelationMode = 'relationToTargetKeyColumns'; } else { $associationSourceClass = $ownerMetadata; - $sourceRelationMode = 'relationToSourceKeyColumns'; + $sourceRelationMode = 'relationToSourceKeyColumns'; } foreach ($mapping[$sourceRelationMode] as $key => $value) { $whereClauses[] = sprintf('t.%s = ?', $key); - $params[] = $ownerMetadata->containsForeignIdentifier + $params[] = $ownerMetadata->containsForeignIdentifier ? $id[$ownerMetadata->getFieldForColumn($value)] : $id[$ownerMetadata->fieldNames[$value]]; } @@ -258,15 +265,15 @@ public function loadCriteria(PersistentCollection $collection, Criteria $criteri $params[] = $value; } - $tableName = $this->quoteStrategy->getTableName($targetClass, $this->platform); - $joinTable = $this->quoteStrategy->getJoinTableName($mapping, $associationSourceClass, $this->platform); + $tableName = $this->quoteStrategy->getTableName($targetClass, $this->platform); + $joinTable = $this->quoteStrategy->getJoinTableName($mapping, $associationSourceClass, $this->platform); $rsm = new Query\ResultSetMappingBuilder($this->em); $rsm->addRootEntityFromClassMetadata($targetClass->name, 'te'); $sql = 'SELECT ' . $rsm->generateSelectClause() . ' FROM ' . $tableName . ' te' - . ' JOIN ' . $joinTable . ' t ON' + . ' JOIN ' . $joinTable . ' t ON' . implode(' AND ', $onConditions) . ' WHERE ' . implode(' AND ', $whereClauses); @@ -305,7 +312,7 @@ public function getFilterSql($mapping) $rootClass = $this->em->getClassMetadata($targetClass->rootEntityName); $filterSql = $this->generateFilterConditionSQL($rootClass, 'te'); - if ('' === $filterSql) { + if ($filterSql === '') { return ['', '']; } @@ -352,7 +359,7 @@ protected function generateFilterConditionSQL(ClassMetadata $targetEntity, $targ protected function getOnConditionSQL($mapping) { $targetClass = $this->em->getClassMetadata($mapping['targetEntity']); - $association = ( ! $mapping['isOwningSide']) + $association = ! $mapping['isOwningSide'] ? $targetClass->associationMappings[$mapping['mappedBy']] : $mapping; @@ -377,10 +384,10 @@ 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); + $columns = []; + $mapping = $collection->getMapping(); + $class = $this->em->getClassMetadata(get_class($collection->getOwner())); + $joinTable = $this->quoteStrategy->getJoinTableName($mapping, $class, $this->platform); foreach ($mapping['joinTable']['joinColumns'] as $joinColumn) { $columns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform); @@ -421,8 +428,6 @@ protected function getDeleteSQLParameters(PersistentCollection $collection) /** * Gets the SQL statement used for deleting a row from the collection. * - * @param \Doctrine\ORM\PersistentCollection $collection - * * @return string[]|string[][] ordered tuple containing the SQL to be executed and an array * of types for bound parameters * @@ -459,8 +464,7 @@ protected function getDeleteRowSQL(PersistentCollection $collection) * * Internal note: Order of the parameters must be the same as the order of the columns in getDeleteRowSql. * - * @param \Doctrine\ORM\PersistentCollection $collection - * @param mixed $element + * @param mixed $element * * @return array * @@ -474,8 +478,6 @@ protected function getDeleteRowSQLParameters(PersistentCollection $collection, $ /** * Gets the SQL statement used for inserting a row in the collection. * - * @param \Doctrine\ORM\PersistentCollection $collection - * * @return string[]|string[][] ordered tuple containing the SQL to be executed and an array * of types for bound parameters * @@ -514,8 +516,7 @@ protected function getInsertRowSQL(PersistentCollection $collection) * * Internal note: Order of the parameters must be the same as the order of the columns in getInsertRowSql. * - * @param \Doctrine\ORM\PersistentCollection $collection - * @param mixed $element + * @param mixed $element * * @return array * @@ -530,8 +531,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. * - * @param \Doctrine\ORM\PersistentCollection $collection - * @param object $element + * @param object $element * * @return mixed[] * @@ -555,7 +555,7 @@ private function collectJoinTableColumnParameters(PersistentCollection $collecti foreach ($mapping['joinTableColumns'] as $joinTableColumn) { $isRelationToSource = isset($mapping['relationToSourceKeyColumns'][$joinTableColumn]); - if ( ! $isComposite) { + if (! $isComposite) { $params[] = $isRelationToSource ? array_pop($identifier1) : array_pop($identifier2); continue; @@ -574,9 +574,8 @@ private function collectJoinTableColumnParameters(PersistentCollection $collecti } /** - * @param \Doctrine\ORM\PersistentCollection $collection - * @param string $key - * @param boolean $addFilters Whether the filter SQL should be included or not. + * @param string $key + * @param bool $addFilters Whether the filter SQL should be included or not. * * @return array ordered vector: * - quoted join table name @@ -608,7 +607,7 @@ private function getJoinTableRestrictionsWithKey(PersistentCollection $collectio $targetRelationMode = 'relationToTargetKeyColumns'; } - $quotedJoinTable = $this->quoteStrategy->getJoinTableName($mapping, $associationSourceClass, $this->platform). ' t'; + $quotedJoinTable = $this->quoteStrategy->getJoinTableName($mapping, $associationSourceClass, $this->platform) . ' t'; $whereClauses = []; $params = []; $types = []; @@ -639,7 +638,7 @@ private function getJoinTableRestrictionsWithKey(PersistentCollection $collectio ? $id[$sourceClass->getFieldForColumn($column)] : $id[$sourceClass->fieldNames[$column]]; $types[] = PersisterHelper::getTypeOfColumn($column, $sourceClass, $this->em); - } elseif ( ! $joinNeeded) { + } elseif (! $joinNeeded) { $column = $mapping[$targetRelationMode][$joinTableColumn]; $whereClauses[] = 't.' . $joinTableColumn . ' = ?'; @@ -653,7 +652,7 @@ private function getJoinTableRestrictionsWithKey(PersistentCollection $collectio if ($filterSql) { $quotedJoinTable .= ' ' . $joinTargetEntitySQL; - $whereClauses[] = $filterSql; + $whereClauses[] = $filterSql; } } @@ -661,9 +660,8 @@ private function getJoinTableRestrictionsWithKey(PersistentCollection $collectio } /** - * @param \Doctrine\ORM\PersistentCollection $collection - * @param object $element - * @param boolean $addFilters Whether the filter SQL should be included or not. + * @param object $element + * @param bool $addFilters Whether the filter SQL should be included or not. * * @return array ordered vector: * - quoted join table name @@ -675,21 +673,21 @@ private function getJoinTableRestrictionsWithKey(PersistentCollection $collectio */ private function getJoinTableRestrictions(PersistentCollection $collection, $element, $addFilters) { - $filterMapping = $collection->getMapping(); - $mapping = $filterMapping; + $filterMapping = $collection->getMapping(); + $mapping = $filterMapping; - if ( ! $mapping['isOwningSide']) { + 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()); + $sourceId = $this->uow->getEntityIdentifier($element); + $targetId = $this->uow->getEntityIdentifier($collection->getOwner()); $mapping = $sourceClass->associationMappings[$mapping['mappedBy']]; } else { $sourceClass = $this->em->getClassMetadata($mapping['sourceEntity']); $targetClass = $this->em->getClassMetadata($mapping['targetEntity']); - $sourceId = $this->uow->getEntityIdentifier($collection->getOwner()); - $targetId = $this->uow->getEntityIdentifier($element); + $sourceId = $this->uow->getEntityIdentifier($collection->getOwner()); + $targetId = $this->uow->getEntityIdentifier($element); } $quotedJoinTable = $this->quoteStrategy->getJoinTableName($mapping, $sourceClass, $this->platform); @@ -721,7 +719,7 @@ private function getJoinTableRestrictions(PersistentCollection $collection, $ele if ($filterSql) { $quotedJoinTable .= ' ' . $joinTargetEntitySQL; - $whereClauses[] = $filterSql; + $whereClauses[] = $filterSql; } } @@ -732,8 +730,6 @@ private function getJoinTableRestrictions(PersistentCollection $collection, $ele * Expands Criteria Parameters by walking the expressions and grabbing all * parameters and types from it. * - * @param \Doctrine\Common\Collections\Criteria $criteria - * * @return array */ private function expandCriteriaParameters(Criteria $criteria) @@ -754,8 +750,6 @@ private function expandCriteriaParameters(Criteria $criteria) } /** - * @param Criteria $criteria - * @param ClassMetadata $targetClass * @return string */ private function getOrderingSql(Criteria $criteria, ClassMetadata $targetClass) @@ -764,7 +758,7 @@ private function getOrderingSql(Criteria $criteria, ClassMetadata $targetClass) if ($orderings) { $orderBy = []; foreach ($orderings as $name => $direction) { - $field = $this->quoteStrategy->getColumnName( + $field = $this->quoteStrategy->getColumnName( $name, $targetClass, $this->platform @@ -774,13 +768,14 @@ private function getOrderingSql(Criteria $criteria, ClassMetadata $targetClass) return ' ORDER BY ' . implode(', ', $orderBy); } + return ''; } /** - * @param Criteria $criteria * @return string - * @throws \Doctrine\DBAL\DBALException + * + * @throws DBALException */ private function getLimitSql(Criteria $criteria) { @@ -789,6 +784,7 @@ private function getLimitSql(Criteria $criteria) if ($limit !== null || $offset !== null) { return $this->platform->modifyLimitQuery('', $limit, $offset); } + return ''; } } diff --git a/lib/Doctrine/ORM/Persisters/Collection/OneToManyPersister.php b/lib/Doctrine/ORM/Persisters/Collection/OneToManyPersister.php index 1409b0e3216..f872cc1c6d4 100644 --- a/lib/Doctrine/ORM/Persisters/Collection/OneToManyPersister.php +++ b/lib/Doctrine/ORM/Persisters/Collection/OneToManyPersister.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Alexander - * @since 2.0 */ class OneToManyPersister extends AbstractCollectionPersister { @@ -46,7 +49,7 @@ public function delete(PersistentCollection $collection) // the entire collection with a new would trigger this operation. $mapping = $collection->getMapping(); - if ( ! $mapping['orphanRemoval']) { + if (! $mapping['orphanRemoval']) { // 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. @@ -78,8 +81,8 @@ public function get(PersistentCollection $collection, $index) { $mapping = $collection->getMapping(); - if ( ! isset($mapping['indexBy'])) { - throw new \BadMethodCallException("Selecting a collection by index is only supported on indexed collections."); + if (! isset($mapping['indexBy'])) { + throw new BadMethodCallException('Selecting a collection by index is only supported on indexed collections.'); } $persister = $this->uow->getEntityPersister($mapping['targetEntity']); @@ -87,7 +90,7 @@ public function get(PersistentCollection $collection, $index) return $persister->load( [ $mapping['mappedBy'] => $collection->getOwner(), - $mapping['indexBy'] => $index + $mapping['indexBy'] => $index, ], null, $mapping, @@ -131,8 +134,8 @@ public function containsKey(PersistentCollection $collection, $key) { $mapping = $collection->getMapping(); - if ( ! isset($mapping['indexBy'])) { - throw new \BadMethodCallException("Selecting a collection by index is only supported on indexed collections."); + if (! isset($mapping['indexBy'])) { + throw new BadMethodCallException('Selecting a collection by index is only supported on indexed collections.'); } $persister = $this->uow->getEntityPersister($mapping['targetEntity']); @@ -149,11 +152,11 @@ public function containsKey(PersistentCollection $collection, $key) } /** - * {@inheritdoc} - */ + * {@inheritdoc} + */ public function contains(PersistentCollection $collection, $element) { - if ( ! $this->isValidEntityState($element)) { + if (! $this->isValidEntityState($element)) { return false; } @@ -173,15 +176,13 @@ public function contains(PersistentCollection $collection, $element) */ public function loadCriteria(PersistentCollection $collection, Criteria $criteria) { - throw new \BadMethodCallException("Filtering a collection by Criteria is not supported by this CollectionPersister."); + throw new BadMethodCallException('Filtering a collection by Criteria is not supported by this CollectionPersister.'); } /** - * @param PersistentCollection $collection - * * @return int * - * @throws \Doctrine\DBAL\DBALException + * @throws DBALException */ private function deleteEntityCollection(PersistentCollection $collection) { @@ -209,11 +210,9 @@ private function deleteEntityCollection(PersistentCollection $collection) * * Thanks Steve Ebersole (Hibernate) for idea on how to tackle reliably this scenario, we owe him a beer! =) * - * @param PersistentCollection $collection - * * @return int * - * @throws \Doctrine\DBAL\DBALException + * @throws DBALException */ private function deleteJoinedEntityCollection(PersistentCollection $collection) { diff --git a/lib/Doctrine/ORM/Persisters/Entity/AbstractEntityInheritancePersister.php b/lib/Doctrine/ORM/Persisters/Entity/AbstractEntityInheritancePersister.php index 79472b50c0e..e84ea7837dc 100644 --- a/lib/Doctrine/ORM/Persisters/Entity/AbstractEntityInheritancePersister.php +++ b/lib/Doctrine/ORM/Persisters/Entity/AbstractEntityInheritancePersister.php @@ -1,4 +1,5 @@ - * @author Benjamin Eberlei - * @since 2.0 */ abstract class AbstractEntityInheritancePersister extends BasicEntityPersister { @@ -41,8 +40,8 @@ protected function prepareInsertData($entity) $data = parent::prepareInsertData($entity); // Populate the discriminator column - $discColumn = $this->class->discriminatorColumn; - $this->columnTypes[$discColumn['name']] = $discColumn['type']; + $discColumn = $this->class->discriminatorColumn; + $this->columnTypes[$discColumn['name']] = $discColumn['type']; $data[$this->getDiscriminatorColumnTableName()][$discColumn['name']] = $this->class->discriminatorValue; return $data; @@ -60,7 +59,7 @@ abstract protected function getDiscriminatorColumnTableName(); */ protected function getSelectColumnSQL($field, ClassMetadata $class, $alias = 'r') { - $tableAlias = $alias == 'r' ? '' : $alias; + $tableAlias = $alias === 'r' ? '' : $alias; $fieldMapping = $class->fieldMappings[$field]; $columnAlias = $this->getSQLColumnAlias($fieldMapping['columnName']); $sql = sprintf( @@ -72,8 +71,8 @@ protected function getSelectColumnSQL($field, ClassMetadata $class, $alias = 'r' $this->currentPersisterContext->rsm->addFieldResult($alias, $columnAlias, $field, $class->name); if (isset($fieldMapping['requireSQLConversion'])) { - $type = Type::getType($fieldMapping['type']); - $sql = $type->convertToPHPValueSQL($sql, $this->platform); + $type = Type::getType($fieldMapping['type']); + $sql = $type->convertToPHPValueSQL($sql, $this->platform); } return $sql . ' AS ' . $columnAlias; @@ -83,7 +82,6 @@ protected function getSelectColumnSQL($field, ClassMetadata $class, $alias = 'r' * @param string $tableAlias * @param string $joinColumnName * @param string $quotedColumnName - * * @param string $type * * @return string diff --git a/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php b/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php index da809358d15..fa085ed8b29 100644 --- a/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php +++ b/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php @@ -1,4 +1,5 @@ - * @author Giorgio Sironi - * @author Benjamin Eberlei - * @author Alexander - * @author Fabio B. Silva - * @author Rob Caiger - * @since 2.0 */ class BasicEntityPersister implements EntityPersister { - /** - * @var array - */ - static private $comparisonMap = [ + /** @var array */ + private static $comparisonMap = [ Comparison::EQ => '= %s', Comparison::NEQ => '!= %s', Comparison::GT => '> %s', @@ -107,21 +117,21 @@ class BasicEntityPersister implements EntityPersister /** * Metadata object that describes the mapping of the mapped entity class. * - * @var \Doctrine\ORM\Mapping\ClassMetadata + * @var ClassMetadata */ protected $class; /** * The underlying DBAL Connection of the used EntityManager. * - * @var \Doctrine\DBAL\Connection $conn + * @var Connection $conn */ protected $conn; /** * The database platform. * - * @var \Doctrine\DBAL\Platforms\AbstractPlatform + * @var AbstractPlatform */ protected $platform; @@ -143,20 +153,20 @@ class BasicEntityPersister implements EntityPersister * The map of column names to DBAL mapping types of all prepared columns used * when INSERTing or UPDATEing an entity. * - * @var array - * * @see prepareInsertData($entity) * @see prepareUpdateData($entity) + * + * @var array */ protected $columnTypes = []; /** * The map of quoted column names. * - * @var array - * * @see prepareInsertData($entity) * @see prepareUpdateData($entity) + * + * @var array */ protected $quotedColumns = []; @@ -171,38 +181,29 @@ class BasicEntityPersister implements EntityPersister /** * The quote strategy. * - * @var \Doctrine\ORM\Mapping\QuoteStrategy + * @var QuoteStrategy */ protected $quoteStrategy; /** * The IdentifierFlattener used for manipulating identifiers * - * @var \Doctrine\ORM\Utility\IdentifierFlattener + * @var IdentifierFlattener */ private $identifierFlattener; - /** - * @var CachedPersisterContext - */ + /** @var CachedPersisterContext */ protected $currentPersisterContext; - /** - * @var CachedPersisterContext - */ + /** @var CachedPersisterContext */ private $limitsHandlingContext; - /** - * @var CachedPersisterContext - */ + /** @var CachedPersisterContext */ private $noLimitsContext; /** * Initializes a new BasicEntityPersister that uses the given EntityManager * and persists instances of the class described by the given ClassMetadata descriptor. - * - * @param EntityManagerInterface $em - * @param ClassMetadata $class */ public function __construct(EntityManagerInterface $em, ClassMetadata $class) { @@ -261,7 +262,7 @@ public function getInserts() */ public function executeInserts() { - if ( ! $this->queuedInserts) { + if (! $this->queuedInserts) { return []; } @@ -269,8 +270,8 @@ public function executeInserts() $idGenerator = $this->class->idGenerator; $isPostInsertId = $idGenerator->isPostInsertGenerator(); - $stmt = $this->conn->prepare($this->getInsertSQL()); - $tableName = $this->class->getTableName(); + $stmt = $this->conn->prepare($this->getInsertSQL()); + $tableName = $this->class->getTableName(); foreach ($this->queuedInserts as $entity) { $insertData = $this->prepareInsertData($entity); @@ -286,10 +287,8 @@ public function executeInserts() $stmt->execute(); if ($isPostInsertId) { - $generatedId = $idGenerator->generate($this->em, $entity); - $id = [ - $this->class->identifier[0] => $generatedId - ]; + $generatedId = $idGenerator->generate($this->em, $entity); + $id = [$this->class->identifier[0] => $generatedId]; $postInsertIds[] = [ 'generatedId' => $generatedId, 'entity' => $entity, @@ -329,8 +328,8 @@ protected function assignDefaultVersionValue($entity, array $id) /** * Fetches the current version value of a versioned entity. * - * @param \Doctrine\ORM\Mapping\ClassMetadata $versionedClass - * @param array $id + * @param ClassMetadata $versionedClass + * @param array $id * * @return mixed */ @@ -344,10 +343,9 @@ protected function fetchVersionValue($versionedClass, array $id) // FIXME: Order with composite keys might not be correct $sql = 'SELECT ' . $columnName - . ' FROM ' . $tableName + . ' FROM ' . $tableName . ' WHERE ' . implode(' = ? AND ', $identifier) . ' = ?'; - $flatId = $this->identifierFlattener->flattenIdentifier($versionedClass, $id); $value = $this->conn->fetchColumn( @@ -363,9 +361,9 @@ protected function fetchVersionValue($versionedClass, array $id) /** * @return int[]|null[]|string[] * - * @psalm-return list + * @psalm-return list<(int|string|null)> */ - private function extractIdentifierTypes(array $id, ClassMetadata $versionedClass) : array + private function extractIdentifierTypes(array $id, ClassMetadata $versionedClass): array { $types = []; @@ -384,7 +382,7 @@ public function update($entity) $tableName = $this->class->getTableName(); $updateData = $this->prepareUpdateData($entity); - if ( ! isset($updateData[$tableName]) || ! ($data = $updateData[$tableName])) { + if (! isset($updateData[$tableName]) || ! ($data = $updateData[$tableName])) { return; } @@ -404,17 +402,17 @@ public function update($entity) * 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. * - * @param object $entity The entity object being updated. - * @param string $quotedTableName The quoted name of the table to apply the UPDATE on. - * @param array $updateData The map of columns to update (column => value). - * @param boolean $versioned Whether the UPDATE should be versioned. + * @param object $entity The entity object being updated. + * @param string $quotedTableName The quoted name of the table to apply the UPDATE on. + * @param array $updateData The map of columns to update (column => value). + * @param bool $versioned Whether the UPDATE should be versioned. * * @return void * - * @throws \Doctrine\ORM\ORMException - * @throws \Doctrine\ORM\OptimisticLockException + * @throws ORMException + * @throws OptimisticLockException */ - protected final function updateTable($entity, $quotedTableName, array $updateData, $versioned = false) + final protected function updateTable($entity, $quotedTableName, array $updateData, $versioned = false) { $set = []; $types = []; @@ -426,8 +424,8 @@ protected final function updateTable($entity, $quotedTableName, array $updateDat switch (true) { case isset($this->class->fieldNames[$columnName]): - $fieldName = $this->class->fieldNames[$columnName]; - $column = $this->quoteStrategy->getColumnName($fieldName, $this->class, $this->platform); + $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]); @@ -442,16 +440,16 @@ protected final function updateTable($entity, $quotedTableName, array $updateDat break; } - $params[] = $value; - $set[] = $column . ' = ' . $placeholder; - $types[] = $this->columnTypes[$columnName]; + $params[] = $value; + $set[] = $column . ' = ' . $placeholder; + $types[] = $this->columnTypes[$columnName]; } $where = []; $identifier = $this->em->getUnitOfWork()->getEntityIdentifier($entity); foreach ($this->class->identifier as $idField) { - if ( ! isset($this->class->associationMappings[$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); @@ -477,13 +475,13 @@ protected final function updateTable($entity, $quotedTableName, array $updateDat } if ($versioned) { - $versionField = $this->class->versionField; - $versionFieldType = $this->class->fieldMappings[$versionField]['type']; - $versionColumn = $this->quoteStrategy->getColumnName($versionField, $this->class, $this->platform); + $versionField = $this->class->versionField; + $versionFieldType = $this->class->fieldMappings[$versionField]['type']; + $versionColumn = $this->quoteStrategy->getColumnName($versionField, $this->class, $this->platform); - $where[] = $versionColumn; - $types[] = $this->class->fieldMappings[$versionField]['type']; - $params[] = $this->class->reflFields[$versionField]->getValue($entity); + $where[] = $versionColumn; + $types[] = $this->class->fieldMappings[$versionField]['type']; + $params[] = $this->class->reflFields[$versionField]->getValue($entity); switch ($versionFieldType) { case Type::SMALLINT: @@ -510,11 +508,11 @@ protected final function updateTable($entity, $quotedTableName, array $updateDat } /** - * @todo Add check for platform if it supports foreign keys/cascading. - * * @param array $identifier * * @return void + * + * @todo Add check for platform if it supports foreign keys/cascading. */ protected function deleteJoinTableRecords($identifier) { @@ -525,14 +523,14 @@ protected function deleteJoinTableRecords($identifier) // @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']); + $selfReferential = ($mapping['targetEntity'] === $mapping['sourceEntity']); $class = $this->class; $association = $mapping; $otherColumns = []; $otherKeys = []; $keys = []; - if ( ! $mapping['isOwningSide']) { + if (! $mapping['isOwningSide']) { $class = $this->em->getClassMetadata($mapping['targetEntity']); $association = $class->associationMappings[$mapping['mappedBy']]; } @@ -541,9 +539,8 @@ protected function deleteJoinTableRecords($identifier) ? $association['joinTable']['joinColumns'] : $association['joinTable']['inverseJoinColumns']; - if ($selfReferential) { - $otherColumns = (! $mapping['isOwningSide']) + $otherColumns = ! $mapping['isOwningSide'] ? $association['joinTable']['joinColumns'] : $association['joinTable']['inverseJoinColumns']; } @@ -616,12 +613,12 @@ protected function prepareUpdateData($entity) $result = []; $uow = $this->em->getUnitOfWork(); - if (($versioned = $this->class->isVersioned) != false) { + if (($versioned = $this->class->isVersioned) !== false) { $versionField = $this->class->versionField; } foreach ($uow->getEntityChangeSet($entity) as $field => $change) { - if (isset($versionField) && $versionField == $field) { + if (isset($versionField) && $versionField === $field) { continue; } @@ -631,7 +628,7 @@ protected function prepareUpdateData($entity) $newVal = $change[1]; - if ( ! isset($this->class->associationMappings[$field])) { + if (! isset($this->class->associationMappings[$field])) { $fieldMapping = $this->class->fieldMappings[$field]; $columnName = $fieldMapping['columnName']; @@ -645,7 +642,7 @@ protected function prepareUpdateData($entity) $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 (! $assoc['isOwningSide'] || ! ($assoc['type'] & ClassMetadata::TO_ONE)) { continue; } @@ -693,12 +690,12 @@ protected function prepareUpdateData($entity) * * The default insert data preparation is the same as for updates. * + * @see prepareUpdateData + * * @param object $entity The entity for which to prepare the data. * * @return mixed[][] The prepared data for the tables to update. * - * @see prepareUpdateData - * * @psalm-return array */ protected function prepareInsertData($entity) @@ -717,17 +714,17 @@ public function getOwningTable($fieldName) /** * {@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, $assoc = null, array $hints = [], $lockMode = null, $limit = null, ?array $orderBy = null) { $this->switchPersisterContext(null, $limit); - $sql = $this->getSelectSQL($criteria, $assoc, $lockMode, $limit, null, $orderBy); + $sql = $this->getSelectSQL($criteria, $assoc, $lockMode, $limit, null, $orderBy); [$params, $types] = $this->expandParameters($criteria); - $stmt = $this->conn->executeQuery($sql, $params, $types); + $stmt = $this->conn->executeQuery($sql, $params, $types); if ($entity !== null) { - $hints[Query::HINT_REFRESH] = true; - $hints[Query::HINT_REFRESH_ENTITY] = $entity; + $hints[Query::HINT_REFRESH] = true; + $hints[Query::HINT_REFRESH_ENTITY] = $entity; } $hydrator = $this->em->newHydrator($this->currentPersisterContext->selectJoinSql ? Query::HYDRATE_OBJECT : Query::HYDRATE_SIMPLEOBJECT); @@ -749,7 +746,7 @@ public function loadById(array $identifier, $entity = null) */ public function loadOneToOneEntity(array $assoc, $sourceEntity, array $identifier = []) { - if (($foundEntity = $this->em->getUnitOfWork()->tryGetById($identifier, $assoc['targetEntity'])) != false) { + if (($foundEntity = $this->em->getUnitOfWork()->tryGetById($identifier, $assoc['targetEntity'])) !== false) { return $foundEntity; } @@ -763,7 +760,7 @@ public function loadOneToOneEntity(array $assoc, $sourceEntity, array $identifie $hints = []; if ($isInverseSingleValued) { - $hints['fetched']["r"][$assoc['inversedBy']] = true; + $hints['fetched']['r'][$assoc['inversedBy']] = true; } /* cascade read-only status @@ -789,9 +786,10 @@ public function loadOneToOneEntity(array $assoc, $sourceEntity, array $identifie // TRICKY: since the association is specular source and target are flipped foreach ($owningAssoc['targetToSourceKeyColumns'] as $sourceKeyColumn => $targetKeyColumn) { - if ( ! isset($sourceClass->fieldNames[$sourceKeyColumn])) { + if (! isset($sourceClass->fieldNames[$sourceKeyColumn])) { throw MappingException::joinColumnMustPointToMappedField( - $sourceClass->name, $sourceKeyColumn + $sourceClass->name, + $sourceKeyColumn ); } @@ -813,9 +811,9 @@ public function loadOneToOneEntity(array $assoc, $sourceEntity, array $identifie */ public function refresh(array $id, $entity, $lockMode = null) { - $sql = $this->getSelectSQL($id, null, $lockMode); + $sql = $this->getSelectSQL($id, null, $lockMode); [$params, $types] = $this->expandParameters($id); - $stmt = $this->conn->executeQuery($sql, $params, $types); + $stmt = $this->conn->executeQuery($sql, $params, $types); $hydrator = $this->em->newHydrator(Query::HYDRATE_OBJECT); $hydrator->hydrateAll($stmt, $this->currentPersisterContext->rsm, [Query::HINT_REFRESH => true]); @@ -847,11 +845,10 @@ public function loadCriteria(Criteria $criteria) [$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); + $hydrator = $this->em->newHydrator($this->currentPersisterContext->selectJoinSql ? Query::HYDRATE_OBJECT : Query::HYDRATE_SIMPLEOBJECT); - return $hydrator->hydrateAll($stmt, $this->currentPersisterContext->rsm, [UnitOfWork::HINT_DEFEREAGERLOAD => true] - ); + return $hydrator->hydrateAll($stmt, $this->currentPersisterContext->rsm, [UnitOfWork::HINT_DEFEREAGERLOAD => true]); } /** @@ -879,7 +876,7 @@ public function expandCriteriaParameters(Criteria $criteria) foreach ($types as $type) { [$field, $value] = $type; - $sqlTypes = array_merge($sqlTypes, $this->getTypes($field, $value, $this->class)); + $sqlTypes = array_merge($sqlTypes, $this->getTypes($field, $value, $this->class)); } return [$sqlParams, $sqlTypes]; @@ -888,18 +885,17 @@ 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 = null, $limit = null, $offset = null) { $this->switchPersisterContext($offset, $limit); - $sql = $this->getSelectSQL($criteria, null, null, $limit, $offset, $orderBy); + $sql = $this->getSelectSQL($criteria, null, null, $limit, $offset, $orderBy); [$params, $types] = $this->expandParameters($criteria); - $stmt = $this->conn->executeQuery($sql, $params, $types); + $stmt = $this->conn->executeQuery($sql, $params, $types); - $hydrator = $this->em->newHydrator(($this->currentPersisterContext->selectJoinSql) ? Query::HYDRATE_OBJECT : Query::HYDRATE_SIMPLEOBJECT); + $hydrator = $this->em->newHydrator($this->currentPersisterContext->selectJoinSql ? Query::HYDRATE_OBJECT : Query::HYDRATE_SIMPLEOBJECT); - return $hydrator->hydrateAll($stmt, $this->currentPersisterContext->rsm, [UnitOfWork::HINT_DEFEREAGERLOAD => true] - ); + return $hydrator->hydrateAll($stmt, $this->currentPersisterContext->rsm, [UnitOfWork::HINT_DEFEREAGERLOAD => true]); } /** @@ -917,18 +913,18 @@ public function getManyToManyCollection(array $assoc, $sourceEntity, $offset = n /** * Loads an array of entities from a given DBAL statement. * - * @param array $assoc - * @param \Doctrine\DBAL\Statement $stmt + * @param array $assoc + * @param Statement $stmt * * @return array */ private function loadArrayFromStatement($assoc, $stmt) { - $rsm = $this->currentPersisterContext->rsm; - $hints = [UnitOfWork::HINT_DEFEREAGERLOAD => true]; + $rsm = $this->currentPersisterContext->rsm; + $hints = [UnitOfWork::HINT_DEFEREAGERLOAD => true]; if (isset($assoc['indexBy'])) { - $rsm = clone ($this->currentPersisterContext->rsm); // this is necessary because the "default rsm" should be changed. + $rsm = clone $this->currentPersisterContext->rsm; // this is necessary because the "default rsm" should be changed. $rsm->addIndexBy('r', $assoc['indexBy']); } @@ -938,9 +934,9 @@ private function loadArrayFromStatement($assoc, $stmt) /** * Hydrates a collection from a given DBAL statement. * - * @param array $assoc - * @param \Doctrine\DBAL\Statement $stmt - * @param PersistentCollection $coll + * @param array $assoc + * @param Statement $stmt + * @param PersistentCollection $coll * * @return array */ @@ -949,11 +945,11 @@ private function loadCollectionFromStatement($assoc, $stmt, $coll) $rsm = $this->currentPersisterContext->rsm; $hints = [ UnitOfWork::HINT_DEFEREAGERLOAD => true, - 'collection' => $coll + 'collection' => $coll, ]; if (isset($assoc['indexBy'])) { - $rsm = clone ($this->currentPersisterContext->rsm); // this is necessary because the "default rsm" should be changed. + $rsm = clone $this->currentPersisterContext->rsm; // this is necessary because the "default rsm" should be changed. $rsm->addIndexBy('r', $assoc['indexBy']); } @@ -978,19 +974,19 @@ public function loadManyToManyCollection(array $assoc, $sourceEntity, Persistent * * @return \Doctrine\DBAL\Driver\Statement * - * @throws \Doctrine\ORM\Mapping\MappingException + * @throws MappingException */ private function getManyToManyStatement(array $assoc, $sourceEntity, $offset = null, $limit = null) { $this->switchPersisterContext($offset, $limit); - $sourceClass = $this->em->getClassMetadata($assoc['sourceEntity']); - $class = $sourceClass; - $association = $assoc; - $criteria = []; - $parameters = []; + $sourceClass = $this->em->getClassMetadata($assoc['sourceEntity']); + $class = $sourceClass; + $association = $assoc; + $criteria = []; + $parameters = []; - if ( ! $assoc['isOwningSide']) { + if (! $assoc['isOwningSide']) { $class = $this->em->getClassMetadata($assoc['targetEntity']); $association = $class->associationMappings[$assoc['mappedBy']]; } @@ -1002,8 +998,8 @@ private function getManyToManyStatement(array $assoc, $sourceEntity, $offset = n $quotedJoinTable = $this->quoteStrategy->getJoinTableName($association, $class, $this->platform); foreach ($joinColumns as $joinColumn) { - $sourceKeyColumn = $joinColumn['referencedColumnName']; - $quotedKeyColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform); + $sourceKeyColumn = $joinColumn['referencedColumnName']; + $quotedKeyColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform); switch (true) { case $sourceClass->containsForeignIdentifier: @@ -1025,19 +1021,20 @@ private function getManyToManyStatement(array $assoc, $sourceEntity, $offset = n default: throw MappingException::joinColumnMustPointToMappedField( - $sourceClass->name, $sourceKeyColumn + $sourceClass->name, + $sourceKeyColumn ); } $criteria[$quotedJoinTable . '.' . $quotedKeyColumn] = $value; - $parameters[] = [ + $parameters[] = [ 'value' => $value, 'field' => $field, 'class' => $sourceClass, ]; } - $sql = $this->getSelectSQL($criteria, $assoc, null, $limit, $offset); + $sql = $this->getSelectSQL($criteria, $assoc, null, $limit, $offset); [$params, $types] = $this->expandToManyParameters($parameters); return $this->conn->executeQuery($sql, $params, $types); @@ -1046,7 +1043,7 @@ 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, $assoc = null, $lockMode = null, $limit = null, $offset = null, ?array $orderBy = null) { $this->switchPersisterContext($offset, $limit); @@ -1054,7 +1051,7 @@ public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit $joinSql = ''; $orderBySql = ''; - if ($assoc != null && $assoc['type'] == ClassMetadata::MANY_TO_MANY) { + if ($assoc !== null && $assoc['type'] === ClassMetadata::MANY_TO_MANY) { $joinSql = $this->getSelectManyToManyJoinSQL($assoc); } @@ -1066,7 +1063,7 @@ public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit $orderBySql = $this->getOrderBySQL($orderBy, $this->getSQLTableAlias($this->class->name)); } - $conditionSql = ($criteria instanceof Criteria) + $conditionSql = $criteria instanceof Criteria ? $this->getSelectConditionCriteriaSQL($criteria) : $this->getSelectConditionSQL($criteria, $assoc); @@ -1085,14 +1082,14 @@ public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit $filterSql = $this->generateFilterConditionSQL($this->class, $tableAlias); $tableName = $this->quoteStrategy->getTableName($this->class, $this->platform); - if ('' !== $filterSql) { + if ($filterSql !== '') { $conditionSql = $conditionSql ? $conditionSql . ' AND ' . $filterSql : $filterSql; } $select = 'SELECT ' . $columnList; - $from = ' FROM ' . $tableName . ' '. $tableAlias; + $from = ' FROM ' . $tableName . ' ' . $tableAlias; $join = $this->currentPersisterContext->selectJoinSql . $joinSql; $where = ($conditionSql ? ' WHERE ' . $conditionSql : ''); $lock = $this->platform->appendLockHint($from, $lockMode); @@ -1113,23 +1110,21 @@ public function getCountSQL($criteria = []) $tableName = $this->quoteStrategy->getTableName($this->class, $this->platform); $tableAlias = $this->getSQLTableAlias($this->class->name); - $conditionSql = ($criteria instanceof Criteria) + $conditionSql = $criteria instanceof Criteria ? $this->getSelectConditionCriteriaSQL($criteria) : $this->getSelectConditionSQL($criteria); $filterSql = $this->generateFilterConditionSQL($this->class, $tableAlias); - if ('' !== $filterSql) { + if ($filterSql !== '') { $conditionSql = $conditionSql ? $conditionSql . ' AND ' . $filterSql : $filterSql; } - $sql = 'SELECT COUNT(*) ' + return 'SELECT COUNT(*) ' . 'FROM ' . $tableName . ' ' . $tableAlias . (empty($conditionSql) ? '' : ' WHERE ' . $conditionSql); - - return $sql; } /** @@ -1138,19 +1133,16 @@ public function getCountSQL($criteria = []) * @param array $orderBy * @param string $baseTableAlias * - * @return string - * - * @throws \Doctrine\ORM\ORMException + * @throws ORMException */ - final protected function getOrderBySQL(array $orderBy, $baseTableAlias) : string + final protected function getOrderBySQL(array $orderBy, $baseTableAlias): string { $orderByList = []; foreach ($orderBy as $fieldName => $orientation) { - $orientation = strtoupper(trim($orientation)); - if ($orientation != 'ASC' && $orientation != 'DESC') { + if ($orientation !== 'ASC' && $orientation !== 'DESC') { throw ORMException::invalidOrientation($this->class->name, $fieldName); } @@ -1166,8 +1158,7 @@ final protected function getOrderBySQL(array $orderBy, $baseTableAlias) : string } if (isset($this->class->associationMappings[$fieldName])) { - - if ( ! $this->class->associationMappings[$fieldName]['isOwningSide']) { + if (! $this->class->associationMappings[$fieldName]['isOwningSide']) { throw ORMException::invalidFindByInverseAssociation($this->class->name, $fieldName); } @@ -1214,8 +1205,8 @@ protected function getSelectColumnsSQL() $columnList[] = $this->getSelectColumnSQL($field, $this->class); } - $this->currentPersisterContext->selectJoinSql = ''; - $eagerAliasCounter = 0; + $this->currentPersisterContext->selectJoinSql = ''; + $eagerAliasCounter = 0; foreach ($this->class->associationMappings as $assocField => $assoc) { $assocColumnSQL = $this->getSelectColumnAssociationSQL($assocField, $assoc, $this->class); @@ -1227,7 +1218,7 @@ protected function getSelectColumnsSQL() $isAssocToOneInverseSide = $assoc['type'] & ClassMetadata::TO_ONE && ! $assoc['isOwningSide']; $isAssocFromOneEager = $assoc['type'] !== ClassMetadata::MANY_TO_MANY && $assoc['fetch'] === ClassMetadata::FETCH_EAGER; - if ( ! ($isAssocFromOneEager || $isAssocToOneInverseSide)) { + if (! ($isAssocFromOneEager || $isAssocToOneInverseSide)) { continue; } @@ -1237,7 +1228,7 @@ protected function getSelectColumnsSQL() $eagerEntity = $this->em->getClassMetadata($assoc['targetEntity']); - if ($eagerEntity->inheritanceType != ClassMetadata::INHERITANCE_TYPE_NONE) { + if ($eagerEntity->inheritanceType !== ClassMetadata::INHERITANCE_TYPE_NONE) { continue; // now this is why you shouldn't use inheritance } @@ -1250,7 +1241,10 @@ protected function getSelectColumnsSQL() foreach ($eagerEntity->associationMappings as $eagerAssocField => $eagerAssoc) { $eagerAssocColumnSQL = $this->getSelectColumnAssociationSQL( - $eagerAssocField, $eagerAssoc, $eagerEntity, $assocAlias + $eagerAssocField, + $eagerAssoc, + $eagerEntity, + $assocAlias ); if ($eagerAssocColumnSQL) { @@ -1258,14 +1252,14 @@ protected function getSelectColumnsSQL() } } - $association = $assoc; - $joinCondition = []; + $association = $assoc; + $joinCondition = []; if (isset($assoc['indexBy'])) { $this->currentPersisterContext->rsm->addIndexBy($assocAlias, $assoc['indexBy']); } - if ( ! $assoc['isOwningSide']) { + if (! $assoc['isOwningSide']) { $eagerEntity = $this->em->getClassMetadata($assoc['targetEntity']); $association = $eagerEntity->getAssociationMapping($assoc['mappedBy']); } @@ -1274,7 +1268,7 @@ protected function getSelectColumnsSQL() $joinTableName = $this->quoteStrategy->getTableName($eagerEntity, $this->platform); if ($assoc['isOwningSide']) { - $tableAlias = $this->getSQLTableAlias($association['targetEntity'], $assocAlias); + $tableAlias = $this->getSQLTableAlias($association['targetEntity'], $assocAlias); $this->currentPersisterContext->selectJoinSql .= ' ' . $this->getJoinSQLForJoinColumns($association['joinColumns']); foreach ($association['joinColumns'] as $joinColumn) { @@ -1288,14 +1282,12 @@ protected function getSelectColumnsSQL() if ($filterSql = $this->generateFilterConditionSQL($eagerEntity, $tableAlias)) { $joinCondition[] = $filterSql; } - } else { - $this->currentPersisterContext->selectJoinSql .= ' LEFT JOIN'; foreach ($association['joinColumns'] as $joinColumn) { - $sourceCol = $this->quoteStrategy->getJoinColumnName($joinColumn, $this->class, $this->platform); - $targetCol = $this->quoteStrategy->getReferencedJoinColumnName($joinColumn, $this->class, $this->platform); + $sourceCol = $this->quoteStrategy->getJoinColumnName($joinColumn, $this->class, $this->platform); + $targetCol = $this->quoteStrategy->getReferencedJoinColumnName($joinColumn, $this->class, $this->platform); $joinCondition[] = $this->getSQLTableAlias($association['sourceEntity'], $assocAlias) . '.' . $sourceCol . ' = ' . $this->getSQLTableAlias($association['targetEntity']) . '.' . $targetCol; @@ -1314,23 +1306,22 @@ 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 array $assoc + * @param string $alias * * @return string */ protected function getSelectColumnAssociationSQL($field, $assoc, ClassMetadata $class, $alias = 'r') { - if ( ! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) ) { + if (! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE)) { return ''; } $columnList = []; $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); $isIdentifier = isset($assoc['id']) && $assoc['id'] === true; - $sqlTableAlias = $this->getSQLTableAlias($class->name, ($alias == 'r' ? '' : $alias)); + $sqlTableAlias = $this->getSQLTableAlias($class->name, ($alias === 'r' ? '' : $alias)); foreach ($assoc['joinColumns'] as $joinColumn) { $quotedColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $this->class, $this->platform); @@ -1355,17 +1346,17 @@ protected function getSelectColumnAssociationSQL($field, $assoc, ClassMetadata $ */ protected function getSelectManyToManyJoinSQL(array $manyToMany) { - $conditions = []; - $association = $manyToMany; - $sourceTableAlias = $this->getSQLTableAlias($this->class->name); + $conditions = []; + $association = $manyToMany; + $sourceTableAlias = $this->getSQLTableAlias($this->class->name); - if ( ! $manyToMany['isOwningSide']) { - $targetEntity = $this->em->getClassMetadata($manyToMany['targetEntity']); - $association = $targetEntity->associationMappings[$manyToMany['mappedBy']]; + if (! $manyToMany['isOwningSide']) { + $targetEntity = $this->em->getClassMetadata($manyToMany['targetEntity']); + $association = $targetEntity->associationMappings[$manyToMany['mappedBy']]; } - $joinTableName = $this->quoteStrategy->getJoinTableName($association, $this->class, $this->platform); - $joinColumns = ($manyToMany['isOwningSide']) + $joinTableName = $this->quoteStrategy->getJoinTableName($association, $this->class, $this->platform); + $joinColumns = $manyToMany['isOwningSide'] ? $association['joinTable']['inverseJoinColumns'] : $association['joinTable']['joinColumns']; @@ -1403,9 +1394,11 @@ public function getInsertSQL() foreach ($columns as $column) { $placeholder = '?'; - if (isset($this->class->fieldNames[$column]) + if ( + isset($this->class->fieldNames[$column]) && isset($this->columnTypes[$this->class->fieldNames[$column]]) - && isset($this->class->fieldMappings[$this->class->fieldNames[$column]]['requireSQLConversion'])) { + && isset($this->class->fieldMappings[$this->class->fieldNames[$column]]['requireSQLConversion']) + ) { $type = Type::getType($this->columnTypes[$this->class->fieldNames[$column]]); $placeholder = $type->convertToDatabaseValueSQL('?', $this->platform); } @@ -1436,7 +1429,7 @@ protected function getInsertColumnList() $columns = []; foreach ($this->class->reflFields as $name => $field) { - if ($this->class->isVersioned && $this->class->versionField == $name) { + if ($this->class->isVersioned && $this->class->versionField === $name) { continue; } @@ -1456,7 +1449,7 @@ protected function getInsertColumnList() continue; } - if (! $this->class->isIdGeneratorIdentity() || $this->class->identifier[0] != $name) { + 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']; } @@ -1477,7 +1470,7 @@ protected function getInsertColumnList() */ protected function getSelectColumnSQL($field, ClassMetadata $class, $alias = 'r') { - $root = $alias == 'r' ? '' : $alias ; + $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)); @@ -1534,14 +1527,13 @@ public function lock(array $criteria, $lockMode) break; case LockMode::PESSIMISTIC_WRITE: - $lockSql = $this->platform->getWriteLockSQL(); break; } $lock = $this->getLockTablesSql($lockMode); $where = ($conditionSql ? ' WHERE ' . $conditionSql : '') . ' '; - $sql = 'SELECT 1 ' + $sql = 'SELECT 1 ' . $lock . $where . $lockSql; @@ -1571,8 +1563,6 @@ protected function getLockTablesSql($lockMode) /** * Gets the Select Where Condition from a Criteria object. * - * @param \Doctrine\Common\Collections\Criteria $criteria - * * @return string */ protected function getSelectConditionCriteriaSQL(Criteria $criteria) @@ -1612,15 +1602,15 @@ public function getSelectConditionStatementSQL($field, $value, $assoc = null, $c $placeholder = $type->convertToDatabaseValueSQL($placeholder, $this->platform); } - if (null !== $comparison) { + if ($comparison !== null) { // special case null value handling - if (($comparison === Comparison::EQ || $comparison === Comparison::IS) && null ===$value) { + if (($comparison === Comparison::EQ || $comparison === Comparison::IS) && $value === null) { $selectedColumns[] = $column . ' IS NULL'; continue; } - if ($comparison === Comparison::NEQ && null === $value) { + if ($comparison === Comparison::NEQ && $value === null) { $selectedColumns[] = $column . ' IS NOT NULL'; continue; @@ -1634,7 +1624,7 @@ public function getSelectConditionStatementSQL($field, $value, $assoc = null, $c if (is_array($value)) { $in = sprintf('%s IN (%s)', $column, $placeholder); - if (false !== array_search(null, $value, true)) { + if (array_search(null, $value, true) !== false) { $selectedColumns[] = sprintf('(%s OR %s IS NULL)', $in, $column); continue; @@ -1645,7 +1635,7 @@ public function getSelectConditionStatementSQL($field, $value, $assoc = null, $c continue; } - if (null === $value) { + if ($value === null) { $selectedColumns[] = sprintf('%s IS NULL', $column); continue; @@ -1665,7 +1655,7 @@ public function getSelectConditionStatementSQL($field, $value, $assoc = null, $c * * @return string[] * - * @throws \Doctrine\ORM\ORMException + * @throws ORMException * * @psalm-return list */ @@ -1684,7 +1674,7 @@ private function getSelectConditionStatementColumnSQL($field, $assoc = null) $class = $this->class; if ($association['type'] === ClassMetadata::MANY_TO_MANY) { - if ( ! $association['isOwningSide']) { + if (! $association['isOwningSide']) { $association = $assoc; } @@ -1693,28 +1683,25 @@ private function getSelectConditionStatementColumnSQL($field, $assoc = null) ? $association['joinTable']['joinColumns'] : $association['joinTable']['inverseJoinColumns']; - foreach ($joinColumns as $joinColumn) { $columns[] = $joinTableName . '.' . $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform); } - } else { - if ( ! $association['isOwningSide']) { + if (! $association['isOwningSide']) { throw ORMException::invalidFindByInverseAssociation($this->class->name, $field); } - $className = (isset($association['inherited'])) - ? $association['inherited'] - : $this->class->name; + $className = $association['inherited'] ?? $this->class->name; foreach ($association['joinColumns'] as $joinColumn) { $columns[] = $this->getSQLTableAlias($className) . '.' . $this->quoteStrategy->getJoinColumnName($joinColumn, $this->class, $this->platform); } } + return $columns; } - if ($assoc !== null && strpos($field, " ") === false && strpos($field, "(") === false) { + if ($assoc !== 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. @@ -1778,7 +1765,7 @@ public function loadOneToManyCollection(array $assoc, $sourceEntity, PersistentC * @param int|null $offset * @param int|null $limit * - * @return \Doctrine\DBAL\Statement + * @return Statement */ private function getOneToManyStatement(array $assoc, $sourceEntity, $offset = null, $limit = null) { @@ -1800,7 +1787,7 @@ private function getOneToManyStatement(array $assoc, $sourceEntity, $offset = nu $value = $value[$this->em->getClassMetadata($sourceClass->associationMappings[$field]['targetEntity'])->identifier[0]]; } - $criteria[$tableAlias . "." . $targetKeyColumn] = $value; + $criteria[$tableAlias . '.' . $targetKeyColumn] = $value; $parameters[] = [ 'value' => $value, 'field' => $field, @@ -1813,16 +1800,15 @@ private function getOneToManyStatement(array $assoc, $sourceEntity, $offset = nu $field = $sourceClass->fieldNames[$sourceKeyColumn]; $value = $sourceClass->reflFields[$field]->getValue($sourceEntity); - $criteria[$tableAlias . "." . $targetKeyColumn] = $value; - $parameters[] = [ + $criteria[$tableAlias . '.' . $targetKeyColumn] = $value; + $parameters[] = [ 'value' => $value, 'field' => $field, 'class' => $sourceClass, ]; - } - $sql = $this->getSelectSQL($criteria, $assoc, null, $limit, $offset); + $sql = $this->getSelectSQL($criteria, $assoc, null, $limit, $offset); [$params, $types] = $this->expandToManyParameters($parameters); return $this->conn->executeQuery($sql, $params, $types); @@ -1881,26 +1867,25 @@ private function expandToManyParameters($criteria) /** * Infers field types to be used by parameter type casting. * - * @param string $field - * @param mixed $value - * @param ClassMetadata $class + * @param string $field + * @param mixed $value * * @return int[]|null[]|string[] * - * @throws \Doctrine\ORM\Query\QueryException + * @throws QueryException * - * @psalm-return list + * @psalm-return list<(int|string|null)> */ private function getTypes($field, $value, ClassMetadata $class) { $types = []; switch (true) { - case (isset($class->fieldMappings[$field])): + case isset($class->fieldMappings[$field]): $types = array_merge($types, [$class->fieldMappings[$field]['type']]); break; - case (isset($class->associationMappings[$field])): + case isset($class->associationMappings[$field]): $assoc = $class->associationMappings[$field]; $class = $this->em->getClassMetadata($assoc['targetEntity']); @@ -1913,9 +1898,10 @@ private function getTypes($field, $value, ClassMetadata $class) ? $assoc['relationToTargetKeyColumns'] : $assoc['sourceToTargetKeyColumns']; - foreach ($columns as $column){ + foreach ($columns as $column) { $types[] = PersisterHelper::getTypeOfColumn($column, $class, $this->em); } + break; default: @@ -1924,7 +1910,7 @@ private function getTypes($field, $value, ClassMetadata $class) } if (is_array($value)) { - return array_map(function ($type) { + return array_map(static function ($type) { $type = Type::getType($type); return $type->getBindingType() + Connection::ARRAY_PARAM_OFFSET; @@ -1978,7 +1964,7 @@ private function getValues($value) */ private function getIndividualValue($value) { - if ( ! is_object($value) || ! $this->em->getMetadataFactory()->hasMetadataFor(ClassUtils::getClass($value))) { + if (! is_object($value) || ! $this->em->getMetadataFactory()->hasMetadataFor(ClassUtils::getClass($value))) { return $value; } @@ -1988,11 +1974,11 @@ private function getIndividualValue($value) /** * {@inheritdoc} */ - public function exists($entity, Criteria $extraConditions = null) + public function exists($entity, ?Criteria $extraConditions = null) { $criteria = $this->class->getIdentifierValues($entity); - if ( ! $criteria) { + if (! $criteria) { return false; } @@ -2004,8 +1990,8 @@ public function exists($entity, Criteria $extraConditions = null) [$params, $types] = $this->expandParameters($criteria); - if (null !== $extraConditions) { - $sql .= ' AND ' . $this->getSelectConditionCriteriaSQL($extraConditions); + if ($extraConditions !== null) { + $sql .= ' AND ' . $this->getSelectConditionCriteriaSQL($extraConditions); [$criteriaParams, $criteriaTypes] = $this->expandCriteriaParameters($extraConditions); $params = array_merge($params, $criteriaParams); @@ -2030,9 +2016,9 @@ protected function getJoinSQLForJoinColumns($joinColumns) { // if one of the join columns is nullable, return left join foreach ($joinColumns as $joinColumn) { - if ( ! isset($joinColumn['nullable']) || $joinColumn['nullable']) { - return 'LEFT JOIN'; - } + if (! isset($joinColumn['nullable']) || $joinColumn['nullable']) { + return 'LEFT JOIN'; + } } return 'INNER JOIN'; @@ -2068,7 +2054,7 @@ protected function generateFilterConditionSQL(ClassMetadata $targetEntity, $targ $sql = implode(' AND ', $filterClauses); - return $sql ? "(" . $sql . ")" : ""; // Wrap again to avoid "X or Y and FilterConditionSQL" + return $sql ? '(' . $sql . ')' : ''; // Wrap again to avoid "X or Y and FilterConditionSQL" } /** @@ -2076,12 +2062,12 @@ protected function generateFilterConditionSQL(ClassMetadata $targetEntity, $targ * * This is due to the fact that to-many associations cannot be fetch-joined when a limit is involved * - * @param null|int $offset - * @param null|int $limit + * @param int|null $offset + * @param int|null $limit */ protected function switchPersisterContext($offset, $limit) { - if (null === $offset && null === $limit) { + if ($offset === null && $limit === null) { $this->currentPersisterContext = $this->noLimitsContext; return; @@ -2093,12 +2079,12 @@ protected function switchPersisterContext($offset, $limit) /** * @return string[] */ - protected function getClassIdentifiersTypes(ClassMetadata $class) : array + protected function getClassIdentifiersTypes(ClassMetadata $class): array { $entityManager = $this->em; return array_map( - static function ($fieldName) use ($class, $entityManager) : string { + static function ($fieldName) use ($class, $entityManager): string { $types = PersisterHelper::getTypeOfField($fieldName, $class, $entityManager); assert(isset($types[0])); diff --git a/lib/Doctrine/ORM/Persisters/Entity/CachedPersisterContext.php b/lib/Doctrine/ORM/Persisters/Entity/CachedPersisterContext.php index c4cc2a4a713..162214106ae 100644 --- a/lib/Doctrine/ORM/Persisters/Entity/CachedPersisterContext.php +++ b/lib/Doctrine/ORM/Persisters/Entity/CachedPersisterContext.php @@ -1,4 +1,5 @@ */ class CachedPersisterContext { @@ -45,7 +44,7 @@ class CachedPersisterContext /** * ResultSetMapping that is used for all queries. Is generated lazily once per request. * - * @var \Doctrine\ORM\Query\ResultSetMapping + * @var ResultSetMapping */ public $rsm; @@ -68,7 +67,7 @@ class CachedPersisterContext /** * Counter for creating unique SQL table and column aliases. * - * @var integer + * @var int */ public $sqlAliasCounter = 0; @@ -87,9 +86,7 @@ class CachedPersisterContext public $handlesLimits; /** - * @param ClassMetadata $class - * @param ResultSetMapping $rsm - * @param bool $handlesLimits + * @param bool $handlesLimits */ public function __construct( ClassMetadata $class, diff --git a/lib/Doctrine/ORM/Persisters/Entity/EntityPersister.php b/lib/Doctrine/ORM/Persisters/Entity/EntityPersister.php index 8840f9db4b9..a3b1723c2e0 100644 --- a/lib/Doctrine/ORM/Persisters/Entity/EntityPersister.php +++ b/lib/Doctrine/ORM/Persisters/Entity/EntityPersister.php @@ -1,4 +1,5 @@ - * @since 2.5 */ interface EntityPersister { /** - * @return \Doctrine\ORM\Mapping\ClassMetadata + * @return ClassMetadata */ public function getClassMetadata(); /** * Gets the ResultSetMapping used for hydration. * - * @return \Doctrine\ORM\Query\ResultSetMapping + * @return ResultSetMapping */ public function getResultSetMapping(); @@ -47,37 +48,37 @@ public function getResultSetMapping(); * Get all queued inserts. * * @return array - */ + */ public function getInserts(); /** - * @TODO - It should not be here. - * But its necessary since JoinedSubclassPersister#executeInserts invoke the root persister. - * - * Gets the INSERT SQL used by the persister to persist a new entity. - * - * @return string - */ + * @return string + * + * @TODO - It should not be here. + * But its necessary since JoinedSubclassPersister#executeInserts invoke the root persister. + * + * Gets the INSERT SQL used by the persister to persist a new entity. + */ public function getInsertSQL(); /** * 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 int|null $lockMode - * @param int|null $limit - * @param int|null $offset - * @param array|null $orderBy + * @param array|Criteria $criteria + * @param array|null $assoc + * @param int|null $lockMode + * @param int|null $limit + * @param int|null $offset + * @param array|null $orderBy * * @return string */ - public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit = null, $offset = null, array $orderBy = null); + public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit = null, $offset = null, ?array $orderBy = null); /** * Get the COUNT SQL to count entities (optionally based on a criteria) * - * @param array|\Doctrine\Common\Collections\Criteria $criteria + * @param array|Criteria $criteria * * @return string */ @@ -95,8 +96,6 @@ public function expandParameters($criteria); /** * Expands Criteria Parameters by walking the expressions and grabbing all parameters and types from it. * - * @param \Doctrine\Common\Collections\Criteria $criteria - * * @return array */ public function expandCriteriaParameters(Criteria $criteria); @@ -161,7 +160,7 @@ public function delete($entity); /** * Count entities (optionally filtered by a criteria) * - * @param array|\Doctrine\Common\Collections\Criteria $criteria + * @param array|Criteria $criteria * * @return int */ @@ -197,7 +196,7 @@ public function getOwningTable($fieldName); * * @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, $assoc = null, array $hints = [], $lockMode = null, $limit = null, ?array $orderBy = null); /** * Loads an entity by identifier. @@ -223,7 +222,7 @@ public function loadById(array $identifier, $entity = null); * * @return object The loaded and managed entity instance or NULL if the entity can not be found. * - * @throws \Doctrine\ORM\Mapping\MappingException + * @throws MappingException */ public function loadOneToOneEntity(array $assoc, $sourceEntity, array $identifier = []); @@ -244,8 +243,6 @@ public function refresh(array $id, $entity, $lockMode = null); /** * Loads Entities matching the given Criteria object. * - * @param \Doctrine\Common\Collections\Criteria $criteria - * * @return array */ public function loadCriteria(Criteria $criteria); @@ -260,7 +257,7 @@ public function loadCriteria(Criteria $criteria); * * @return array */ - public function loadAll(array $criteria = [], array $orderBy = null, $limit = null, $offset = null); + public function loadAll(array $criteria = [], ?array $orderBy = null, $limit = null, $offset = null); /** * Gets (sliced or full) elements of the given collection. @@ -279,7 +276,7 @@ public function getManyToManyCollection(array $assoc, $sourceEntity, $offset = n * * @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 PersistentCollection $collection The collection to fill. * * @return array */ @@ -321,10 +318,9 @@ public function getOneToManyCollection(array $assoc, $sourceEntity, $offset = nu /** * Checks whether the given managed entity exists in the database. * - * @param object $entity - * @param Criteria|null $extraConditions + * @param object $entity * - * @return boolean TRUE if the entity exists in the database, FALSE otherwise. + * @return bool TRUE if the entity exists in the database, FALSE otherwise. */ - public function exists($entity, Criteria $extraConditions = null); + public function exists($entity, ?Criteria $extraConditions = null); } diff --git a/lib/Doctrine/ORM/Persisters/Entity/JoinedSubclassPersister.php b/lib/Doctrine/ORM/Persisters/Entity/JoinedSubclassPersister.php index 65e1b4efb6a..49c47f465d2 100644 --- a/lib/Doctrine/ORM/Persisters/Entity/JoinedSubclassPersister.php +++ b/lib/Doctrine/ORM/Persisters/Entity/JoinedSubclassPersister.php @@ -1,4 +1,5 @@ Class Table Inheritance strategy. * - * @author Roman Borschel - * @author Benjamin Eberlei - * @author Alexander - * @since 2.0 * @see http://martinfowler.com/eaaCatalog/classTableInheritance.html */ class JoinedSubclassPersister extends AbstractEntityInheritancePersister @@ -61,7 +59,7 @@ class JoinedSubclassPersister extends AbstractEntityInheritancePersister */ protected function getDiscriminatorColumnTableName() { - $class = ($this->class->name !== $this->class->rootEntityName) + $class = $this->class->name !== $this->class->rootEntityName ? $this->em->getClassMetadata($this->class->rootEntityName) : $this->class; @@ -72,7 +70,7 @@ protected function getDiscriminatorColumnTableName() * This function finds the ClassMetadata instance in an inheritance hierarchy * that is responsible for enabling versioning. * - * @return \Doctrine\ORM\Mapping\ClassMetadata + * @return ClassMetadata */ private function getVersionedClassMetadata() { @@ -114,8 +112,8 @@ public function getOwningTable($fieldName) break; } - $tableName = $cm->getTableName(); - $quotedTableName = $this->quoteStrategy->getTableName($cm, $this->platform); + $tableName = $cm->getTableName(); + $quotedTableName = $this->quoteStrategy->getTableName($cm, $this->platform); $this->owningTableMap[$fieldName] = $tableName; $this->quotedTableMap[$tableName] = $quotedTableName; @@ -128,14 +126,14 @@ public function getOwningTable($fieldName) */ public function executeInserts() { - if ( ! $this->queuedInserts) { + if (! $this->queuedInserts) { return []; } $postInsertIds = []; $idGenerator = $this->class->idGenerator; $isPostInsertId = $idGenerator->isPostInsertGenerator(); - $rootClass = ($this->class->name !== $this->class->rootEntityName) + $rootClass = $this->class->name !== $this->class->rootEntityName ? $this->em->getClassMetadata($this->class->rootEntityName) : $this->class; @@ -152,11 +150,11 @@ public function executeInserts() } foreach ($this->class->parentClasses as $parentClassName) { - $parentClass = $this->em->getClassMetadata($parentClassName); + $parentClass = $this->em->getClassMetadata($parentClassName); $parentTableName = $parentClass->getTableName(); if ($parentClass !== $rootClass) { - $parentPersister = $this->em->getUnitOfWork()->getEntityPersister($parentClassName); + $parentPersister = $this->em->getUnitOfWork()->getEntityPersister($parentClassName); $subTableStmts[$parentTableName] = $this->conn->prepare($parentPersister->getInsertSQL()); } } @@ -177,10 +175,8 @@ public function executeInserts() $rootTableStmt->execute(); if ($isPostInsertId) { - $generatedId = $idGenerator->generate($this->em, $entity); - $id = [ - $this->class->identifier[0] => $generatedId - ]; + $generatedId = $idGenerator->generate($this->em, $entity); + $id = [$this->class->identifier[0] => $generatedId]; $postInsertIds[] = [ 'generatedId' => $generatedId, 'entity' => $entity, @@ -196,18 +192,18 @@ public function executeInserts() // 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 */ + /** @var Statement $stmt */ $paramIndex = 1; $data = $insertData[$tableName] ?? []; foreach ((array) $id as $idName => $idVal) { - $type = isset($this->columnTypes[$idName]) ? $this->columnTypes[$idName] : Type::STRING; + $type = $this->columnTypes[$idName] ?? Type::STRING; $stmt->bindValue($paramIndex++, $idVal, $type); } foreach ($data as $columnName => $value) { - if (!is_array($id) || !isset($id[$columnName])) { + if (! is_array($id) || ! isset($id[$columnName])) { $stmt->bindValue($paramIndex++, $value, $this->columnTypes[$columnName]); } } @@ -234,7 +230,7 @@ public function update($entity) { $updateData = $this->prepareUpdateData($entity); - if ( ! $updateData) { + if (! $updateData) { return; } @@ -242,8 +238,8 @@ public function update($entity) return; } - $versionedClass = $this->getVersionedClassMetadata(); - $versionedTable = $versionedClass->getTableName(); + $versionedClass = $this->getVersionedClassMetadata(); + $versionedTable = $versionedClass->getTableName(); foreach ($updateData as $tableName => $data) { $tableName = $this->quotedTableMap[$tableName]; @@ -255,7 +251,7 @@ public function update($entity) // Make sure the table with the version column is updated even if no columns on that // table were affected. if ($isVersioned) { - if ( ! isset($updateData[$versionedTable])) { + if (! isset($updateData[$versionedTable])) { $tableName = $this->quoteStrategy->getTableName($versionedClass, $this->platform); $this->updateTable($entity, $tableName, [], true); @@ -307,18 +303,18 @@ public function delete($entity) /** * {@inheritdoc} */ - public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit = null, $offset = null, array $orderBy = null) + public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit = null, $offset = null, ?array $orderBy = null) { $this->switchPersisterContext($offset, $limit); $baseTableAlias = $this->getSQLTableAlias($this->class->name); $joinSql = $this->getJoinSql($baseTableAlias); - if ($assoc != null && $assoc['type'] == ClassMetadata::MANY_TO_MANY) { + if ($assoc !== null && $assoc['type'] === ClassMetadata::MANY_TO_MANY) { $joinSql .= $this->getSelectManyToManyJoinSQL($assoc); } - $conditionSql = ($criteria instanceof Criteria) + $conditionSql = $criteria instanceof Criteria ? $this->getSelectConditionCriteriaSQL($criteria) : $this->getSelectConditionSQL($criteria, $assoc); @@ -343,13 +339,11 @@ public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit switch ($lockMode) { case LockMode::PESSIMISTIC_READ: - $lockSql = ' ' . $this->platform->getReadLockSQL(); break; case LockMode::PESSIMISTIC_WRITE: - $lockSql = ' ' . $this->platform->getWriteLockSQL(); break; @@ -357,10 +351,10 @@ public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit $tableName = $this->quoteStrategy->getTableName($this->class, $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 + $query = 'SELECT ' . $columnList . $lock . $joinSql . $where @@ -378,24 +372,22 @@ public function getCountSQL($criteria = []) $baseTableAlias = $this->getSQLTableAlias($this->class->name); $joinSql = $this->getJoinSql($baseTableAlias); - $conditionSql = ($criteria instanceof Criteria) + $conditionSql = $criteria instanceof Criteria ? $this->getSelectConditionCriteriaSQL($criteria) : $this->getSelectConditionSQL($criteria); $filterSql = $this->generateFilterConditionSQL($this->em->getClassMetadata($this->class->rootEntityName), $this->getSQLTableAlias($this->class->rootEntityName)); - if ('' !== $filterSql) { + if ($filterSql !== '') { $conditionSql = $conditionSql ? $conditionSql . ' AND ' . $filterSql : $filterSql; } - $sql = 'SELECT COUNT(*) ' + return 'SELECT COUNT(*) ' . 'FROM ' . $tableName . ' ' . $baseTableAlias . $joinSql . (empty($conditionSql) ? '' : ' WHERE ' . $conditionSql); - - return $sql; } /** @@ -403,16 +395,16 @@ public function getCountSQL($criteria = []) */ protected function getLockTablesSql($lockMode) { - $joinSql = ''; - $identifierColumns = $this->class->getIdentifierColumnNames(); - $baseTableAlias = $this->getSQLTableAlias($this->class->name); + $joinSql = ''; + $identifierColumns = $this->class->getIdentifierColumnNames(); + $baseTableAlias = $this->getSQLTableAlias($this->class->name); // 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 '; + $conditions = []; + $tableAlias = $this->getSQLTableAlias($parentClassName); + $parentClass = $this->em->getClassMetadata($parentClassName); + $joinSql .= ' INNER JOIN ' . $this->quoteStrategy->getTableName($parentClass, $this->platform) . ' ' . $tableAlias . ' ON '; foreach ($identifierColumns as $idColumn) { $conditions[] = $baseTableAlias . '.' . $idColumn . ' = ' . $tableAlias . '.' . $idColumn; @@ -436,11 +428,11 @@ 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); + $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->name, 'r'); $this->currentPersisterContext->rsm->setDiscriminatorColumn('r', $resultColumnName); @@ -457,7 +449,7 @@ protected function getSelectColumnsSQL() // Add foreign key columns foreach ($this->class->associationMappings as $mapping) { - if ( ! $mapping['isOwningSide'] || ! ($mapping['type'] & ClassMetadata::TO_ONE)) { + if (! $mapping['isOwningSide'] || ! ($mapping['type'] & ClassMetadata::TO_ONE)) { continue; } @@ -478,7 +470,7 @@ protected function getSelectColumnsSQL() } // Add discriminator column (DO NOT ALIAS, see AbstractEntityInheritancePersister#processSQLResult). - $tableAlias = ($this->class->rootEntityName == $this->class->name) + $tableAlias = $this->class->rootEntityName === $this->class->name ? $baseTableAlias : $this->getSQLTableAlias($this->class->rootEntityName); @@ -500,9 +492,11 @@ protected function getSelectColumnsSQL() // Add join columns (foreign keys) foreach ($subClass->associationMappings as $mapping) { - if ( ! $mapping['isOwningSide'] + if ( + ! $mapping['isOwningSide'] || ! ($mapping['type'] & ClassMetadata::TO_ONE) - || isset($mapping['inherited'])) { + || isset($mapping['inherited']) + ) { continue; } @@ -535,11 +529,13 @@ protected function getInsertColumnList() : []; foreach ($this->class->reflFields as $name => $field) { - if (isset($this->class->fieldMappings[$name]['inherited']) + 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])) { + || ($this->class->isVersioned && $this->class->versionField === $name) + || isset($this->class->embeddedClasses[$name]) + ) { continue; } @@ -550,15 +546,17 @@ protected function getInsertColumnList() $columns[] = $sourceCol; } } - } 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']; + } elseif ( + $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']; } } // Add discriminator column if it is the topmost class. - if ($this->class->name == $this->class->rootEntityName) { + if ($this->class->name === $this->class->rootEntityName) { $columns[] = $this->class->discriminatorColumn['name']; } @@ -586,11 +584,10 @@ private function getJoinSql($baseTableAlias) // INNER JOIN parent tables foreach ($this->class->parentClasses as $parentClassName) { - $conditions = []; - $parentClass = $this->em->getClassMetadata($parentClassName); - $tableAlias = $this->getSQLTableAlias($parentClassName); - $joinSql .= ' INNER JOIN ' . $this->quoteStrategy->getTableName($parentClass, $this->platform) . ' ' . $tableAlias . ' ON '; - + $conditions = []; + $parentClass = $this->em->getClassMetadata($parentClassName); + $tableAlias = $this->getSQLTableAlias($parentClassName); + $joinSql .= ' INNER JOIN ' . $this->quoteStrategy->getTableName($parentClass, $this->platform) . ' ' . $tableAlias . ' ON '; foreach ($identifierColumn as $idColumn) { $conditions[] = $baseTableAlias . '.' . $idColumn . ' = ' . $tableAlias . '.' . $idColumn; @@ -601,10 +598,10 @@ private function getJoinSql($baseTableAlias) // OUTER JOIN sub tables foreach ($this->class->subClasses as $subClassName) { - $conditions = []; - $subClass = $this->em->getClassMetadata($subClassName); - $tableAlias = $this->getSQLTableAlias($subClassName); - $joinSql .= ' LEFT JOIN ' . $this->quoteStrategy->getTableName($subClass, $this->platform) . ' ' . $tableAlias . ' ON '; + $conditions = []; + $subClass = $this->em->getClassMetadata($subClassName); + $tableAlias = $this->getSQLTableAlias($subClassName); + $joinSql .= ' LEFT JOIN ' . $this->quoteStrategy->getTableName($subClass, $this->platform) . ' ' . $tableAlias . ' ON '; foreach ($identifierColumn as $idColumn) { $conditions[] = $baseTableAlias . '.' . $idColumn . ' = ' . $tableAlias . '.' . $idColumn; diff --git a/lib/Doctrine/ORM/Persisters/Entity/SingleTablePersister.php b/lib/Doctrine/ORM/Persisters/Entity/SingleTablePersister.php index 4b8352b350c..33104882c95 100644 --- a/lib/Doctrine/ORM/Persisters/Entity/SingleTablePersister.php +++ b/lib/Doctrine/ORM/Persisters/Entity/SingleTablePersister.php @@ -1,4 +1,5 @@ - * @author Benjamin Eberlei - * @author Alexander - * @since 2.0 * @link http://martinfowler.com/eaaCatalog/singleTableInheritance.html */ class SingleTablePersister extends AbstractEntityInheritancePersister @@ -61,7 +61,7 @@ protected function getSelectColumnsSQL() $discrColumn = $this->class->discriminatorColumn['name']; $discrColumnType = $this->class->discriminatorColumn['type']; - $columnList[] = $tableAlias . '.' . $discrColumn; + $columnList[] = $tableAlias . '.' . $discrColumn; $resultColumnName = $this->platform->getSQLResultCasing($discrColumn); @@ -83,7 +83,7 @@ protected function getSelectColumnsSQL() // Foreign key columns foreach ($subClass->associationMappings as $assoc) { - if ( ! $assoc['isOwningSide'] || ! ($assoc['type'] & ClassMetadata::TO_ONE) || isset($assoc['inherited'])) { + if (! $assoc['isOwningSide'] || ! ($assoc['type'] & ClassMetadata::TO_ONE) || isset($assoc['inherited'])) { continue; } diff --git a/lib/Doctrine/ORM/Persisters/PersisterException.php b/lib/Doctrine/ORM/Persisters/PersisterException.php index 09f73b21b5d..7275945325a 100644 --- a/lib/Doctrine/ORM/Persisters/PersisterException.php +++ b/lib/Doctrine/ORM/Persisters/PersisterException.php @@ -1,4 +1,5 @@ - * @since 2.3 */ class SqlExpressionVisitor extends ExpressionVisitor { - /** - * @var \Doctrine\ORM\Persisters\Entity\BasicEntityPersister - */ + /** @var BasicEntityPersister */ private $persister; - /** - * @var \Doctrine\ORM\Mapping\ClassMetadata - */ + /** @var ClassMetadata */ private $classMetadata; - /** - * @param \Doctrine\ORM\Persisters\Entity\BasicEntityPersister $persister - * @param \Doctrine\ORM\Mapping\ClassMetadata $classMetadata - */ public function __construct(BasicEntityPersister $persister, ClassMetadata $classMetadata) { - $this->persister = $persister; + $this->persister = $persister; $this->classMetadata = $classMetadata; } /** * Converts a comparison expression into the target query language output. * - * @param \Doctrine\Common\Collections\Expr\Comparison $comparison - * * @return mixed */ public function walkComparison(Comparison $comparison) @@ -67,11 +59,12 @@ public function walkComparison(Comparison $comparison) $field = $comparison->getField(); $value = $comparison->getValue()->getValue(); // shortcut for walkValue() - if (isset($this->classMetadata->associationMappings[$field]) && + if ( + isset($this->classMetadata->associationMappings[$field]) && $value !== null && ! is_object($value) && - ! in_array($comparison->getOperator(), [Comparison::IN, Comparison::NIN])) { - + ! in_array($comparison->getOperator(), [Comparison::IN, Comparison::NIN]) + ) { throw PersisterException::matchingAssocationFieldRequiresObject($this->classMetadata->name, $field); } @@ -81,11 +74,9 @@ public function walkComparison(Comparison $comparison) /** * Converts a composite expression into the target query language output. * - * @param \Doctrine\Common\Collections\Expr\CompositeExpression $expr - * * @return mixed * - * @throws \RuntimeException + * @throws RuntimeException */ public function walkCompositeExpression(CompositeExpression $expr) { @@ -95,7 +86,7 @@ public function walkCompositeExpression(CompositeExpression $expr) $expressionList[] = $this->dispatch($child); } - switch($expr->getType()) { + switch ($expr->getType()) { case CompositeExpression::TYPE_AND: return '(' . implode(' AND ', $expressionList) . ')'; @@ -103,15 +94,13 @@ public function walkCompositeExpression(CompositeExpression $expr) return '(' . implode(' OR ', $expressionList) . ')'; default: - throw new \RuntimeException("Unknown composite " . $expr->getType()); + throw new RuntimeException('Unknown composite ' . $expr->getType()); } } /** * Converts a value expression into the target query language part. * - * @param \Doctrine\Common\Collections\Expr\Value $value - * * @return mixed */ public function walkValue(Value $value) @@ -119,4 +108,3 @@ public function walkValue(Value $value) return '?'; } } - diff --git a/lib/Doctrine/ORM/Persisters/SqlValueVisitor.php b/lib/Doctrine/ORM/Persisters/SqlValueVisitor.php index 560ea932212..82173a98a81 100644 --- a/lib/Doctrine/ORM/Persisters/SqlValueVisitor.php +++ b/lib/Doctrine/ORM/Persisters/SqlValueVisitor.php @@ -1,4 +1,5 @@ */ class SqlValueVisitor extends ExpressionVisitor { - /** - * @var array - */ + /** @var array */ private $values = []; - /** - * @var array - */ - private $types = []; + /** @var array */ + private $types = []; /** * Converts a comparison expression into the target query language output. * - * @param \Doctrine\Common\Collections\Expr\Comparison $comparison - * * @return void */ public function walkComparison(Comparison $comparison) @@ -56,7 +49,7 @@ public function walkComparison(Comparison $comparison) if (($operator === Comparison::EQ || $operator === Comparison::IS) && $value === null) { return; - } else if ($operator === Comparison::NEQ && $value === null) { + } elseif ($operator === Comparison::NEQ && $value === null) { return; } @@ -67,8 +60,6 @@ public function walkComparison(Comparison $comparison) /** * Converts a composite expression into the target query language output. * - * @param \Doctrine\Common\Collections\Expr\CompositeExpression $expr - * * @return void */ public function walkCompositeExpression(CompositeExpression $expr) @@ -81,8 +72,6 @@ public function walkCompositeExpression(CompositeExpression $expr) /** * Converts a value expression into the target query language part. * - * @param \Doctrine\Common\Collections\Expr\Value $value - * * @return mixed */ public function walkValue(Value $value) @@ -106,7 +95,6 @@ public function getParamsAndTypes() * Returns the value from a Comparison. In case of a CONTAINS comparison, * the value is wrapped in %-signs, because it will be used in a LIKE clause. * - * @param \Doctrine\Common\Collections\Expr\Comparison $comparison * @return mixed */ protected function getValueFromComparison(Comparison $comparison) diff --git a/lib/Doctrine/ORM/PessimisticLockException.php b/lib/Doctrine/ORM/PessimisticLockException.php index d60f7a82177..1df83d93729 100644 --- a/lib/Doctrine/ORM/PessimisticLockException.php +++ b/lib/Doctrine/ORM/PessimisticLockException.php @@ -1,4 +1,5 @@ - * @author Roman Borschel */ class PessimisticLockException extends ORMException { @@ -35,6 +32,6 @@ class PessimisticLockException extends ORMException */ public static function lockFailed() { - return new self("The pessimistic lock failed."); + return new self('The pessimistic lock failed.'); } } diff --git a/lib/Doctrine/ORM/Proxy/Autoloader.php b/lib/Doctrine/ORM/Proxy/Autoloader.php index 9b2e2cdfa1a..de95cbefe1f 100644 --- a/lib/Doctrine/ORM/Proxy/Autoloader.php +++ b/lib/Doctrine/ORM/Proxy/Autoloader.php @@ -1,4 +1,5 @@ - * @since 2.0 - * * @deprecated 2.7 This interface is being removed from the ORM and won't have any replacement, proxies will no longer implement it. */ interface Proxy extends BaseProxy diff --git a/lib/Doctrine/ORM/Proxy/ProxyFactory.php b/lib/Doctrine/ORM/Proxy/ProxyFactory.php index c5a55ac712b..cca943bcb63 100644 --- a/lib/Doctrine/ORM/Proxy/ProxyFactory.php +++ b/lib/Doctrine/ORM/Proxy/ProxyFactory.php @@ -1,4 +1,5 @@ - * @author Giorgio Sironi - * @author Marco Pivetta - * @since 2.0 - * * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement */ class ProxyFactory extends AbstractProxyFactory { - /** - * @var EntityManagerInterface The EntityManager this factory is bound to. - */ + /** @var EntityManagerInterface The EntityManager this factory is bound to. */ private $em; - /** - * @var \Doctrine\ORM\UnitOfWork The UnitOfWork this factory uses to retrieve persisters - */ + /** @var UnitOfWork The UnitOfWork this factory uses to retrieve persisters */ private $uow; - /** - * @var string - */ + /** @var string */ private $proxyNs; /** * The IdentifierFlattener used for manipulating identifiers * - * @var \Doctrine\ORM\Utility\IdentifierFlattener + * @var IdentifierFlattener */ private $identifierFlattener; @@ -72,8 +64,8 @@ class ProxyFactory extends AbstractProxyFactory * @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. + * @param bool|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) { @@ -93,7 +85,7 @@ public function __construct(EntityManagerInterface $em, $proxyDir, $proxyNs, $au */ protected function skipClass(ClassMetadata $metadata) { - /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadataInfo */ + /** @var ClassMetadataInfo $metadata */ return $metadata->isMappedSuperclass || $metadata->isEmbeddedClass || $metadata->getReflectionClass()->isAbstract(); @@ -119,11 +111,11 @@ protected function createProxyDefinition($className) /** * Creates a closure capable of initializing a proxy * - * @return \Closure + * @return Closure * - * @throws \Doctrine\ORM\EntityNotFoundException + * @throws EntityNotFoundException * - * @psalm-return \Closure(BaseProxy):void + * @psalm-return Closure(BaseProxy ): void */ private function createInitializer(ClassMetadata $classMetadata, EntityPersister $entityPersister) { @@ -143,7 +135,7 @@ private function createInitializer(ClassMetadata $classMetadata, EntityPersister $properties = $proxy->__getLazyProperties(); foreach ($properties as $propertyName => $property) { - if ( ! isset($proxy->$propertyName)) { + if (! isset($proxy->$propertyName)) { $proxy->$propertyName = $properties[$propertyName]; } } @@ -156,7 +148,7 @@ private function createInitializer(ClassMetadata $classMetadata, EntityPersister $identifier = $classMetadata->getIdentifierValues($proxy); - if (null === $entityPersister->loadById($identifier, $proxy)) { + if ($entityPersister->loadById($identifier, $proxy) === null) { $proxy->__setInitializer($initializer); $proxy->__setCloner($cloner); $proxy->__setInitialized(false); @@ -172,11 +164,11 @@ private function createInitializer(ClassMetadata $classMetadata, EntityPersister /** * Creates a closure capable of finalizing state a cloned proxy * - * @return \Closure + * @return Closure * - * @throws \Doctrine\ORM\EntityNotFoundException + * @throws EntityNotFoundException * - * @psalm-return \Closure(BaseProxy):void + * @psalm-return Closure(BaseProxy ): void */ private function createCloner(ClassMetadata $classMetadata, EntityPersister $entityPersister) { @@ -192,7 +184,7 @@ private function createCloner(ClassMetadata $classMetadata, EntityPersister $ent $identifier = $classMetadata->getIdentifierValues($proxy); $original = $entityPersister->loadById($identifier); - if (null === $original) { + if ($original === null) { throw EntityNotFoundException::fromClassNameAndIdentifier( $classMetadata->getName(), $this->identifierFlattener->flattenIdentifier($classMetadata, $identifier) @@ -200,7 +192,7 @@ private function createCloner(ClassMetadata $classMetadata, EntityPersister $ent } foreach ($class->getReflectionProperties() as $property) { - if ( ! $class->hasField($property->name) && ! $class->hasAssociation($property->name)) { + if (! $class->hasField($property->name) && ! $class->hasAssociation($property->name)) { continue; } diff --git a/lib/Doctrine/ORM/Query.php b/lib/Doctrine/ORM/Query.php index 6b5ece76de1..8925a3b6e20 100644 --- a/lib/Doctrine/ORM/Query.php +++ b/lib/Doctrine/ORM/Query.php @@ -1,4 +1,5 @@ - * @author Konsta Vesterinen - * @author Roman Borschel */ final class Query extends AbstractQuery { /** * A query object is in CLEAN state when it has NO unparsed/unprocessed DQL parts. */ - const STATE_CLEAN = 1; + public const STATE_CLEAN = 1; /** * A query object is in state DIRTY when it has DQL parts that have not yet been * parsed/processed. This is automatically defined as DIRTY when addDqlQueryPart * is called. */ - const STATE_DIRTY = 2; + public const STATE_DIRTY = 2; /* Query HINTS */ /** * The refresh hint turns any query into a refresh query with the result that * any local changes in entities are overridden with the fetched values. - * - * @var string */ - const HINT_REFRESH = 'doctrine.refresh'; + public const HINT_REFRESH = 'doctrine.refresh'; - /** - * @var string - */ - const HINT_CACHE_ENABLED = 'doctrine.cache.enabled'; + public const HINT_CACHE_ENABLED = 'doctrine.cache.enabled'; - /** - * @var string - */ - const HINT_CACHE_EVICT = 'doctrine.cache.evict'; + public const HINT_CACHE_EVICT = 'doctrine.cache.evict'; /** * Internal hint: is set to the proxy entity that is currently triggered for loading - * - * @var string */ - const HINT_REFRESH_ENTITY = 'doctrine.refresh.entity'; + public const HINT_REFRESH_ENTITY = 'doctrine.refresh.entity'; /** * The forcePartialLoad query hint forces a particular query to return * partial objects. * - * @var string * @todo Rename: HINT_OPTIMIZE */ - const HINT_FORCE_PARTIAL_LOAD = 'doctrine.forcePartialLoad'; + public const HINT_FORCE_PARTIAL_LOAD = 'doctrine.forcePartialLoad'; /** * The includeMetaColumns query hint causes meta columns like foreign keys and * discriminator columns to be selected and returned as part of the query result. * * This hint does only apply to non-object queries. - * - * @var string */ - const HINT_INCLUDE_META_COLUMNS = 'doctrine.includeMetaColumns'; + public const HINT_INCLUDE_META_COLUMNS = 'doctrine.includeMetaColumns'; /** * An array of class names that implement \Doctrine\ORM\Query\TreeWalker and * are iterated and executed after the DQL has been parsed into an AST. - * - * @var string */ - const HINT_CUSTOM_TREE_WALKERS = 'doctrine.customTreeWalkers'; + public const HINT_CUSTOM_TREE_WALKERS = 'doctrine.customTreeWalkers'; /** * A string with a class name that implements \Doctrine\ORM\Query\TreeWalker * and is used for generating the target SQL from any DQL AST tree. - * - * @var string */ - const HINT_CUSTOM_OUTPUT_WALKER = 'doctrine.customOutputWalker'; + public const HINT_CUSTOM_OUTPUT_WALKER = 'doctrine.customOutputWalker'; //const HINT_READ_ONLY = 'doctrine.readOnly'; - /** - * @var string - */ - const HINT_INTERNAL_ITERATION = 'doctrine.internal.iteration'; + public const HINT_INTERNAL_ITERATION = 'doctrine.internal.iteration'; - /** - * @var string - */ - const HINT_LOCK_MODE = 'doctrine.lockMode'; + public const HINT_LOCK_MODE = 'doctrine.lockMode'; /** * The current state of this query. * - * @var integer + * @var int */ private $_state = self::STATE_DIRTY; @@ -155,7 +140,7 @@ final class Query extends AbstractQuery /** * The parser result that holds DQL => SQL information. * - * @var \Doctrine\ORM\Query\ParserResult + * @var ParserResult */ private $_parserResult; @@ -169,21 +154,21 @@ final class Query extends AbstractQuery /** * The maximum number of results to return (the "limit"). * - * @var integer|null + * @var int|null */ private $_maxResults = null; /** * The cache driver used for caching queries. * - * @var \Doctrine\Common\Cache\Cache|null + * @var Cache|null */ private $_queryCache; /** * Whether or not expire the query cache. * - * @var boolean + * @var bool */ private $_expireQueryCache = false; @@ -197,7 +182,7 @@ final class Query extends AbstractQuery /** * Whether to use a query cache, if available. Defaults to TRUE. * - * @var boolean + * @var bool */ private $_useQueryCache = true; @@ -243,7 +228,7 @@ protected function getResultSetMapping() * * Note: Populates $this->_parserResult as a side-effect. * - * @return \Doctrine\ORM\Query\ParserResult + * @return ParserResult */ private function _parse() { @@ -259,11 +244,11 @@ private function _parse() return $this->_parserResult; } - $this->_state = self::STATE_CLEAN; + $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(); @@ -310,8 +295,8 @@ protected function _doExecute() // Prepare parameters $paramMappings = $this->_parserResult->getParameterMappings(); - $paramCount = count($this->parameters); - $mappingCount = count($paramMappings); + $paramCount = count($this->parameters); + $mappingCount = count($paramMappings); if ($paramCount > $mappingCount) { throw QueryException::tooManyParameters($mappingCount, $paramCount); @@ -344,7 +329,7 @@ private function evictResultSetCache( array $types, array $connectionParams ) { - if (null === $this->_queryCacheProfile || ! $this->getExpireResultCache()) { + if ($this->_queryCacheProfile === null || ! $this->getExpireResultCache()) { return; } @@ -387,7 +372,7 @@ private function evictEntityCacheRegion() * * @psalm-return array{0: list, 1: array} */ - private function processParameterMappings($paramMappings) : array + private function processParameterMappings($paramMappings): array { $sqlParams = []; $types = []; @@ -395,7 +380,7 @@ private function processParameterMappings($paramMappings) : array foreach ($this->parameters as $parameter) { $key = $parameter->getName(); - if ( ! isset($paramMappings[$key])) { + if (! isset($paramMappings[$key])) { throw QueryException::unknownParameter($key); } @@ -409,15 +394,15 @@ private function processParameterMappings($paramMappings) : array // optimized multi value sql positions away for now, // they are not allowed in DQL anyways. - $value = [$value]; + $value = [$value]; $countValue = count($value); for ($i = 0, $l = count($sqlPositions); $i < $l; $i++) { - $sqlParams[$sqlPositions[$i]] = $value[($i % $countValue)]; + $sqlParams[$sqlPositions[$i]] = $value[$i % $countValue]; } } - if (count($sqlParams) != count($types)) { + if (count($sqlParams) !== count($types)) { throw QueryException::parameterTypeMismatch(); } @@ -437,7 +422,7 @@ private function processParameterMappings($paramMappings) : array * * @psalm-return array{0: mixed, 1: mixed} */ - private function resolveParameterValue(Parameter $parameter) : array + private function resolveParameterValue(Parameter $parameter): array { if ($parameter->typeWasSpecified()) { return [$parameter->getValue(), $parameter->getType()]; @@ -471,11 +456,11 @@ private function resolveParameterValue(Parameter $parameter) : array /** * Defines a cache driver to be used for caching queries. * - * @param \Doctrine\Common\Cache\Cache|null $queryCache Cache driver. + * @param Cache|null $queryCache Cache driver. * * @return self This query instance. */ - public function setQueryCacheDriver($queryCache) : self + public function setQueryCacheDriver($queryCache): self { $this->_queryCache = $queryCache; @@ -485,11 +470,11 @@ public function setQueryCacheDriver($queryCache) : self /** * Defines whether the query should make use of a query cache, if available. * - * @param boolean $bool + * @param bool $bool * * @return self This query instance. */ - public function useQueryCache($bool) : self + public function useQueryCache($bool): self { $this->_useQueryCache = $bool; @@ -499,8 +484,8 @@ public function useQueryCache($bool) : self /** * Returns the cache driver used for query caching. * - * @return \Doctrine\Common\Cache\Cache|null The cache driver used for query caching or NULL, if - * this Query does not use query caching. + * @return Cache|null The cache driver used for query caching or NULL, if + * this Query does not use query caching. */ public function getQueryCacheDriver() { @@ -514,11 +499,11 @@ public function getQueryCacheDriver() /** * Defines how long the query cache will be active before expire. * - * @param integer $timeToLive How long the cache entry is valid. + * @param int $timeToLive How long the cache entry is valid. * * @return self This query instance. */ - public function setQueryCacheLifetime($timeToLive) : self + public function setQueryCacheLifetime($timeToLive): self { if ($timeToLive !== null) { $timeToLive = (int) $timeToLive; @@ -542,11 +527,11 @@ public function getQueryCacheLifetime() /** * Defines if the query cache is active or not. * - * @param boolean $expire Whether or not to force query cache expiration. + * @param bool $expire Whether or not to force query cache expiration. * * @return self This query instance. */ - public function expireQueryCache($expire = true) : self + public function expireQueryCache($expire = true): self { $this->_expireQueryCache = $expire; @@ -570,7 +555,7 @@ public function free() { parent::free(); - $this->_dql = null; + $this->_dql = null; $this->_state = self::STATE_CLEAN; } @@ -579,10 +564,10 @@ public function free() * * @param string $dqlQuery DQL Query. */ - public function setDQL($dqlQuery) : self + public function setDQL($dqlQuery): self { if ($dqlQuery !== null) { - $this->_dql = $dqlQuery; + $this->_dql = $dqlQuery; $this->_state = self::STATE_DIRTY; } @@ -607,7 +592,7 @@ public function getDQL() * @see AbstractQuery::STATE_CLEAN * @see AbstractQuery::STATE_DIRTY * - * @return integer The query state. + * @return int The query state. */ public function getState() { @@ -619,7 +604,7 @@ public function getState() * * @param string $dql Arbitrary piece of DQL to check for. * - * @return boolean + * @return bool */ public function contains($dql) { @@ -633,7 +618,7 @@ public function contains($dql) * * @return self This query object. */ - public function setFirstResult($firstResult) : self + public function setFirstResult($firstResult): self { $this->_firstResult = $firstResult; $this->_state = self::STATE_DIRTY; @@ -655,11 +640,11 @@ public function getFirstResult() /** * Sets the maximum number of results to retrieve (the "limit"). * - * @param integer|null $maxResults + * @param int|null $maxResults * * @return self This query object. */ - public function setMaxResults($maxResults) : self + public function setMaxResults($maxResults): self { $this->_maxResults = $maxResults; $this->_state = self::STATE_DIRTY; @@ -671,7 +656,7 @@ public function setMaxResults($maxResults) : self * Gets the maximum number of results the query object was set to retrieve (the "limit"). * Returns NULL if {@link setMaxResults} was not applied to this query. * - * @return integer|null Maximum number of results. + * @return int|null Maximum number of results. */ public function getMaxResults() { @@ -685,7 +670,7 @@ public function getMaxResults() * @param ArrayCollection|array|null $parameters The query parameters. * @param string|int $hydrationMode The hydration mode to use. * - * @return \Doctrine\ORM\Internal\Hydration\IterableResult + * @return IterableResult */ public function iterate($parameters = null, $hydrationMode = self::HYDRATE_OBJECT) { @@ -695,7 +680,7 @@ public function iterate($parameters = null, $hydrationMode = self::HYDRATE_OBJEC } /** {@inheritDoc} */ - public function toIterable(iterable $parameters = [], $hydrationMode = self::HYDRATE_OBJECT) : iterable + public function toIterable(iterable $parameters = [], $hydrationMode = self::HYDRATE_OBJECT): iterable { $this->setHint(self::HINT_INTERNAL_ITERATION, true); @@ -731,10 +716,10 @@ public function setHydrationMode($hydrationMode) * * @throws TransactionRequiredException */ - public function setLockMode($lockMode) : self + public function setLockMode($lockMode): self { 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(); } } @@ -753,7 +738,7 @@ public function getLockMode() { $lockMode = $this->getHint(self::HINT_LOCK_MODE); - if (false === $lockMode) { + if ($lockMode === false) { return null; } @@ -784,11 +769,11 @@ protected function _getQueryCacheId() } /** - * {@inheritdoc} - */ + * {@inheritdoc} + */ protected function getHash() { - return sha1(parent::getHash(). '-'. $this->_firstResult . '-' . $this->_maxResults); + return sha1(parent::getHash() . '-' . $this->_firstResult . '-' . $this->_maxResults); } /** diff --git a/lib/Doctrine/ORM/Query/AST/ASTException.php b/lib/Doctrine/ORM/Query/AST/ASTException.php index b8f931b45ee..0ff9a3293b4 100644 --- a/lib/Doctrine/ORM/Query/AST/ASTException.php +++ b/lib/Doctrine/ORM/Query/AST/ASTException.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class AggregateExpression extends Node { - /** - * @var string - */ + /** @var string */ public $functionName; - /** - * @var PathExpression|SimpleArithmeticExpression - */ + /** @var PathExpression|SimpleArithmeticExpression */ public $pathExpression; /** @@ -54,9 +47,9 @@ class AggregateExpression extends Node */ public function __construct($functionName, $pathExpression, $isDistinct) { - $this->functionName = $functionName; + $this->functionName = $functionName; $this->pathExpression = $pathExpression; - $this->isDistinct = $isDistinct; + $this->isDistinct = $isDistinct; } /** diff --git a/lib/Doctrine/ORM/Query/AST/ArithmeticExpression.php b/lib/Doctrine/ORM/Query/AST/ArithmeticExpression.php index b586cba3084..081057c181e 100644 --- a/lib/Doctrine/ORM/Query/AST/ArithmeticExpression.php +++ b/lib/Doctrine/ORM/Query/AST/ArithmeticExpression.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class ArithmeticExpression extends Node { - /** - * @var SimpleArithmeticExpression|null - */ + /** @var SimpleArithmeticExpression|null */ public $simpleArithmeticExpression; - /** - * @var Subselect|null - */ + /** @var Subselect|null */ public $subselect; /** diff --git a/lib/Doctrine/ORM/Query/AST/ArithmeticFactor.php b/lib/Doctrine/ORM/Query/AST/ArithmeticFactor.php index 3120466fd86..ee03ca127d0 100644 --- a/lib/Doctrine/ORM/Query/AST/ArithmeticFactor.php +++ b/lib/Doctrine/ORM/Query/AST/ArithmeticFactor.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class ArithmeticFactor extends Node { - /** - * @var mixed - */ + /** @var mixed */ public $arithmeticPrimary; /** * NULL represents no sign, TRUE means positive and FALSE means negative sign. * - * @var null|boolean + * @var bool|null */ public $sign; /** * @param mixed $arithmeticPrimary - * @param null|bool $sign + * @param bool|null $sign */ public function __construct($arithmeticPrimary, $sign = null) { $this->arithmeticPrimary = $arithmeticPrimary; - $this->sign = $sign; + $this->sign = $sign; } /** diff --git a/lib/Doctrine/ORM/Query/AST/ArithmeticTerm.php b/lib/Doctrine/ORM/Query/AST/ArithmeticTerm.php index e08ae7fbb83..60e8f08bfec 100644 --- a/lib/Doctrine/ORM/Query/AST/ArithmeticTerm.php +++ b/lib/Doctrine/ORM/Query/AST/ArithmeticTerm.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class ArithmeticTerm extends Node { - /** - * @var array - */ + /** @var array */ public $arithmeticFactors; /** diff --git a/lib/Doctrine/ORM/Query/AST/BetweenExpression.php b/lib/Doctrine/ORM/Query/AST/BetweenExpression.php index 1e31fd1a5a6..f6975b6bd07 100644 --- a/lib/Doctrine/ORM/Query/AST/BetweenExpression.php +++ b/lib/Doctrine/ORM/Query/AST/BetweenExpression.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class BetweenExpression extends Node { - /** - * @var ArithmeticExpression - */ + /** @var ArithmeticExpression */ public $expression; - /** - * @var ArithmeticExpression - */ + /** @var ArithmeticExpression */ public $leftBetweenExpression; - /** - * @var ArithmeticExpression - */ + /** @var ArithmeticExpression */ public $rightBetweenExpression; - /** - * @var bool - */ + /** @var bool */ public $not; /** @@ -57,8 +46,8 @@ class BetweenExpression extends Node */ public function __construct($expr, $leftExpr, $rightExpr) { - $this->expression = $expr; - $this->leftBetweenExpression = $leftExpr; + $this->expression = $expr; + $this->leftBetweenExpression = $leftExpr; $this->rightBetweenExpression = $rightExpr; } diff --git a/lib/Doctrine/ORM/Query/AST/CoalesceExpression.php b/lib/Doctrine/ORM/Query/AST/CoalesceExpression.php index 9e3b4c526fb..f5432b3bec3 100644 --- a/lib/Doctrine/ORM/Query/AST/CoalesceExpression.php +++ b/lib/Doctrine/ORM/Query/AST/CoalesceExpression.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class CoalesceExpression extends Node { - /** - * @var array - */ + /** @var array */ public $scalarExpressions = []; /** @@ -42,7 +35,7 @@ class CoalesceExpression extends Node */ public function __construct(array $scalarExpressions) { - $this->scalarExpressions = $scalarExpressions; + $this->scalarExpressions = $scalarExpressions; } /** diff --git a/lib/Doctrine/ORM/Query/AST/CollectionMemberExpression.php b/lib/Doctrine/ORM/Query/AST/CollectionMemberExpression.php index 70989a26784..48259f79186 100644 --- a/lib/Doctrine/ORM/Query/AST/CollectionMemberExpression.php +++ b/lib/Doctrine/ORM/Query/AST/CollectionMemberExpression.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class CollectionMemberExpression extends Node { public $entityExpression; - /** - * @var PathExpression - */ + /** @var PathExpression */ public $collectionValuedPathExpression; - /** - * @var bool - */ + /** @var bool */ public $not; /** @@ -49,7 +41,7 @@ class CollectionMemberExpression extends Node */ public function __construct($entityExpr, $collValuedPathExpr) { - $this->entityExpression = $entityExpr; + $this->entityExpression = $entityExpr; $this->collectionValuedPathExpression = $collValuedPathExpr; } diff --git a/lib/Doctrine/ORM/Query/AST/ComparisonExpression.php b/lib/Doctrine/ORM/Query/AST/ComparisonExpression.php index ad4d2225736..6b5cac9fed5 100644 --- a/lib/Doctrine/ORM/Query/AST/ComparisonExpression.php +++ b/lib/Doctrine/ORM/Query/AST/ComparisonExpression.php @@ -1,4 +1,5 @@ ") (EntityExpression | QuantifiedExpression) * * @link www.doctrine-project.org - * @since 2.0 - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class ComparisonExpression extends Node { - /** - * @var Node - */ + /** @var Node */ public $leftExpression; - /** - * @var Node - */ + /** @var Node */ public $rightExpression; - /** - * @var string - */ + /** @var string */ public $operator; /** @@ -57,9 +48,9 @@ class ComparisonExpression extends Node */ public function __construct($leftExpr, $operator, $rightExpr) { - $this->leftExpression = $leftExpr; + $this->leftExpression = $leftExpr; $this->rightExpression = $rightExpr; - $this->operator = $operator; + $this->operator = $operator; } /** diff --git a/lib/Doctrine/ORM/Query/AST/ConditionalExpression.php b/lib/Doctrine/ORM/Query/AST/ConditionalExpression.php index bf823629b69..02d5277246b 100644 --- a/lib/Doctrine/ORM/Query/AST/ConditionalExpression.php +++ b/lib/Doctrine/ORM/Query/AST/ConditionalExpression.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class ConditionalExpression extends Node { - /** - * @var array - */ + /** @var array */ public $conditionalTerms = []; /** diff --git a/lib/Doctrine/ORM/Query/AST/ConditionalFactor.php b/lib/Doctrine/ORM/Query/AST/ConditionalFactor.php index 7c89faa420b..7b440821994 100644 --- a/lib/Doctrine/ORM/Query/AST/ConditionalFactor.php +++ b/lib/Doctrine/ORM/Query/AST/ConditionalFactor.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class ConditionalFactor extends Node { - /** - * @var bool - */ + /** @var bool */ public $not = false; - /** - * @var ConditionalPrimary - */ + /** @var ConditionalPrimary */ public $conditionalPrimary; /** diff --git a/lib/Doctrine/ORM/Query/AST/ConditionalPrimary.php b/lib/Doctrine/ORM/Query/AST/ConditionalPrimary.php index 1eed41dce67..36e6cc7cc84 100644 --- a/lib/Doctrine/ORM/Query/AST/ConditionalPrimary.php +++ b/lib/Doctrine/ORM/Query/AST/ConditionalPrimary.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class ConditionalPrimary extends Node { - /** - * @var Node|null - */ + /** @var Node|null */ public $simpleConditionalExpression; - /** - * @var ConditionalExpression|null - */ + /** @var ConditionalExpression|null */ public $conditionalExpression; /** diff --git a/lib/Doctrine/ORM/Query/AST/ConditionalTerm.php b/lib/Doctrine/ORM/Query/AST/ConditionalTerm.php index 7122c9c6822..d4d712afa66 100644 --- a/lib/Doctrine/ORM/Query/AST/ConditionalTerm.php +++ b/lib/Doctrine/ORM/Query/AST/ConditionalTerm.php @@ -1,4 +1,5 @@ . */ + namespace Doctrine\ORM\Query\AST; /** * ConditionalTerm ::= ConditionalFactor {"AND" ConditionalFactor}* * * @link www.doctrine-project.org - * @since 2.0 - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class ConditionalTerm extends Node { - /** - * @var array - */ + /** @var array */ public $conditionalFactors = []; /** diff --git a/lib/Doctrine/ORM/Query/AST/DeleteClause.php b/lib/Doctrine/ORM/Query/AST/DeleteClause.php index 8ca35c6772f..8f7f368361b 100644 --- a/lib/Doctrine/ORM/Query/AST/DeleteClause.php +++ b/lib/Doctrine/ORM/Query/AST/DeleteClause.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class DeleteClause extends Node { - /** - * @var string - */ + /** @var string */ public $abstractSchemaName; - /** - * @var string - */ + /** @var string */ public $aliasIdentificationVariable; /** diff --git a/lib/Doctrine/ORM/Query/AST/DeleteStatement.php b/lib/Doctrine/ORM/Query/AST/DeleteStatement.php index da6859b8678..29b14cbd8c4 100644 --- a/lib/Doctrine/ORM/Query/AST/DeleteStatement.php +++ b/lib/Doctrine/ORM/Query/AST/DeleteStatement.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class DeleteStatement extends Node { - /** - * @var DeleteClause - */ + /** @var DeleteClause */ public $deleteClause; - /** - * @var WhereClause|null - */ + /** @var WhereClause|null */ public $whereClause; /** diff --git a/lib/Doctrine/ORM/Query/AST/EmptyCollectionComparisonExpression.php b/lib/Doctrine/ORM/Query/AST/EmptyCollectionComparisonExpression.php index bd978af04be..36ba7ee4130 100644 --- a/lib/Doctrine/ORM/Query/AST/EmptyCollectionComparisonExpression.php +++ b/lib/Doctrine/ORM/Query/AST/EmptyCollectionComparisonExpression.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class EmptyCollectionComparisonExpression extends Node { - /** - * @var PathExpression - */ + /** @var PathExpression */ public $expression; - /** - * @var bool - */ + /** @var bool */ public $not; /** diff --git a/lib/Doctrine/ORM/Query/AST/ExistsExpression.php b/lib/Doctrine/ORM/Query/AST/ExistsExpression.php index c53a10775e1..2093ebf2072 100644 --- a/lib/Doctrine/ORM/Query/AST/ExistsExpression.php +++ b/lib/Doctrine/ORM/Query/AST/ExistsExpression.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class ExistsExpression extends Node { - /** - * @var bool - */ + /** @var bool */ public $not; - /** - * @var Subselect - */ + /** @var Subselect */ public $subselect; /** diff --git a/lib/Doctrine/ORM/Query/AST/FromClause.php b/lib/Doctrine/ORM/Query/AST/FromClause.php index fdb61ca373a..be1bac370a4 100644 --- a/lib/Doctrine/ORM/Query/AST/FromClause.php +++ b/lib/Doctrine/ORM/Query/AST/FromClause.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class FromClause extends Node { - /** - * @var array - */ + /** @var array */ public $identificationVariableDeclarations = []; /** diff --git a/lib/Doctrine/ORM/Query/AST/Functions/AbsFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/AbsFunction.php index 484df01497a..b0607a73b72 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/AbsFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/AbsFunction.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel - * @author Benjamin Eberlei */ class AbsFunction extends FunctionNode { - /** - * @var \Doctrine\ORM\Query\AST\SimpleArithmeticExpression - */ + /** @var SimpleArithmeticExpression */ public $simpleArithmeticExpression; /** * @override * @inheritdoc */ - public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) + public function getSql(SqlWalker $sqlWalker) { return 'ABS(' . $sqlWalker->walkSimpleArithmeticExpression( $this->simpleArithmeticExpression @@ -54,7 +50,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) * @override * @inheritdoc */ - public function parse(\Doctrine\ORM\Query\Parser $parser) + public function parse(Parser $parser) { $parser->match(Lexer::T_IDENTIFIER); $parser->match(Lexer::T_OPEN_PARENTHESIS); diff --git a/lib/Doctrine/ORM/Query/AST/Functions/AvgFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/AvgFunction.php index 6cb8d92b6b2..8ee2e62d812 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/AvgFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/AvgFunction.php @@ -1,4 +1,5 @@ */ final class AvgFunction extends FunctionNode { - /** - * @var AggregateExpression - */ + /** @var AggregateExpression */ private $aggregateExpression; - /** - * @inheritDoc - */ public function getSql(SqlWalker $sqlWalker): string { return $this->aggregateExpression->dispatch($sqlWalker); } - /** - * @inheritDoc - */ public function parse(Parser $parser): void { $this->aggregateExpression = $parser->AggregateExpression(); diff --git a/lib/Doctrine/ORM/Query/AST/Functions/BitAndFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/BitAndFunction.php index 469a4b0a24e..3f63d492639 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/BitAndFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/BitAndFunction.php @@ -1,4 +1,5 @@ */ class BitAndFunction extends FunctionNode { @@ -38,7 +38,7 @@ class BitAndFunction extends FunctionNode * @override * @inheritdoc */ - public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) + public function getSql(SqlWalker $sqlWalker) { $platform = $sqlWalker->getConnection()->getDatabasePlatform(); @@ -52,7 +52,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) * @override * @inheritdoc */ - public function parse(\Doctrine\ORM\Query\Parser $parser) + public function parse(Parser $parser) { $parser->match(Lexer::T_IDENTIFIER); $parser->match(Lexer::T_OPEN_PARENTHESIS); diff --git a/lib/Doctrine/ORM/Query/AST/Functions/BitOrFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/BitOrFunction.php index d3a3efc8324..0c7d14bc708 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/BitOrFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/BitOrFunction.php @@ -1,4 +1,5 @@ */ class BitOrFunction extends FunctionNode { @@ -38,7 +38,7 @@ class BitOrFunction extends FunctionNode * @override * @inheritdoc */ - public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) + public function getSql(SqlWalker $sqlWalker) { $platform = $sqlWalker->getConnection()->getDatabasePlatform(); @@ -52,7 +52,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) * @override * @inheritdoc */ - public function parse(\Doctrine\ORM\Query\Parser $parser) + public function parse(Parser $parser) { $parser->match(Lexer::T_IDENTIFIER); $parser->match(Lexer::T_OPEN_PARENTHESIS); diff --git a/lib/Doctrine/ORM/Query/AST/Functions/ConcatFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/ConcatFunction.php index b7c5ae13f82..056de574208 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/ConcatFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/ConcatFunction.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel - * @author Benjamin Eberlei */ class ConcatFunction extends FunctionNode { @@ -44,7 +43,7 @@ class ConcatFunction extends FunctionNode * @override * @inheritdoc */ - public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) + public function getSql(SqlWalker $sqlWalker) { $platform = $sqlWalker->getConnection()->getDatabasePlatform(); @@ -54,19 +53,19 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) $args[] = $sqlWalker->walkStringPrimary($expression); } - return call_user_func_array([$platform,'getConcatExpression'], $args); + return call_user_func_array([$platform, 'getConcatExpression'], $args); } /** * @override * @inheritdoc */ - public function parse(\Doctrine\ORM\Query\Parser $parser) + public function parse(Parser $parser) { $parser->match(Lexer::T_IDENTIFIER); $parser->match(Lexer::T_OPEN_PARENTHESIS); - $this->firstStringPrimary = $parser->StringPrimary(); + $this->firstStringPrimary = $parser->StringPrimary(); $this->concatExpressions[] = $this->firstStringPrimary; $parser->match(Lexer::T_COMMA); @@ -82,4 +81,3 @@ public function parse(\Doctrine\ORM\Query\Parser $parser) $parser->match(Lexer::T_CLOSE_PARENTHESIS); } } - diff --git a/lib/Doctrine/ORM/Query/AST/Functions/CountFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/CountFunction.php index 500edbee537..42e7b00795a 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/CountFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/CountFunction.php @@ -1,4 +1,5 @@ */ final class CountFunction extends FunctionNode implements TypedExpression { - /** - * @var AggregateExpression - */ + /** @var AggregateExpression */ private $aggregateExpression; - /** - * @inheritDoc - */ public function getSql(SqlWalker $sqlWalker): string { return $this->aggregateExpression->dispatch($sqlWalker); } - /** - * @inheritDoc - */ public function parse(Parser $parser): void { $this->aggregateExpression = $parser->AggregateExpression(); } - public function getReturnType() : Type + public function getReturnType(): Type { return Type::getType(Type::INTEGER); } diff --git a/lib/Doctrine/ORM/Query/AST/Functions/CurrentDateFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/CurrentDateFunction.php index 565b87581b3..19e32c84409 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/CurrentDateFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/CurrentDateFunction.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel - * @author Benjamin Eberlei */ class CurrentDateFunction extends FunctionNode { @@ -38,7 +35,7 @@ class CurrentDateFunction extends FunctionNode * @override * @inheritdoc */ - public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) + public function getSql(SqlWalker $sqlWalker) { return $sqlWalker->getConnection()->getDatabasePlatform()->getCurrentDateSQL(); } @@ -47,7 +44,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) * @override * @inheritdoc */ - public function parse(\Doctrine\ORM\Query\Parser $parser) + public function parse(Parser $parser) { $parser->match(Lexer::T_IDENTIFIER); $parser->match(Lexer::T_OPEN_PARENTHESIS); diff --git a/lib/Doctrine/ORM/Query/AST/Functions/CurrentTimeFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/CurrentTimeFunction.php index ec9ceb757f5..2587eea0b21 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/CurrentTimeFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/CurrentTimeFunction.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel - * @author Benjamin Eberlei */ class CurrentTimeFunction extends FunctionNode { @@ -38,7 +35,7 @@ class CurrentTimeFunction extends FunctionNode * @override * @inheritdoc */ - public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) + public function getSql(SqlWalker $sqlWalker) { return $sqlWalker->getConnection()->getDatabasePlatform()->getCurrentTimeSQL(); } @@ -47,7 +44,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) * @override * @inheritdoc */ - public function parse(\Doctrine\ORM\Query\Parser $parser) + public function parse(Parser $parser) { $parser->match(Lexer::T_IDENTIFIER); $parser->match(Lexer::T_OPEN_PARENTHESIS); diff --git a/lib/Doctrine/ORM/Query/AST/Functions/CurrentTimestampFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/CurrentTimestampFunction.php index 4203072128d..ef7ec8005d5 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/CurrentTimestampFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/CurrentTimestampFunction.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel - * @author Benjamin Eberlei */ class CurrentTimestampFunction extends FunctionNode { @@ -38,7 +35,7 @@ class CurrentTimestampFunction extends FunctionNode * @override * @inheritdoc */ - public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) + public function getSql(SqlWalker $sqlWalker) { return $sqlWalker->getConnection()->getDatabasePlatform()->getCurrentTimestampSQL(); } @@ -47,7 +44,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) * @override * @inheritdoc */ - public function parse(\Doctrine\ORM\Query\Parser $parser) + public function parse(Parser $parser) { $parser->match(Lexer::T_IDENTIFIER); $parser->match(Lexer::T_OPEN_PARENTHESIS); diff --git a/lib/Doctrine/ORM/Query/AST/Functions/DateAddFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/DateAddFunction.php index edec7f9874a..d466f25b423 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/DateAddFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/DateAddFunction.php @@ -1,4 +1,5 @@ - * @author Benjamin Eberlei */ class DateAddFunction extends FunctionNode { public $firstDateExpression = null; - public $intervalExpression = null; - public $unit = null; + public $intervalExpression = null; + public $unit = null; /** * @override @@ -51,31 +50,37 @@ public function getSql(SqlWalker $sqlWalker) $this->firstDateExpression->dispatch($sqlWalker), $this->intervalExpression->dispatch($sqlWalker) ); + case 'minute': return $sqlWalker->getConnection()->getDatabasePlatform()->getDateAddMinutesExpression( $this->firstDateExpression->dispatch($sqlWalker), $this->intervalExpression->dispatch($sqlWalker) ); + case 'hour': return $sqlWalker->getConnection()->getDatabasePlatform()->getDateAddHourExpression( $this->firstDateExpression->dispatch($sqlWalker), $this->intervalExpression->dispatch($sqlWalker) ); + case 'day': return $sqlWalker->getConnection()->getDatabasePlatform()->getDateAddDaysExpression( $this->firstDateExpression->dispatch($sqlWalker), $this->intervalExpression->dispatch($sqlWalker) ); + case 'week': return $sqlWalker->getConnection()->getDatabasePlatform()->getDateAddWeeksExpression( $this->firstDateExpression->dispatch($sqlWalker), $this->intervalExpression->dispatch($sqlWalker) ); + case 'month': return $sqlWalker->getConnection()->getDatabasePlatform()->getDateAddMonthExpression( $this->firstDateExpression->dispatch($sqlWalker), $this->intervalExpression->dispatch($sqlWalker) ); + case 'year': return $sqlWalker->getConnection()->getDatabasePlatform()->getDateAddYearsExpression( $this->firstDateExpression->dispatch($sqlWalker), diff --git a/lib/Doctrine/ORM/Query/AST/Functions/DateDiffFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/DateDiffFunction.php index 53724825f4e..7902c9b5b4e 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/DateDiffFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/DateDiffFunction.php @@ -1,4 +1,5 @@ */ class DateDiffFunction extends FunctionNode { diff --git a/lib/Doctrine/ORM/Query/AST/Functions/DateSubFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/DateSubFunction.php index 8dcc1353719..8c1585b0065 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/DateSubFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/DateSubFunction.php @@ -1,4 +1,5 @@ - * @author Benjamin Eberlei */ class DateSubFunction extends DateAddFunction { @@ -45,31 +44,37 @@ public function getSql(SqlWalker $sqlWalker) $this->firstDateExpression->dispatch($sqlWalker), $this->intervalExpression->dispatch($sqlWalker) ); + case 'minute': return $sqlWalker->getConnection()->getDatabasePlatform()->getDateSubMinutesExpression( $this->firstDateExpression->dispatch($sqlWalker), $this->intervalExpression->dispatch($sqlWalker) ); + case 'hour': return $sqlWalker->getConnection()->getDatabasePlatform()->getDateSubHourExpression( $this->firstDateExpression->dispatch($sqlWalker), $this->intervalExpression->dispatch($sqlWalker) ); + case 'day': return $sqlWalker->getConnection()->getDatabasePlatform()->getDateSubDaysExpression( $this->firstDateExpression->dispatch($sqlWalker), $this->intervalExpression->dispatch($sqlWalker) ); + case 'week': return $sqlWalker->getConnection()->getDatabasePlatform()->getDateSubWeeksExpression( $this->firstDateExpression->dispatch($sqlWalker), $this->intervalExpression->dispatch($sqlWalker) ); + case 'month': return $sqlWalker->getConnection()->getDatabasePlatform()->getDateSubMonthExpression( $this->firstDateExpression->dispatch($sqlWalker), $this->intervalExpression->dispatch($sqlWalker) ); + case 'year': return $sqlWalker->getConnection()->getDatabasePlatform()->getDateSubYearsExpression( $this->firstDateExpression->dispatch($sqlWalker), diff --git a/lib/Doctrine/ORM/Query/AST/Functions/FunctionNode.php b/lib/Doctrine/ORM/Query/AST/Functions/FunctionNode.php index 2b2c645ffe5..818f7f1d6a8 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/FunctionNode.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/FunctionNode.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel - * @author Benjamin Eberlei */ abstract class FunctionNode extends Node { - /** - * @var string - */ + /** @var string */ public $name; /** @@ -48,14 +43,12 @@ public function __construct($name) } /** - * @param \Doctrine\ORM\Query\SqlWalker $sqlWalker - * * @return string */ - abstract public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker); + abstract public function getSql(SqlWalker $sqlWalker); /** - * @param \Doctrine\ORM\Query\SqlWalker $sqlWalker + * @param SqlWalker $sqlWalker * * @return string */ @@ -65,9 +58,7 @@ public function dispatch($sqlWalker) } /** - * @param \Doctrine\ORM\Query\Parser $parser - * * @return void */ - abstract public function parse(\Doctrine\ORM\Query\Parser $parser); + abstract public function parse(Parser $parser); } diff --git a/lib/Doctrine/ORM/Query/AST/Functions/IdentityFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/IdentityFunction.php index 6f69d5357ac..222365ad84f 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/IdentityFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/IdentityFunction.php @@ -1,4 +1,5 @@ - * @author Benjamin Eberlei */ class IdentityFunction extends FunctionNode { - /** - * @var \Doctrine\ORM\Query\AST\PathExpression - */ + /** @var PathExpression */ public $pathExpression; - /** - * @var string - */ + /** @var string */ public $fieldMapping; /** @@ -50,18 +47,18 @@ class IdentityFunction extends FunctionNode */ public function getSql(SqlWalker $sqlWalker) { - $platform = $sqlWalker->getEntityManager()->getConnection()->getDatabasePlatform(); - $quoteStrategy = $sqlWalker->getEntityManager()->getConfiguration()->getQuoteStrategy(); - $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']); + $platform = $sqlWalker->getEntityManager()->getConnection()->getDatabasePlatform(); + $quoteStrategy = $sqlWalker->getEntityManager()->getConfiguration()->getQuoteStrategy(); + $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']); if ($this->fieldMapping !== null) { - if ( ! isset($targetEntity->fieldMappings[$this->fieldMapping])) { + if (! isset($targetEntity->fieldMappings[$this->fieldMapping])) { throw new QueryException(sprintf('Undefined reference field mapping "%s"', $this->fieldMapping)); } @@ -69,7 +66,6 @@ public function getSql(SqlWalker $sqlWalker) $joinColumn = null; foreach ($assoc['joinColumns'] as $mapping) { - if ($mapping['referencedColumnName'] === $field['columnName']) { $joinColumn = $mapping; @@ -86,7 +82,7 @@ public function getSql(SqlWalker $sqlWalker) $tableName = $sqlWalker->getEntityManager()->getClassMetadata($assoc['sourceEntity'])->getTableName(); $tableAlias = $sqlWalker->getSQLTableAlias($tableName, $dqlAlias); - $columnName = $quoteStrategy->getJoinColumnName($joinColumn, $targetEntity, $platform); + $columnName = $quoteStrategy->getJoinColumnName($joinColumn, $targetEntity, $platform); return $tableAlias . '.' . $columnName; } diff --git a/lib/Doctrine/ORM/Query/AST/Functions/LengthFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/LengthFunction.php index 1405b342dd3..7eacfaf1454 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/LengthFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/LengthFunction.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel - * @author Benjamin Eberlei */ class LengthFunction extends FunctionNode implements TypedExpression { @@ -42,7 +39,7 @@ class LengthFunction extends FunctionNode implements TypedExpression * @override * @inheritdoc */ - public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) + public function getSql(SqlWalker $sqlWalker) { return $sqlWalker->getConnection()->getDatabasePlatform()->getLengthExpression( $sqlWalker->walkSimpleArithmeticExpression($this->stringPrimary) @@ -53,7 +50,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) * @override * @inheritdoc */ - public function parse(\Doctrine\ORM\Query\Parser $parser) + public function parse(Parser $parser) { $parser->match(Lexer::T_IDENTIFIER); $parser->match(Lexer::T_OPEN_PARENTHESIS); @@ -63,7 +60,7 @@ public function parse(\Doctrine\ORM\Query\Parser $parser) $parser->match(Lexer::T_CLOSE_PARENTHESIS); } - public function getReturnType() : Type + public function getReturnType(): Type { return Type::getType(Type::INTEGER); } diff --git a/lib/Doctrine/ORM/Query/AST/Functions/LocateFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/LocateFunction.php index 473aa34eec9..1cdc3abf1c1 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/LocateFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/LocateFunction.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel - * @author Benjamin Eberlei */ class LocateFunction extends FunctionNode { public $firstStringPrimary; public $secondStringPrimary; - /** - * @var \Doctrine\ORM\Query\AST\SimpleArithmeticExpression|bool - */ + /** @var SimpleArithmeticExpression|bool */ public $simpleArithmeticExpression = false; /** * @override * @inheritdoc */ - public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) + public function getSql(SqlWalker $sqlWalker) { - return $sqlWalker->getConnection()->getDatabasePlatform()->getLocateExpression( $sqlWalker->walkStringPrimary($this->secondStringPrimary), // its the other way around in platform $sqlWalker->walkStringPrimary($this->firstStringPrimary), - (($this->simpleArithmeticExpression) + ($this->simpleArithmeticExpression ? $sqlWalker->walkSimpleArithmeticExpression($this->simpleArithmeticExpression) : false ) @@ -63,7 +58,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) * @override * @inheritdoc */ - public function parse(\Doctrine\ORM\Query\Parser $parser) + public function parse(Parser $parser) { $parser->match(Lexer::T_IDENTIFIER); $parser->match(Lexer::T_OPEN_PARENTHESIS); diff --git a/lib/Doctrine/ORM/Query/AST/Functions/LowerFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/LowerFunction.php index 5f0fb950018..a1edad69b42 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/LowerFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/LowerFunction.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel - * @author Benjamin Eberlei */ class LowerFunction extends FunctionNode { @@ -40,7 +37,7 @@ class LowerFunction extends FunctionNode * @override * @inheritdoc */ - public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) + public function getSql(SqlWalker $sqlWalker) { return $sqlWalker->getConnection()->getDatabasePlatform()->getLowerExpression( $sqlWalker->walkSimpleArithmeticExpression($this->stringPrimary) @@ -51,7 +48,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) * @override * @inheritdoc */ - public function parse(\Doctrine\ORM\Query\Parser $parser) + public function parse(Parser $parser) { $parser->match(Lexer::T_IDENTIFIER); $parser->match(Lexer::T_OPEN_PARENTHESIS); diff --git a/lib/Doctrine/ORM/Query/AST/Functions/MaxFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/MaxFunction.php index eba9b86393a..4d8e8cece5e 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/MaxFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/MaxFunction.php @@ -1,4 +1,5 @@ */ final class MaxFunction extends FunctionNode { - /** - * @var AggregateExpression - */ + /** @var AggregateExpression */ private $aggregateExpression; - /** - * @inheritDoc - */ public function getSql(SqlWalker $sqlWalker): string { return $this->aggregateExpression->dispatch($sqlWalker); } - /** - * @inheritDoc - */ public function parse(Parser $parser): void { $this->aggregateExpression = $parser->AggregateExpression(); diff --git a/lib/Doctrine/ORM/Query/AST/Functions/MinFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/MinFunction.php index e1c08691323..2609042ed09 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/MinFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/MinFunction.php @@ -1,4 +1,5 @@ */ final class MinFunction extends FunctionNode { - /** - * @var AggregateExpression - */ + /** @var AggregateExpression */ private $aggregateExpression; - /** - * @inheritDoc - */ public function getSql(SqlWalker $sqlWalker): string { return $this->aggregateExpression->dispatch($sqlWalker); } - /** - * @inheritDoc - */ public function parse(Parser $parser): void { $this->aggregateExpression = $parser->AggregateExpression(); diff --git a/lib/Doctrine/ORM/Query/AST/Functions/ModFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/ModFunction.php index 61bc9a79ed9..a78bf49d524 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/ModFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/ModFunction.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel - * @author Benjamin Eberlei */ class ModFunction extends FunctionNode { - /** - * @var \Doctrine\ORM\Query\AST\SimpleArithmeticExpression - */ + /** @var SimpleArithmeticExpression */ public $firstSimpleArithmeticExpression; - /** - * @var \Doctrine\ORM\Query\AST\SimpleArithmeticExpression - */ + /** @var SimpleArithmeticExpression */ public $secondSimpleArithmeticExpression; /** * @override * @inheritdoc */ - public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) + public function getSql(SqlWalker $sqlWalker) { return $sqlWalker->getConnection()->getDatabasePlatform()->getModExpression( $sqlWalker->walkSimpleArithmeticExpression($this->firstSimpleArithmeticExpression), @@ -60,7 +54,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) * @override * @inheritdoc */ - public function parse(\Doctrine\ORM\Query\Parser $parser) + public function parse(Parser $parser) { $parser->match(Lexer::T_IDENTIFIER); $parser->match(Lexer::T_OPEN_PARENTHESIS); diff --git a/lib/Doctrine/ORM/Query/AST/Functions/SizeFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/SizeFunction.php index bf0f7a4ec04..9027dfa4df3 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/SizeFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/SizeFunction.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel - * @author Benjamin Eberlei */ class SizeFunction extends FunctionNode { - /** - * @var \Doctrine\ORM\Query\AST\PathExpression - */ + /** @var PathExpression */ public $collectionPathExpression; /** @@ -44,22 +41,22 @@ class SizeFunction extends FunctionNode * @inheritdoc * @todo If the collection being counted is already joined, the SQL can be simpler (more efficient). */ - public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) + public function getSql(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']); - $targetTableAlias = $sqlWalker->getSQLTableAlias($targetClass->getTableName()); - $sourceTableAlias = $sqlWalker->getSQLTableAlias($class->getTableName(), $dqlAlias); + $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'] === ClassMetadata::ONE_TO_MANY) { + $targetClass = $sqlWalker->getEntityManager()->getClassMetadata($assoc['targetEntity']); + $targetTableAlias = $sqlWalker->getSQLTableAlias($targetClass->getTableName()); + $sourceTableAlias = $sqlWalker->getSQLTableAlias($class->getTableName(), $dqlAlias); $sql .= $quoteStrategy->getTableName($targetClass, $platform) . ' ' . $targetTableAlias . ' WHERE '; @@ -68,7 +65,11 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) $first = true; foreach ($owningAssoc['targetToSourceKeyColumns'] as $targetColumn => $sourceColumn) { - if ($first) $first = false; else $sql .= ' AND '; + if ($first) { + $first = false; + } else { + $sql .= ' AND '; + } $sql .= $targetTableAlias . '.' . $sourceColumn . ' = ' @@ -78,10 +79,10 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) $targetClass = $sqlWalker->getEntityManager()->getClassMetadata($assoc['targetEntity']); $owningAssoc = $assoc['isOwningSide'] ? $assoc : $targetClass->associationMappings[$assoc['mappedBy']]; - $joinTable = $owningAssoc['joinTable']; + $joinTable = $owningAssoc['joinTable']; // SQL table aliases - $joinTableAlias = $sqlWalker->getSQLTableAlias($joinTable['name']); + $joinTableAlias = $sqlWalker->getSQLTableAlias($joinTable['name']); $sourceTableAlias = $sqlWalker->getSQLTableAlias($class->getTableName(), $dqlAlias); // join to target table @@ -94,10 +95,16 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) $first = true; foreach ($joinColumns as $joinColumn) { - if ($first) $first = false; else $sql .= ' AND '; + if ($first) { + $first = false; + } else { + $sql .= ' AND '; + } $sourceColumnName = $quoteStrategy->getColumnName( - $class->fieldNames[$joinColumn['referencedColumnName']], $class, $platform + $class->fieldNames[$joinColumn['referencedColumnName']], + $class, + $platform ); $sql .= $joinTableAlias . '.' . $joinColumn['name'] @@ -113,7 +120,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) * @override * @inheritdoc */ - public function parse(\Doctrine\ORM\Query\Parser $parser) + public function parse(Parser $parser) { $parser->match(Lexer::T_IDENTIFIER); $parser->match(Lexer::T_OPEN_PARENTHESIS); diff --git a/lib/Doctrine/ORM/Query/AST/Functions/SqrtFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/SqrtFunction.php index 139d17a82dd..ed6f4d3802f 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/SqrtFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/SqrtFunction.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel - * @author Benjamin Eberlei */ class SqrtFunction extends FunctionNode { - /** - * @var \Doctrine\ORM\Query\AST\SimpleArithmeticExpression - */ + /** @var SimpleArithmeticExpression */ public $simpleArithmeticExpression; /** * @override * @inheritdoc */ - public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) + public function getSql(SqlWalker $sqlWalker) { return $sqlWalker->getConnection()->getDatabasePlatform()->getSqrtExpression( $sqlWalker->walkSimpleArithmeticExpression($this->simpleArithmeticExpression) @@ -54,7 +50,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) * @override * @inheritdoc */ - public function parse(\Doctrine\ORM\Query\Parser $parser) + public function parse(Parser $parser) { $parser->match(Lexer::T_IDENTIFIER); $parser->match(Lexer::T_OPEN_PARENTHESIS); diff --git a/lib/Doctrine/ORM/Query/AST/Functions/SubstringFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/SubstringFunction.php index a6a80f8112b..e3dfb87cfbd 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/SubstringFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/SubstringFunction.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel - * @author Benjamin Eberlei */ class SubstringFunction extends FunctionNode { public $stringPrimary; - /** - * @var \Doctrine\ORM\Query\AST\SimpleArithmeticExpression - */ + /** @var SimpleArithmeticExpression */ public $firstSimpleArithmeticExpression; - /** - * @var \Doctrine\ORM\Query\AST\SimpleArithmeticExpression|null - */ + /** @var SimpleArithmeticExpression|null */ public $secondSimpleArithmeticExpression = null; /** * @override * @inheritdoc */ - public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) + public function getSql(SqlWalker $sqlWalker) { $optionalSecondSimpleArithmeticExpression = null; if ($this->secondSimpleArithmeticExpression !== null) { @@ -68,7 +62,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) * @override * @inheritdoc */ - public function parse(\Doctrine\ORM\Query\Parser $parser) + public function parse(Parser $parser) { $parser->match(Lexer::T_IDENTIFIER); $parser->match(Lexer::T_OPEN_PARENTHESIS); diff --git a/lib/Doctrine/ORM/Query/AST/Functions/SumFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/SumFunction.php index c9fcf7b04e7..4055459eb2c 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/SumFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/SumFunction.php @@ -1,4 +1,5 @@ */ final class SumFunction extends FunctionNode { - /** - * @var AggregateExpression - */ + /** @var AggregateExpression */ private $aggregateExpression; - /** - * @inheritDoc - */ public function getSql(SqlWalker $sqlWalker): string { return $this->aggregateExpression->dispatch($sqlWalker); } - /** - * @inheritDoc - */ public function parse(Parser $parser): void { $this->aggregateExpression = $parser->AggregateExpression(); diff --git a/lib/Doctrine/ORM/Query/AST/Functions/TrimFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/TrimFunction.php index f26616ed86e..b7e07099036 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/TrimFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/TrimFunction.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel - * @author Benjamin Eberlei */ class TrimFunction extends FunctionNode { - /** - * @var boolean - */ + /** @var bool */ public $leading; - /** - * @var boolean - */ + /** @var bool */ public $trailing; - /** - * @var boolean - */ + /** @var bool */ public $both; - /** - * @var boolean - */ + /** @var bool */ public $trimChar = false; - /** - * @var \Doctrine\ORM\Query\AST\Node - */ + /** @var Node */ public $stringPrimary; /** @@ -67,10 +55,10 @@ class TrimFunction extends FunctionNode */ public function getSql(SqlWalker $sqlWalker) { - $stringPrimary = $sqlWalker->walkStringPrimary($this->stringPrimary); - $platform = $sqlWalker->getConnection()->getDatabasePlatform(); - $trimMode = $this->getTrimMode(); - $trimChar = ($this->trimChar !== false) + $stringPrimary = $sqlWalker->walkStringPrimary($this->stringPrimary); + $platform = $sqlWalker->getConnection()->getDatabasePlatform(); + $trimMode = $this->getTrimMode(); + $trimChar = $this->trimChar !== false ? $sqlWalker->getConnection()->quote($this->trimChar) : false; @@ -125,8 +113,6 @@ private function getTrimMode() } /** - * @param \Doctrine\ORM\Query\Parser $parser - * * @return void */ private function parseTrimMode(Parser $parser) diff --git a/lib/Doctrine/ORM/Query/AST/Functions/UpperFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/UpperFunction.php index 28e0f162714..11b351b2d8d 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/UpperFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/UpperFunction.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel - * @author Benjamin Eberlei */ class UpperFunction extends FunctionNode { @@ -40,7 +37,7 @@ class UpperFunction extends FunctionNode * @override * @inheritdoc */ - public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) + public function getSql(SqlWalker $sqlWalker) { return $sqlWalker->getConnection()->getDatabasePlatform()->getUpperExpression( $sqlWalker->walkSimpleArithmeticExpression($this->stringPrimary) @@ -51,7 +48,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) * @override * @inheritdoc */ - public function parse(\Doctrine\ORM\Query\Parser $parser) + public function parse(Parser $parser) { $parser->match(Lexer::T_IDENTIFIER); $parser->match(Lexer::T_OPEN_PARENTHESIS); diff --git a/lib/Doctrine/ORM/Query/AST/GeneralCaseExpression.php b/lib/Doctrine/ORM/Query/AST/GeneralCaseExpression.php index e7937d60d2e..5f755d77a52 100644 --- a/lib/Doctrine/ORM/Query/AST/GeneralCaseExpression.php +++ b/lib/Doctrine/ORM/Query/AST/GeneralCaseExpression.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class GeneralCaseExpression extends Node { - /** - * @var array - */ + /** @var array */ public $whenClauses = []; - /** - * @var mixed - */ + /** @var mixed */ public $elseScalarExpression = null; /** @@ -48,7 +39,7 @@ class GeneralCaseExpression extends Node */ public function __construct(array $whenClauses, $elseScalarExpression) { - $this->whenClauses = $whenClauses; + $this->whenClauses = $whenClauses; $this->elseScalarExpression = $elseScalarExpression; } diff --git a/lib/Doctrine/ORM/Query/AST/GroupByClause.php b/lib/Doctrine/ORM/Query/AST/GroupByClause.php index 687512a4c73..fa126f9e0ef 100644 --- a/lib/Doctrine/ORM/Query/AST/GroupByClause.php +++ b/lib/Doctrine/ORM/Query/AST/GroupByClause.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class GroupByClause extends Node { - /** - * @var array - */ + /** @var array */ public $groupByItems = []; /** diff --git a/lib/Doctrine/ORM/Query/AST/HavingClause.php b/lib/Doctrine/ORM/Query/AST/HavingClause.php index 1d369fff66a..23c2b6c398a 100644 --- a/lib/Doctrine/ORM/Query/AST/HavingClause.php +++ b/lib/Doctrine/ORM/Query/AST/HavingClause.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class HavingClause extends Node { - /** - * @var ConditionalExpression - */ + /** @var ConditionalExpression */ public $conditionalExpression; /** diff --git a/lib/Doctrine/ORM/Query/AST/IdentificationVariableDeclaration.php b/lib/Doctrine/ORM/Query/AST/IdentificationVariableDeclaration.php index 2e2032ca341..a86c75975d1 100644 --- a/lib/Doctrine/ORM/Query/AST/IdentificationVariableDeclaration.php +++ b/lib/Doctrine/ORM/Query/AST/IdentificationVariableDeclaration.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class IdentificationVariableDeclaration extends Node { - /** - * @var RangeVariableDeclaration|null - */ + /** @var RangeVariableDeclaration|null */ public $rangeVariableDeclaration = null; - /** - * @var IndexBy|null - */ + /** @var IndexBy|null */ public $indexBy = null; - /** - * @var array - */ + /** @var array */ public $joins = []; /** @@ -53,8 +44,8 @@ class IdentificationVariableDeclaration extends Node public function __construct($rangeVariableDecl, $indexBy, array $joins) { $this->rangeVariableDeclaration = $rangeVariableDecl; - $this->indexBy = $indexBy; - $this->joins = $joins; + $this->indexBy = $indexBy; + $this->joins = $joins; } /** diff --git a/lib/Doctrine/ORM/Query/AST/InExpression.php b/lib/Doctrine/ORM/Query/AST/InExpression.php index 64ef1340573..8e63f9605b8 100644 --- a/lib/Doctrine/ORM/Query/AST/InExpression.php +++ b/lib/Doctrine/ORM/Query/AST/InExpression.php @@ -1,4 +1,5 @@ . */ + namespace Doctrine\ORM\Query\AST; /** * InExpression ::= StateFieldPathExpression ["NOT"] "IN" "(" (Literal {"," Literal}* | Subselect) ")" * * @link www.doctrine-project.org - * @since 2.0 - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class InExpression extends Node { - /** - * @var bool - */ + /** @var bool */ public $not; - /** - * @var ArithmeticExpression - */ + /** @var ArithmeticExpression */ public $expression; - /** - * @var array - */ + /** @var array */ public $literals = []; - /** - * @var Subselect|null - */ + /** @var Subselect|null */ public $subselect; /** diff --git a/lib/Doctrine/ORM/Query/AST/IndexBy.php b/lib/Doctrine/ORM/Query/AST/IndexBy.php index c7874b70a35..1c0eb091b15 100644 --- a/lib/Doctrine/ORM/Query/AST/IndexBy.php +++ b/lib/Doctrine/ORM/Query/AST/IndexBy.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class IndexBy extends Node { - /** - * @var PathExpression - */ + /** @var PathExpression */ public $simpleStateFieldPathExpression = null; /** diff --git a/lib/Doctrine/ORM/Query/AST/InputParameter.php b/lib/Doctrine/ORM/Query/AST/InputParameter.php index 4da550f9b4f..b963959c5a4 100644 --- a/lib/Doctrine/ORM/Query/AST/InputParameter.php +++ b/lib/Doctrine/ORM/Query/AST/InputParameter.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class InputParameter extends Node { - /** - * @var bool - */ + /** @var bool */ public $isNamed; - /** - * @var string - */ + /** @var string */ public $name; /** * @param string $value * - * @throws \Doctrine\ORM\Query\QueryException + * @throws QueryException */ public function __construct($value) { if (strlen($value) === 1) { - throw \Doctrine\ORM\Query\QueryException::invalidParameterFormat($value); + throw QueryException::invalidParameterFormat($value); } - $param = substr($value, 1); + $param = substr($value, 1); $this->isNamed = ! is_numeric($param); - $this->name = $param; + $this->name = $param; } /** diff --git a/lib/Doctrine/ORM/Query/AST/InstanceOfExpression.php b/lib/Doctrine/ORM/Query/AST/InstanceOfExpression.php index c1fd65b8e6b..73630f92d24 100644 --- a/lib/Doctrine/ORM/Query/AST/InstanceOfExpression.php +++ b/lib/Doctrine/ORM/Query/AST/InstanceOfExpression.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class InstanceOfExpression extends Node { - /** - * @var bool - */ + /** @var bool */ public $not; - /** - * @var string - */ + /** @var string */ public $identificationVariable; - /** - * @var array - */ + /** @var array */ public $value; /** diff --git a/lib/Doctrine/ORM/Query/AST/Join.php b/lib/Doctrine/ORM/Query/AST/Join.php index 5c203aa0b47..7591fc4f2f4 100644 --- a/lib/Doctrine/ORM/Query/AST/Join.php +++ b/lib/Doctrine/ORM/Query/AST/Join.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class Join extends Node { - const JOIN_TYPE_LEFT = 1; - const JOIN_TYPE_LEFTOUTER = 2; - const JOIN_TYPE_INNER = 3; + public const JOIN_TYPE_LEFT = 1; + public const JOIN_TYPE_LEFTOUTER = 2; + public const JOIN_TYPE_INNER = 3; - /** - * @var int - */ + /** @var int */ public $joinType = self::JOIN_TYPE_INNER; - /** - * @var Node|null - */ + /** @var Node|null */ public $joinAssociationDeclaration = null; - /** - * @var ConditionalExpression|null - */ + /** @var ConditionalExpression|null */ public $conditionalExpression = null; /** @@ -56,7 +47,7 @@ class Join extends Node */ public function __construct($joinType, $joinAssociationDeclaration) { - $this->joinType = $joinType; + $this->joinType = $joinType; $this->joinAssociationDeclaration = $joinAssociationDeclaration; } diff --git a/lib/Doctrine/ORM/Query/AST/JoinAssociationDeclaration.php b/lib/Doctrine/ORM/Query/AST/JoinAssociationDeclaration.php index a33900a6d65..e6cfca4bdf9 100644 --- a/lib/Doctrine/ORM/Query/AST/JoinAssociationDeclaration.php +++ b/lib/Doctrine/ORM/Query/AST/JoinAssociationDeclaration.php @@ -1,4 +1,5 @@ */ class JoinAssociationDeclaration extends Node { - /** - * @var JoinAssociationPathExpression - */ + /** @var JoinAssociationPathExpression */ public $joinAssociationPathExpression; - /** - * @var string - */ + /** @var string */ public $aliasIdentificationVariable; - /** - * @var IndexBy|null - */ + /** @var IndexBy|null */ public $indexBy; /** diff --git a/lib/Doctrine/ORM/Query/AST/JoinAssociationPathExpression.php b/lib/Doctrine/ORM/Query/AST/JoinAssociationPathExpression.php index 946bbb15b7d..ec0a5ad8804 100644 --- a/lib/Doctrine/ORM/Query/AST/JoinAssociationPathExpression.php +++ b/lib/Doctrine/ORM/Query/AST/JoinAssociationPathExpression.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class JoinAssociationPathExpression extends Node { - /** - * @var string - */ + /** @var string */ public $identificationVariable; - /** - * @var string - */ + /** @var string */ public $associationField; /** diff --git a/lib/Doctrine/ORM/Query/AST/JoinClassPathExpression.php b/lib/Doctrine/ORM/Query/AST/JoinClassPathExpression.php index 7e374149f2d..9a4b9164a17 100644 --- a/lib/Doctrine/ORM/Query/AST/JoinClassPathExpression.php +++ b/lib/Doctrine/ORM/Query/AST/JoinClassPathExpression.php @@ -1,4 +1,5 @@ */ class JoinClassPathExpression extends Node { - /** - * @var mixed - */ + /** @var mixed */ public $abstractSchemaName; - /** - * @var mixed - */ + /** @var mixed */ public $aliasIdentificationVariable; /** @@ -45,7 +39,7 @@ class JoinClassPathExpression extends Node */ public function __construct($abstractSchemaName, $aliasIdentificationVar) { - $this->abstractSchemaName = $abstractSchemaName; + $this->abstractSchemaName = $abstractSchemaName; $this->aliasIdentificationVariable = $aliasIdentificationVar; } diff --git a/lib/Doctrine/ORM/Query/AST/JoinVariableDeclaration.php b/lib/Doctrine/ORM/Query/AST/JoinVariableDeclaration.php index 89aa83ad8cc..12def9891ac 100644 --- a/lib/Doctrine/ORM/Query/AST/JoinVariableDeclaration.php +++ b/lib/Doctrine/ORM/Query/AST/JoinVariableDeclaration.php @@ -1,4 +1,5 @@ */ class JoinVariableDeclaration extends Node { - /** - * @var Join - */ + /** @var Join */ public $join; - - /** - * @var IndexBy|null - */ + + /** @var IndexBy|null */ public $indexBy; - + /** - * Constructor. - * * @param Join $join * @param IndexBy|null $indexBy */ diff --git a/lib/Doctrine/ORM/Query/AST/LikeExpression.php b/lib/Doctrine/ORM/Query/AST/LikeExpression.php index e320c51c882..09b27bdb74a 100644 --- a/lib/Doctrine/ORM/Query/AST/LikeExpression.php +++ b/lib/Doctrine/ORM/Query/AST/LikeExpression.php @@ -1,4 +1,5 @@ . */ + namespace Doctrine\ORM\Query\AST; /** * LikeExpression ::= StringExpression ["NOT"] "LIKE" string ["ESCAPE" char] * * @link www.doctrine-project.org - * @since 2.0 - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class LikeExpression extends Node { - /** - * @var bool - */ + /** @var bool */ public $not; - /** - * @var Node - */ + /** @var Node */ public $stringExpression; - /** - * @var InputParameter - */ + /** @var InputParameter */ public $stringPattern; - /** - * @var Literal|null - */ + /** @var Literal|null */ public $escapeChar; /** @@ -57,8 +47,8 @@ class LikeExpression extends Node public function __construct($stringExpression, $stringPattern, $escapeChar = null) { $this->stringExpression = $stringExpression; - $this->stringPattern = $stringPattern; - $this->escapeChar = $escapeChar; + $this->stringPattern = $stringPattern; + $this->escapeChar = $escapeChar; } /** diff --git a/lib/Doctrine/ORM/Query/AST/Literal.php b/lib/Doctrine/ORM/Query/AST/Literal.php index 43d71add08f..a87b6340801 100644 --- a/lib/Doctrine/ORM/Query/AST/Literal.php +++ b/lib/Doctrine/ORM/Query/AST/Literal.php @@ -1,4 +1,5 @@ type = $type; + $this->type = $type; $this->value = $value; } diff --git a/lib/Doctrine/ORM/Query/AST/NewObjectExpression.php b/lib/Doctrine/ORM/Query/AST/NewObjectExpression.php index ec011ce29f0..90ceabe78ca 100644 --- a/lib/Doctrine/ORM/Query/AST/NewObjectExpression.php +++ b/lib/Doctrine/ORM/Query/AST/NewObjectExpression.php @@ -1,4 +1,5 @@ */ class NewObjectExpression extends Node { - /** - * @var string - */ + /** @var string */ public $className; - /** - * @var array - */ + /** @var array */ public $args; /** diff --git a/lib/Doctrine/ORM/Query/AST/Node.php b/lib/Doctrine/ORM/Query/AST/Node.php index a257dc2d79c..f9337f40a0f 100644 --- a/lib/Doctrine/ORM/Query/AST/Node.php +++ b/lib/Doctrine/ORM/Query/AST/Node.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ abstract class Node { @@ -35,7 +43,7 @@ abstract class Node * * Implementation is not mandatory for all nodes. * - * @param \Doctrine\ORM\Query\SqlWalker $walker + * @param SqlWalker $walker * * @return string * @@ -68,21 +76,21 @@ public function dump($obj) $str = ''; if ($obj instanceof Node) { - $str .= get_class($obj) . '(' . PHP_EOL; + $str .= get_class($obj) . '(' . PHP_EOL; $props = get_object_vars($obj); foreach ($props as $name => $prop) { $ident += 4; - $str .= str_repeat(' ', $ident) . '"' . $name . '": ' + $str .= str_repeat(' ', $ident) . '"' . $name . '": ' . $this->dump($prop) . ',' . PHP_EOL; $ident -= 4; } $str .= str_repeat(' ', $ident) . ')'; - } else if (is_array($obj)) { + } elseif (is_array($obj)) { $ident += 4; - $str .= 'array('; - $some = false; + $str .= 'array('; + $some = false; foreach ($obj as $k => $v) { $str .= PHP_EOL . str_repeat(' ', $ident) . '"' @@ -91,8 +99,8 @@ public function dump($obj) } $ident -= 4; - $str .= ($some ? PHP_EOL . str_repeat(' ', $ident) : '') . ')'; - } else if (is_object($obj)) { + $str .= ($some ? PHP_EOL . str_repeat(' ', $ident) : '') . ')'; + } elseif (is_object($obj)) { $str .= 'instanceof(' . get_class($obj) . ')'; } else { $str .= var_export($obj, true); diff --git a/lib/Doctrine/ORM/Query/AST/NullComparisonExpression.php b/lib/Doctrine/ORM/Query/AST/NullComparisonExpression.php index 84a199784cc..557f43de222 100644 --- a/lib/Doctrine/ORM/Query/AST/NullComparisonExpression.php +++ b/lib/Doctrine/ORM/Query/AST/NullComparisonExpression.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class NullComparisonExpression extends Node { - /** - * @var bool - */ + /** @var bool */ public $not; - /** - * @var Node - */ + /** @var Node */ public $expression; /** diff --git a/lib/Doctrine/ORM/Query/AST/NullIfExpression.php b/lib/Doctrine/ORM/Query/AST/NullIfExpression.php index e33bc72b15e..0c4b2962555 100644 --- a/lib/Doctrine/ORM/Query/AST/NullIfExpression.php +++ b/lib/Doctrine/ORM/Query/AST/NullIfExpression.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class NullIfExpression extends Node { - /** - * @var mixed - */ + /** @var mixed */ public $firstExpression; - /** - * @var mixed - */ + /** @var mixed */ public $secondExpression; /** diff --git a/lib/Doctrine/ORM/Query/AST/OrderByClause.php b/lib/Doctrine/ORM/Query/AST/OrderByClause.php index e0e30e9d997..d4728346511 100644 --- a/lib/Doctrine/ORM/Query/AST/OrderByClause.php +++ b/lib/Doctrine/ORM/Query/AST/OrderByClause.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class OrderByClause extends Node { - /** - * @var array - */ + /** @var array */ public $orderByItems = []; /** diff --git a/lib/Doctrine/ORM/Query/AST/OrderByItem.php b/lib/Doctrine/ORM/Query/AST/OrderByItem.php index bf3288a7b9a..eeb6d2801a7 100644 --- a/lib/Doctrine/ORM/Query/AST/OrderByItem.php +++ b/lib/Doctrine/ORM/Query/AST/OrderByItem.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class OrderByItem extends Node { - /** - * @var mixed - */ + /** @var mixed */ public $expression; - /** - * @var string - */ + /** @var string */ public $type; /** @@ -54,7 +48,7 @@ public function __construct($expression) */ public function isAsc() { - return strtoupper($this->type) == 'ASC'; + return strtoupper($this->type) === 'ASC'; } /** @@ -62,7 +56,7 @@ public function isAsc() */ public function isDesc() { - return strtoupper($this->type) == 'DESC'; + return strtoupper($this->type) === 'DESC'; } /** diff --git a/lib/Doctrine/ORM/Query/AST/ParenthesisExpression.php b/lib/Doctrine/ORM/Query/AST/ParenthesisExpression.php index 307a5cce398..a77fd968927 100644 --- a/lib/Doctrine/ORM/Query/AST/ParenthesisExpression.php +++ b/lib/Doctrine/ORM/Query/AST/ParenthesisExpression.php @@ -22,20 +22,12 @@ /** * ParenthesisExpression ::= "(" ArithmeticPrimary ")" - * - * @author Fabio B. Silva - * @since 2.4 */ class ParenthesisExpression extends Node { - /** - * @var \Doctrine\ORM\Query\AST\Node - */ + /** @var Node */ public $expression; - /** - * @param \Doctrine\ORM\Query\AST\Node $expression - */ public function __construct(Node $expression) { $this->expression = $expression; diff --git a/lib/Doctrine/ORM/Query/AST/PartialObjectExpression.php b/lib/Doctrine/ORM/Query/AST/PartialObjectExpression.php index e4ffe79b2aa..68048797585 100644 --- a/lib/Doctrine/ORM/Query/AST/PartialObjectExpression.php +++ b/lib/Doctrine/ORM/Query/AST/PartialObjectExpression.php @@ -1,4 +1,5 @@ identificationVariable = $identificationVariable; - $this->partialFieldSet = $partialFieldSet; + $this->partialFieldSet = $partialFieldSet; } } diff --git a/lib/Doctrine/ORM/Query/AST/PathExpression.php b/lib/Doctrine/ORM/Query/AST/PathExpression.php index 37674b6fd47..bc37e3813d7 100644 --- a/lib/Doctrine/ORM/Query/AST/PathExpression.php +++ b/lib/Doctrine/ORM/Query/AST/PathExpression.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class PathExpression extends Node { - const TYPE_COLLECTION_VALUED_ASSOCIATION = 2; - const TYPE_SINGLE_VALUED_ASSOCIATION = 4; - const TYPE_STATE_FIELD = 8; + public const TYPE_COLLECTION_VALUED_ASSOCIATION = 2; + public const TYPE_SINGLE_VALUED_ASSOCIATION = 4; + public const TYPE_STATE_FIELD = 8; - /** - * @var int - */ + /** @var int */ public $type; - /** - * @var int - */ + /** @var int */ public $expectedType; - /** - * @var string - */ + /** @var string */ public $identificationVariable; - /** - * @var string|null - */ + /** @var string|null */ public $field; /** @@ -66,9 +54,9 @@ class PathExpression extends Node */ public function __construct($expectedType, $identificationVariable, $field = null) { - $this->expectedType = $expectedType; + $this->expectedType = $expectedType; $this->identificationVariable = $identificationVariable; - $this->field = $field; + $this->field = $field; } /** diff --git a/lib/Doctrine/ORM/Query/AST/QuantifiedExpression.php b/lib/Doctrine/ORM/Query/AST/QuantifiedExpression.php index 15be9523471..3427650814c 100644 --- a/lib/Doctrine/ORM/Query/AST/QuantifiedExpression.php +++ b/lib/Doctrine/ORM/Query/AST/QuantifiedExpression.php @@ -1,4 +1,5 @@ . */ + namespace Doctrine\ORM\Query\AST; +use function strtoupper; + /** * QuantifiedExpression ::= ("ALL" | "ANY" | "SOME") "(" Subselect ")" * * @link www.doctrine-project.org - * @since 2.0 - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class QuantifiedExpression extends Node { - /** - * @var string - */ + /** @var string */ public $type; - /** - * @var Subselect - */ + /** @var Subselect */ public $subselect; /** @@ -52,7 +48,7 @@ public function __construct($subselect) */ public function isAll() { - return strtoupper($this->type) == 'ALL'; + return strtoupper($this->type) === 'ALL'; } /** @@ -60,7 +56,7 @@ public function isAll() */ public function isAny() { - return strtoupper($this->type) == 'ANY'; + return strtoupper($this->type) === 'ANY'; } /** @@ -68,7 +64,7 @@ public function isAny() */ public function isSome() { - return strtoupper($this->type) == 'SOME'; + return strtoupper($this->type) === 'SOME'; } /** diff --git a/lib/Doctrine/ORM/Query/AST/RangeVariableDeclaration.php b/lib/Doctrine/ORM/Query/AST/RangeVariableDeclaration.php index 0ca5274d19e..b31f3198d74 100644 --- a/lib/Doctrine/ORM/Query/AST/RangeVariableDeclaration.php +++ b/lib/Doctrine/ORM/Query/AST/RangeVariableDeclaration.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class RangeVariableDeclaration extends Node { - /** - * @var string - */ + /** @var string */ public $abstractSchemaName; - /** - * @var string - */ + /** @var string */ public $aliasIdentificationVariable; - /** - * @var boolean - */ + /** @var bool */ public $isRoot; /** - * @param string $abstractSchemaName - * @param string $aliasIdentificationVar - * @param boolean $isRoot + * @param string $abstractSchemaName + * @param string $aliasIdentificationVar + * @param bool $isRoot */ public function __construct($abstractSchemaName, $aliasIdentificationVar, $isRoot = true) { diff --git a/lib/Doctrine/ORM/Query/AST/SelectClause.php b/lib/Doctrine/ORM/Query/AST/SelectClause.php index f8e6f472a1e..a57e2a118d4 100644 --- a/lib/Doctrine/ORM/Query/AST/SelectClause.php +++ b/lib/Doctrine/ORM/Query/AST/SelectClause.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class SelectClause extends Node { - /** - * @var bool - */ + /** @var bool */ public $isDistinct; - /** - * @var array - */ + /** @var array */ public $selectExpressions = []; /** @@ -46,7 +39,7 @@ class SelectClause extends Node */ public function __construct(array $selectExpressions, $isDistinct) { - $this->isDistinct = $isDistinct; + $this->isDistinct = $isDistinct; $this->selectExpressions = $selectExpressions; } diff --git a/lib/Doctrine/ORM/Query/AST/SelectExpression.php b/lib/Doctrine/ORM/Query/AST/SelectExpression.php index 4187013994a..053dc7c059e 100644 --- a/lib/Doctrine/ORM/Query/AST/SelectExpression.php +++ b/lib/Doctrine/ORM/Query/AST/SelectExpression.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class SelectExpression extends Node { - /** - * @var mixed - */ + /** @var mixed */ public $expression; - /** - * @var string|null - */ + /** @var string|null */ public $fieldIdentificationVariable; - /** - * @var bool - */ + /** @var bool */ public $hiddenAliasResultVariable; /** @@ -53,9 +44,9 @@ class SelectExpression extends Node */ public function __construct($expression, $fieldIdentificationVariable, $hiddenAliasResultVariable = false) { - $this->expression = $expression; + $this->expression = $expression; $this->fieldIdentificationVariable = $fieldIdentificationVariable; - $this->hiddenAliasResultVariable = $hiddenAliasResultVariable; + $this->hiddenAliasResultVariable = $hiddenAliasResultVariable; } /** diff --git a/lib/Doctrine/ORM/Query/AST/SelectStatement.php b/lib/Doctrine/ORM/Query/AST/SelectStatement.php index d84f7258a9f..33f954c2c89 100644 --- a/lib/Doctrine/ORM/Query/AST/SelectStatement.php +++ b/lib/Doctrine/ORM/Query/AST/SelectStatement.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class SelectStatement extends Node { - /** - * @var SelectClause - */ + /** @var SelectClause */ public $selectClause; - /** - * @var FromClause - */ + /** @var FromClause */ public $fromClause; - /** - * @var WhereClause|null - */ + /** @var WhereClause|null */ public $whereClause; - /** - * @var GroupByClause|null - */ + /** @var GroupByClause|null */ public $groupByClause; - /** - * @var HavingClause|null - */ + /** @var HavingClause|null */ public $havingClause; - /** - * @var OrderByClause|null - */ + /** @var OrderByClause|null */ public $orderByClause; /** @@ -67,7 +52,7 @@ class SelectStatement extends Node public function __construct($selectClause, $fromClause) { $this->selectClause = $selectClause; - $this->fromClause = $fromClause; + $this->fromClause = $fromClause; } /** diff --git a/lib/Doctrine/ORM/Query/AST/SimpleArithmeticExpression.php b/lib/Doctrine/ORM/Query/AST/SimpleArithmeticExpression.php index 80ecd15ce57..1b3355b86ea 100644 --- a/lib/Doctrine/ORM/Query/AST/SimpleArithmeticExpression.php +++ b/lib/Doctrine/ORM/Query/AST/SimpleArithmeticExpression.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class SimpleArithmeticExpression extends Node { - /** - * @var array - */ + /** @var array */ public $arithmeticTerms = []; /** diff --git a/lib/Doctrine/ORM/Query/AST/SimpleCaseExpression.php b/lib/Doctrine/ORM/Query/AST/SimpleCaseExpression.php index 67e354e5569..5d1861c0f57 100644 --- a/lib/Doctrine/ORM/Query/AST/SimpleCaseExpression.php +++ b/lib/Doctrine/ORM/Query/AST/SimpleCaseExpression.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class SimpleCaseExpression extends Node { - /** - * @var PathExpression - */ + /** @var PathExpression */ public $caseOperand = null; - /** - * @var array - */ + /** @var array */ public $simpleWhenClauses = []; - /** - * @var mixed - */ + /** @var mixed */ public $elseScalarExpression = null; /** @@ -54,8 +43,8 @@ class SimpleCaseExpression extends Node */ public function __construct($caseOperand, array $simpleWhenClauses, $elseScalarExpression) { - $this->caseOperand = $caseOperand; - $this->simpleWhenClauses = $simpleWhenClauses; + $this->caseOperand = $caseOperand; + $this->simpleWhenClauses = $simpleWhenClauses; $this->elseScalarExpression = $elseScalarExpression; } diff --git a/lib/Doctrine/ORM/Query/AST/SimpleSelectClause.php b/lib/Doctrine/ORM/Query/AST/SimpleSelectClause.php index 92361da45b7..64e113f3ef3 100644 --- a/lib/Doctrine/ORM/Query/AST/SimpleSelectClause.php +++ b/lib/Doctrine/ORM/Query/AST/SimpleSelectClause.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class SimpleSelectClause extends Node { - /** - * @var bool - */ + /** @var bool */ public $isDistinct = false; - /** - * @var SimpleSelectExpression - */ + /** @var SimpleSelectExpression */ public $simpleSelectExpression; /** @@ -47,7 +40,7 @@ class SimpleSelectClause extends Node public function __construct($simpleSelectExpression, $isDistinct) { $this->simpleSelectExpression = $simpleSelectExpression; - $this->isDistinct = $isDistinct; + $this->isDistinct = $isDistinct; } /** diff --git a/lib/Doctrine/ORM/Query/AST/SimpleSelectExpression.php b/lib/Doctrine/ORM/Query/AST/SimpleSelectExpression.php index afb98ab6bd2..416bedd2d7c 100644 --- a/lib/Doctrine/ORM/Query/AST/SimpleSelectExpression.php +++ b/lib/Doctrine/ORM/Query/AST/SimpleSelectExpression.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class SimpleSelectExpression extends Node { - /** - * @var Node|string - */ + /** @var Node|string */ public $expression; - /** - * @var string - */ + /** @var string */ public $fieldIdentificationVariable; /** diff --git a/lib/Doctrine/ORM/Query/AST/SimpleWhenClause.php b/lib/Doctrine/ORM/Query/AST/SimpleWhenClause.php index 4f60881d42a..8a2338884aa 100644 --- a/lib/Doctrine/ORM/Query/AST/SimpleWhenClause.php +++ b/lib/Doctrine/ORM/Query/AST/SimpleWhenClause.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class SimpleWhenClause extends Node { - /** - * @var mixed - */ + /** @var mixed */ public $caseScalarExpression = null; - /** - * @var mixed - */ + /** @var mixed */ public $thenScalarExpression = null; /** diff --git a/lib/Doctrine/ORM/Query/AST/Subselect.php b/lib/Doctrine/ORM/Query/AST/Subselect.php index ce08266f083..f11e938a077 100644 --- a/lib/Doctrine/ORM/Query/AST/Subselect.php +++ b/lib/Doctrine/ORM/Query/AST/Subselect.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class Subselect extends Node { - /** - * @var SimpleSelectClause - */ + /** @var SimpleSelectClause */ public $simpleSelectClause; - /** - * @var SubselectFromClause - */ + /** @var SubselectFromClause */ public $subselectFromClause; - /** - * @var WhereClause|null - */ + /** @var WhereClause|null */ public $whereClause; - /** - * @var GroupByClause|null - */ + /** @var GroupByClause|null */ public $groupByClause; - /** - * @var HavingClause|null - */ + /** @var HavingClause|null */ public $havingClause; - /** - * @var OrderByClause|null - */ + /** @var OrderByClause|null */ public $orderByClause; /** @@ -66,7 +51,7 @@ class Subselect extends Node */ public function __construct($simpleSelectClause, $subselectFromClause) { - $this->simpleSelectClause = $simpleSelectClause; + $this->simpleSelectClause = $simpleSelectClause; $this->subselectFromClause = $subselectFromClause; } diff --git a/lib/Doctrine/ORM/Query/AST/SubselectFromClause.php b/lib/Doctrine/ORM/Query/AST/SubselectFromClause.php index 9704061e8cd..8053406ed0e 100644 --- a/lib/Doctrine/ORM/Query/AST/SubselectFromClause.php +++ b/lib/Doctrine/ORM/Query/AST/SubselectFromClause.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class SubselectFromClause extends Node { - /** - * @var array - */ + /** @var array */ public $identificationVariableDeclarations = []; /** diff --git a/lib/Doctrine/ORM/Query/AST/SubselectIdentificationVariableDeclaration.php b/lib/Doctrine/ORM/Query/AST/SubselectIdentificationVariableDeclaration.php index 866f112226b..2a253629b1c 100644 --- a/lib/Doctrine/ORM/Query/AST/SubselectIdentificationVariableDeclaration.php +++ b/lib/Doctrine/ORM/Query/AST/SubselectIdentificationVariableDeclaration.php @@ -1,4 +1,5 @@ */ class SubselectIdentificationVariableDeclaration { - /** - * @var PathExpression - */ + /** @var PathExpression */ public $associationPathExpression; - /** - * @var string - */ + /** @var string */ public $aliasIdentificationVariable; /** - * Constructor. - * * @param PathExpression $associationPathExpression * @param string $aliasIdentificationVariable */ diff --git a/lib/Doctrine/ORM/Query/AST/TypedExpression.php b/lib/Doctrine/ORM/Query/AST/TypedExpression.php index 5fa72dc1c46..d71a1af75df 100644 --- a/lib/Doctrine/ORM/Query/AST/TypedExpression.php +++ b/lib/Doctrine/ORM/Query/AST/TypedExpression.php @@ -1,7 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class UpdateClause extends Node { - /** - * @var string - */ + /** @var string */ public $abstractSchemaName; - /** - * @var string - */ + /** @var string */ public $aliasIdentificationVariable; - /** - * @var array - */ + /** @var array */ public $updateItems = []; /** @@ -52,7 +43,7 @@ class UpdateClause extends Node public function __construct($abstractSchemaName, array $updateItems) { $this->abstractSchemaName = $abstractSchemaName; - $this->updateItems = $updateItems; + $this->updateItems = $updateItems; } /** diff --git a/lib/Doctrine/ORM/Query/AST/UpdateItem.php b/lib/Doctrine/ORM/Query/AST/UpdateItem.php index f1a288cae21..da02f168459 100644 --- a/lib/Doctrine/ORM/Query/AST/UpdateItem.php +++ b/lib/Doctrine/ORM/Query/AST/UpdateItem.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class UpdateItem extends Node { - /** - * @var PathExpression - */ + /** @var PathExpression */ public $pathExpression; - /** - * @var InputParameter|ArithmeticExpression|null - */ + /** @var InputParameter|ArithmeticExpression|null */ public $newValue; /** @@ -49,7 +42,7 @@ class UpdateItem extends Node public function __construct($pathExpression, $newValue) { $this->pathExpression = $pathExpression; - $this->newValue = $newValue; + $this->newValue = $newValue; } /** diff --git a/lib/Doctrine/ORM/Query/AST/UpdateStatement.php b/lib/Doctrine/ORM/Query/AST/UpdateStatement.php index c578efef487..5ff01fc8ec9 100644 --- a/lib/Doctrine/ORM/Query/AST/UpdateStatement.php +++ b/lib/Doctrine/ORM/Query/AST/UpdateStatement.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class UpdateStatement extends Node { - /** - * @var UpdateClause - */ + /** @var UpdateClause */ public $updateClause; - /** - * @var WhereClause|null - */ + /** @var WhereClause|null */ public $whereClause; /** diff --git a/lib/Doctrine/ORM/Query/AST/WhenClause.php b/lib/Doctrine/ORM/Query/AST/WhenClause.php index 01c0330f48c..e5a5820a790 100644 --- a/lib/Doctrine/ORM/Query/AST/WhenClause.php +++ b/lib/Doctrine/ORM/Query/AST/WhenClause.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class WhenClause extends Node { - /** - * @var ConditionalExpression - */ + /** @var ConditionalExpression */ public $caseConditionExpression = null; - /** - * @var mixed - */ + /** @var mixed */ public $thenScalarExpression = null; /** @@ -49,7 +40,7 @@ class WhenClause extends Node public function __construct($caseConditionExpression, $thenScalarExpression) { $this->caseConditionExpression = $caseConditionExpression; - $this->thenScalarExpression = $thenScalarExpression; + $this->thenScalarExpression = $thenScalarExpression; } /** diff --git a/lib/Doctrine/ORM/Query/AST/WhereClause.php b/lib/Doctrine/ORM/Query/AST/WhereClause.php index dab80580e8b..36421d86d65 100644 --- a/lib/Doctrine/ORM/Query/AST/WhereClause.php +++ b/lib/Doctrine/ORM/Query/AST/WhereClause.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class WhereClause extends Node { - /** - * @var ConditionalExpression|ConditionalTerm - */ + /** @var ConditionalExpression|ConditionalTerm */ public $conditionalExpression; /** diff --git a/lib/Doctrine/ORM/Query/Exec/AbstractSqlExecutor.php b/lib/Doctrine/ORM/Query/Exec/AbstractSqlExecutor.php index ee2af6ef292..662587dadc8 100644 --- a/lib/Doctrine/ORM/Query/Exec/AbstractSqlExecutor.php +++ b/lib/Doctrine/ORM/Query/Exec/AbstractSqlExecutor.php @@ -1,4 +1,5 @@ - * @license http://www.opensource.org/licenses/mit-license.php MIT * @link http://www.doctrine-project.org - * @since 2.0 + * * @todo Rename: AbstractSQLExecutor */ abstract class AbstractSqlExecutor { - /** - * @var mixed[]|string - */ + /** @var mixed[]|string */ protected $_sqlStatements; - /** - * @var QueryCacheProfile - */ + /** @var QueryCacheProfile */ protected $queryCacheProfile; /** @@ -54,8 +50,6 @@ public function getSqlStatements() } /** - * @param \Doctrine\DBAL\Cache\QueryCacheProfile $qcp - * * @return void */ public function setQueryCacheProfile(QueryCacheProfile $qcp) @@ -80,7 +74,7 @@ public function removeQueryCacheProfile() * @param array $params The parameters. * @param array $types The parameter types. * - * @return \Doctrine\DBAL\Driver\Statement + * @return Statement */ abstract public function execute(Connection $conn, array $params, array $types); } diff --git a/lib/Doctrine/ORM/Query/Exec/MultiTableDeleteExecutor.php b/lib/Doctrine/ORM/Query/Exec/MultiTableDeleteExecutor.php index a6b9ef2fe41..c955833662a 100644 --- a/lib/Doctrine/ORM/Query/Exec/MultiTableDeleteExecutor.php +++ b/lib/Doctrine/ORM/Query/Exec/MultiTableDeleteExecutor.php @@ -1,4 +1,5 @@ - * @license http://www.opensource.org/licenses/mit-license.php MIT * @link http://www.doctrine-project.org - * @since 2.0 */ class MultiTableDeleteExecutor extends AbstractSqlExecutor { - /** - * @var string - */ + /** @var string */ private $_createTempTableSql; - /** - * @var string - */ + /** @var string */ private $_dropTempTableSql; - /** - * @var string - */ + /** @var string */ private $_insertSql; /** @@ -64,18 +60,18 @@ class MultiTableDeleteExecutor extends AbstractSqlExecutor */ public function __construct(AST\Node $AST, $sqlWalker) { - $em = $sqlWalker->getEntityManager(); - $conn = $em->getConnection(); - $platform = $conn->getDatabasePlatform(); - $quoteStrategy = $em->getConfiguration()->getQuoteStrategy(); + $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->rootEntityName); - $tempTable = $platform->getTemporaryTableName($rootClass->getTemporaryIdTableName()); - $idColumnNames = $rootClass->getIdentifierColumnNames(); - $idColumnList = implode(', ', $idColumnNames); + $tempTable = $platform->getTemporaryTableName($rootClass->getTemporaryIdTableName()); + $idColumnNames = $rootClass->getIdentifierColumnNames(); + $idColumnList = implode(', ', $idColumnNames); // 1. Create an INSERT INTO temptable ... SELECT identifiers WHERE $AST->getWhereClause() $sqlWalker->setSQLTableAlias($primaryClass->getTableName(), 't0', $primaryDqlAlias); @@ -83,8 +79,8 @@ public function __construct(AST\Node $AST, $sqlWalker) $this->_insertSql = 'INSERT INTO ' . $tempTable . ' (' . $idColumnList . ')' . ' SELECT t0.' . implode(', t0.', $idColumnNames); - $rangeDecl = new AST\RangeVariableDeclaration($primaryClass->name, $primaryDqlAlias); - $fromClause = new AST\FromClause([new AST\IdentificationVariableDeclaration($rangeDecl, null, [])]); + $rangeDecl = new AST\RangeVariableDeclaration($primaryClass->name, $primaryDqlAlias); + $fromClause = new AST\FromClause([new AST\IdentificationVariableDeclaration($rangeDecl, null, [])]); $this->_insertSql .= $sqlWalker->walkFromClause($fromClause); // Append WHERE clause, if there is one. @@ -98,7 +94,7 @@ public function __construct(AST\Node $AST, $sqlWalker) // 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); + $tableName = $quoteStrategy->getTableName($em->getClassMetadata($className), $platform); $this->_sqlStatements[] = 'DELETE FROM ' . $tableName . ' WHERE (' . $idColumnList . ') IN (' . $idSubselect . ')'; } @@ -111,9 +107,10 @@ public function __construct(AST\Node $AST, $sqlWalker) 'type' => Type::getType(PersisterHelper::getTypeOfColumn($idColumnName, $rootClass, $em)), ]; } + $this->_createTempTableSql = $platform->getCreateTemporaryTableSnippetSQL() . ' ' . $tempTable . ' (' . $platform->getColumnDeclarationListSQL($columnDefinitions) . ')'; - $this->_dropTempTableSql = $platform->getDropTemporaryTableSQL($tempTable); + $this->_dropTempTableSql = $platform->getDropTemporaryTableSQL($tempTable); } /** diff --git a/lib/Doctrine/ORM/Query/Exec/MultiTableUpdateExecutor.php b/lib/Doctrine/ORM/Query/Exec/MultiTableUpdateExecutor.php index 53d13304f3e..3dbb34f836a 100644 --- a/lib/Doctrine/ORM/Query/Exec/MultiTableUpdateExecutor.php +++ b/lib/Doctrine/ORM/Query/Exec/MultiTableUpdateExecutor.php @@ -1,4 +1,5 @@ - * @since 2.0 */ class MultiTableUpdateExecutor extends AbstractSqlExecutor { - /** - * @var string - */ + /** @var string */ private $_createTempTableSql; - /** - * @var string - */ + /** @var string */ private $_dropTempTableSql; - /** - * @var string - */ + /** @var string */ private $_insertSql; - /** - * @var array - */ + /** @var array */ private $_sqlParameters = []; - /** - * @var int - */ + /** @var int */ private $_numParametersInUpdateClause = 0; /** @@ -73,20 +66,20 @@ class MultiTableUpdateExecutor extends AbstractSqlExecutor */ public function __construct(AST\Node $AST, $sqlWalker) { - $em = $sqlWalker->getEntityManager(); - $conn = $em->getConnection(); - $platform = $conn->getDatabasePlatform(); - $quoteStrategy = $em->getConfiguration()->getQuoteStrategy(); + $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); + $updateClause = $AST->updateClause; + $primaryClass = $sqlWalker->getEntityManager()->getClassMetadata($updateClause->abstractSchemaName); + $rootClass = $em->getClassMetadata($primaryClass->rootEntityName); - $updateItems = $updateClause->updateItems; + $updateItems = $updateClause->updateItems; - $tempTable = $platform->getTemporaryTableName($rootClass->getTemporaryIdTableName()); - $idColumnNames = $rootClass->getIdentifierColumnNames(); - $idColumnList = implode(', ', $idColumnNames); + $tempTable = $platform->getTemporaryTableName($rootClass->getTemporaryIdTableName()); + $idColumnNames = $rootClass->getIdentifierColumnNames(); + $idColumnList = implode(', ', $idColumnNames); // 1. Create an INSERT INTO temptable ... SELECT identifiers WHERE $AST->getWhereClause() $sqlWalker->setSQLTableAlias($primaryClass->getTableName(), 't0', $updateClause->aliasIdentificationVariable); @@ -94,7 +87,7 @@ public function __construct(AST\Node $AST, $sqlWalker) $this->_insertSql = 'INSERT INTO ' . $tempTable . ' (' . $idColumnList . ')' . ' SELECT t0.' . implode(', t0.', $idColumnNames); - $rangeDecl = new AST\RangeVariableDeclaration($primaryClass->name, $updateClause->aliasIdentificationVariable); + $rangeDecl = new AST\RangeVariableDeclaration($primaryClass->name, $updateClause->aliasIdentificationVariable); $fromClause = new AST\FromClause([new AST\IdentificationVariableDeclaration($rangeDecl, null, [])]); $this->_insertSql .= $sqlWalker->walkFromClause($fromClause); @@ -104,21 +97,23 @@ public function __construct(AST\Node $AST, $sqlWalker) // 3. Create and store UPDATE statements $classNames = array_merge($primaryClass->parentClasses, [$primaryClass->name], $primaryClass->subClasses); - $i = -1; + $i = -1; foreach (array_reverse($classNames) as $className) { - $affected = false; - $class = $em->getClassMetadata($className); + $affected = false; + $class = $em->getClassMetadata($className); $updateSql = 'UPDATE ' . $quoteStrategy->getTableName($class, $platform) . ' SET '; 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']))) { + if ( + (isset($class->fieldMappings[$field]) && ! isset($class->fieldMappings[$field]['inherited'])) || + (isset($class->associationMappings[$field]) && ! isset($class->associationMappings[$field]['inherited'])) + ) { $newValue = $updateItem->newValue; - if ( ! $affected) { + if (! $affected) { $affected = true; ++$i; } else { diff --git a/lib/Doctrine/ORM/Query/Exec/SingleSelectExecutor.php b/lib/Doctrine/ORM/Query/Exec/SingleSelectExecutor.php index 91827ab1adc..25977dff714 100644 --- a/lib/Doctrine/ORM/Query/Exec/SingleSelectExecutor.php +++ b/lib/Doctrine/ORM/Query/Exec/SingleSelectExecutor.php @@ -1,4 +1,5 @@ * @link www.doctrine-project.org - * @since 2.0 */ class SingleSelectExecutor extends AbstractSqlExecutor { - /** - * @param \Doctrine\ORM\Query\AST\SelectStatement $AST - * @param \Doctrine\ORM\Query\SqlWalker $sqlWalker - */ public function __construct(SelectStatement $AST, SqlWalker $sqlWalker) { $this->_sqlStatements = $sqlWalker->walkSelectStatement($AST); diff --git a/lib/Doctrine/ORM/Query/Exec/SingleTableDeleteUpdateExecutor.php b/lib/Doctrine/ORM/Query/Exec/SingleTableDeleteUpdateExecutor.php index a457f6de9b8..404ae994e55 100644 --- a/lib/Doctrine/ORM/Query/Exec/SingleTableDeleteUpdateExecutor.php +++ b/lib/Doctrine/ORM/Query/Exec/SingleTableDeleteUpdateExecutor.php @@ -1,4 +1,5 @@ * @link www.doctrine-project.org - * @since 2.0 + * * @todo This is exactly the same as SingleSelectExecutor. Unify in SingleStatementExecutor. */ class SingleTableDeleteUpdateExecutor extends AbstractSqlExecutor { /** - * @param \Doctrine\ORM\Query\AST\Node $AST - * @param \Doctrine\ORM\Query\SqlWalker $sqlWalker + * @param SqlWalker $sqlWalker */ public function __construct(AST\Node $AST, $sqlWalker) { if ($AST instanceof AST\UpdateStatement) { $this->_sqlStatements = $sqlWalker->walkUpdateStatement($AST); - } else if ($AST instanceof AST\DeleteStatement) { + } elseif ($AST instanceof AST\DeleteStatement) { $this->_sqlStatements = $sqlWalker->walkDeleteStatement($AST); } } diff --git a/lib/Doctrine/ORM/Query/Expr.php b/lib/Doctrine/ORM/Query/Expr.php index 7beb681364f..d971589baf4 100644 --- a/lib/Doctrine/ORM/Query/Expr.php +++ b/lib/Doctrine/ORM/Query/Expr.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel - * @author Benjamin Eberlei + * * @todo Rename: ExpressionBuilder */ class Expr @@ -452,7 +456,7 @@ public function in($x, $y) } foreach ($y as &$literal) { - if ( ! ($literal instanceof Expr\Literal)) { + if (! ($literal instanceof Expr\Literal)) { $literal = $this->_quoteLiteral($literal); } } @@ -477,7 +481,7 @@ public function notIn($x, $y) } foreach ($y as &$literal) { - if ( ! ($literal instanceof Expr\Literal)) { + if (! ($literal instanceof Expr\Literal)) { $literal = $this->_quoteLiteral($literal); } } @@ -539,7 +543,7 @@ public function notLike($x, $y) /** * Creates a CONCAT() function expression with the given arguments. * - * @param mixed $x First argument to be used in CONCAT() function. + * @param mixed $x First argument to be used in CONCAT() function. * @param mixed $y,... Other arguments to be used in CONCAT() function. * * @return Expr\Func @@ -561,7 +565,7 @@ public function concat($x, $y) public function substring($x, $from, $len = null) { $args = [$x, $from]; - if (null !== $len) { + if ($len !== null) { $args[] = $len; } @@ -625,10 +629,10 @@ public function literal($literal) */ private function _quoteLiteral($literal) { - if (is_numeric($literal) && !is_string($literal)) { + if (is_numeric($literal) && ! is_string($literal)) { return (string) $literal; - } else if (is_bool($literal)) { - return $literal ? "true" : "false"; + } elseif (is_bool($literal)) { + return $literal ? 'true' : 'false'; } return "'" . str_replace("'", "''", $literal) . "'"; @@ -637,9 +641,9 @@ private function _quoteLiteral($literal) /** * Creates an instance of BETWEEN() function, with the given argument. * - * @param mixed $val Valued to be inspected by range values. - * @param integer|string $x Starting range value to be used in BETWEEN() function. - * @param integer|string $y End point value to be used in BETWEEN() function. + * @param mixed $val Valued to be inspected by range values. + * @param int|string $x Starting range value to be used in BETWEEN() function. + * @param int|string $y End point value to be used in BETWEEN() function. * * @return string A BETWEEN expression. */ diff --git a/lib/Doctrine/ORM/Query/Expr/Andx.php b/lib/Doctrine/ORM/Query/Expr/Andx.php index dd91916a671..de6b1bc6507 100644 --- a/lib/Doctrine/ORM/Query/Expr/Andx.php +++ b/lib/Doctrine/ORM/Query/Expr/Andx.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class Andx extends Composite { - /** - * @var string - */ + /** @var string */ protected $separator = ' AND '; - /** - * @var array - */ + /** @var array */ protected $allowedClasses = [ Comparison::class, Func::class, Orx::class, - Andx::class, + self::class, ]; /** diff --git a/lib/Doctrine/ORM/Query/Expr/Base.php b/lib/Doctrine/ORM/Query/Expr/Base.php index 7ac660e5a93..b25c649ca07 100644 --- a/lib/Doctrine/ORM/Query/Expr/Base.php +++ b/lib/Doctrine/ORM/Query/Expr/Base.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ abstract class Base { - /** - * @var string - */ + /** @var string */ protected $preSeparator = '('; - /** - * @var string - */ + /** @var string */ protected $separator = ', '; - /** - * @var string - */ + /** @var string */ protected $postSeparator = ')'; - /** - * @var array - */ + /** @var array */ protected $allowedClasses = []; - /** - * @var array - */ + /** @var array */ protected $parts = []; /** @@ -82,17 +77,17 @@ public function addMultiple($args = []) * * @return static * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public function add($arg) { - if ( $arg !== null && (!$arg instanceof self || $arg->count() > 0) ) { + if ($arg !== null && (! $arg instanceof self || $arg->count() > 0)) { // If we decide to keep Expr\Base instances, we can use this check - if ( ! is_string($arg)) { + if (! is_string($arg)) { $class = get_class($arg); - if ( ! in_array($class, $this->allowedClasses)) { - throw new \InvalidArgumentException("Expression of type '$class' not allowed in this context."); + if (! in_array($class, $this->allowedClasses)) { + throw new InvalidArgumentException("Expression of type '$class' not allowed in this context."); } } @@ -103,7 +98,7 @@ public function add($arg) } /** - * @return integer + * @return int */ public function count() { @@ -115,7 +110,7 @@ public function count() */ public function __toString() { - if ($this->count() == 1) { + if ($this->count() === 1) { 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..7122bb17ea2 100644 --- a/lib/Doctrine/ORM/Query/Expr/Comparison.php +++ b/lib/Doctrine/ORM/Query/Expr/Comparison.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class Comparison { - const EQ = '='; - const NEQ = '<>'; - const LT = '<'; - const LTE = '<='; - const GT = '>'; - const GTE = '>='; + public const EQ = '='; + public const NEQ = '<>'; + public const LT = '<'; + public const LTE = '<='; + public const GT = '>'; + public const GTE = '>='; - /** - * @var mixed - */ + /** @var mixed */ protected $leftExpr; - /** - * @var string - */ + /** @var string */ protected $operator; - /** - * @var mixed - */ + /** @var mixed */ protected $rightExpr; /** * Creates a comparison expression with the given arguments. - * + * * @param mixed $leftExpr * @param string $operator * @param mixed $rightExpr diff --git a/lib/Doctrine/ORM/Query/Expr/Composite.php b/lib/Doctrine/ORM/Query/Expr/Composite.php index 635d8aa8fe9..27658a7ff3f 100644 --- a/lib/Doctrine/ORM/Query/Expr/Composite.php +++ b/lib/Doctrine/ORM/Query/Expr/Composite.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class Composite extends Base { diff --git a/lib/Doctrine/ORM/Query/Expr/From.php b/lib/Doctrine/ORM/Query/Expr/From.php index 9dcce9bbe27..caecc90277f 100644 --- a/lib/Doctrine/ORM/Query/Expr/From.php +++ b/lib/Doctrine/ORM/Query/Expr/From.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class From { - /** - * @var string - */ + /** @var string */ protected $from; - /** - * @var string - */ + /** @var string */ protected $alias; - /** - * @var string - */ + /** @var string */ protected $indexBy; /** diff --git a/lib/Doctrine/ORM/Query/Expr/Func.php b/lib/Doctrine/ORM/Query/Expr/Func.php index b4ed07cd3b2..6ae37bf24ff 100644 --- a/lib/Doctrine/ORM/Query/Expr/Func.php +++ b/lib/Doctrine/ORM/Query/Expr/Func.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class Func { - /** - * @var string - */ + /** @var string */ protected $name; - /** - * @var array - */ + /** @var array */ protected $arguments; /** @@ -48,12 +43,12 @@ class Func */ public function __construct($name, $arguments) { - $this->name = $name; - $this->arguments = (array) $arguments; + $this->name = $name; + $this->arguments = (array) $arguments; } /** - * @return string + * @return string */ public function getName() { diff --git a/lib/Doctrine/ORM/Query/Expr/GroupBy.php b/lib/Doctrine/ORM/Query/Expr/GroupBy.php index efa3582bdb2..d723c59dd8a 100644 --- a/lib/Doctrine/ORM/Query/Expr/GroupBy.php +++ b/lib/Doctrine/ORM/Query/Expr/GroupBy.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class GroupBy extends Base { - /** - * @var string - */ - protected $preSeparator = ''; + /** @var string */ + protected $preSeparator = ''; - /** - * @var string - */ + /** @var string */ protected $postSeparator = ''; /** diff --git a/lib/Doctrine/ORM/Query/Expr/Join.php b/lib/Doctrine/ORM/Query/Expr/Join.php index 7a59e247ae0..d9b76dcdb1e 100644 --- a/lib/Doctrine/ORM/Query/Expr/Join.php +++ b/lib/Doctrine/ORM/Query/Expr/Join.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class Join { - const INNER_JOIN = 'INNER'; - const LEFT_JOIN = 'LEFT'; + public const INNER_JOIN = 'INNER'; + public const LEFT_JOIN = 'LEFT'; - const ON = 'ON'; - const WITH = 'WITH'; + public const ON = 'ON'; + public const WITH = 'WITH'; - /** - * @var string - */ + /** @var string */ protected $joinType; - /** - * @var string - */ + /** @var string */ protected $join; - /** - * @var string - */ + /** @var string */ protected $alias; - /** - * @var string - */ + /** @var string */ protected $conditionType; - /** - * @var string - */ + /** @var string */ protected $condition; - /** - * @var string - */ + /** @var string */ protected $indexBy; /** @@ -76,16 +63,16 @@ class Join */ public function __construct($joinType, $join, $alias = null, $conditionType = null, $condition = null, $indexBy = null) { - $this->joinType = $joinType; - $this->join = $join; - $this->alias = $alias; - $this->conditionType = $conditionType; - $this->condition = $condition; - $this->indexBy = $indexBy; + $this->joinType = $joinType; + $this->join = $join; + $this->alias = $alias; + $this->conditionType = $conditionType; + $this->condition = $condition; + $this->indexBy = $indexBy; } /** - * @return string + * @return string */ public function getJoinType() { diff --git a/lib/Doctrine/ORM/Query/Expr/Literal.php b/lib/Doctrine/ORM/Query/Expr/Literal.php index 98cee79d7ed..9f81b188e68 100644 --- a/lib/Doctrine/ORM/Query/Expr/Literal.php +++ b/lib/Doctrine/ORM/Query/Expr/Literal.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class Literal extends Base { - /** - * @var string - */ - protected $preSeparator = ''; + /** @var string */ + protected $preSeparator = ''; - /** - * @var string - */ + /** @var string */ protected $postSeparator = ''; /** diff --git a/lib/Doctrine/ORM/Query/Expr/Math.php b/lib/Doctrine/ORM/Query/Expr/Math.php index 9bf800de8fe..144bf789f78 100644 --- a/lib/Doctrine/ORM/Query/Expr/Math.php +++ b/lib/Doctrine/ORM/Query/Expr/Math.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class Math { - /** - * @var mixed - */ + /** @var mixed */ protected $leftExpr; - /** - * @var string - */ + /** @var string */ protected $operator; - /** - * @var mixed - */ + /** @var mixed */ protected $rightExpr; /** diff --git a/lib/Doctrine/ORM/Query/Expr/OrderBy.php b/lib/Doctrine/ORM/Query/Expr/OrderBy.php index a5f8ef95765..258db2c025d 100644 --- a/lib/Doctrine/ORM/Query/Expr/OrderBy.php +++ b/lib/Doctrine/ORM/Query/Expr/OrderBy.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class OrderBy { - /** - * @var string - */ + /** @var string */ protected $preSeparator = ''; - /** - * @var string - */ + /** @var string */ protected $separator = ', '; - /** - * @var string - */ + /** @var string */ protected $postSeparator = ''; - /** - * @var array - */ + /** @var array */ protected $allowedClasses = []; - /** - * @var array - */ + /** @var array */ protected $parts = []; /** @@ -74,12 +64,12 @@ public function __construct($sort = null, $order = null) */ public function add($sort, $order = null) { - $order = ! $order ? 'ASC' : $order; - $this->parts[] = $sort . ' '. $order; + $order = ! $order ? 'ASC' : $order; + $this->parts[] = $sort . ' ' . $order; } /** - * @return integer + * @return int */ public function count() { diff --git a/lib/Doctrine/ORM/Query/Expr/Orx.php b/lib/Doctrine/ORM/Query/Expr/Orx.php index d36abfa922c..0b847353259 100644 --- a/lib/Doctrine/ORM/Query/Expr/Orx.php +++ b/lib/Doctrine/ORM/Query/Expr/Orx.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class Orx extends Composite { - /** - * @var string - */ + /** @var string */ protected $separator = ' OR '; - /** - * @var array - */ + /** @var array */ protected $allowedClasses = [ Comparison::class, Func::class, Andx::class, - Orx::class, + self::class, ]; /** diff --git a/lib/Doctrine/ORM/Query/Expr/Select.php b/lib/Doctrine/ORM/Query/Expr/Select.php index 8ab5153f1f6..495fa7e0853 100644 --- a/lib/Doctrine/ORM/Query/Expr/Select.php +++ b/lib/Doctrine/ORM/Query/Expr/Select.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class Select extends Base { - /** - * @var string - */ + /** @var string */ protected $preSeparator = ''; - /** - * @var string - */ + /** @var string */ protected $postSeparator = ''; - /** - * @var array - */ + /** @var array */ protected $allowedClasses = [Func::class]; /** diff --git a/lib/Doctrine/ORM/Query/Filter/SQLFilter.php b/lib/Doctrine/ORM/Query/Filter/SQLFilter.php index c12a7cb2151..3c7dcdbf548 100644 --- a/lib/Doctrine/ORM/Query/Filter/SQLFilter.php +++ b/lib/Doctrine/ORM/Query/Filter/SQLFilter.php @@ -1,4 +1,5 @@ - * @author Benjamin Eberlei * @abstract */ abstract class SQLFilter @@ -69,9 +73,9 @@ final public function __construct(EntityManagerInterface $em) * * @return self The current SQL filter. */ - final public function setParameter($name, $value, $type = null) : self + final public function setParameter($name, $value, $type = null): self { - if (null === $type) { + if ($type === null) { $type = ParameterTypeInferer::inferType($value); } @@ -96,12 +100,12 @@ final public function setParameter($name, $value, $type = null) : self * * @return string The SQL escaped parameter to use in a query. * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ final public function getParameter($name) { - if (!isset($this->parameters[$name])) { - throw new \InvalidArgumentException("Parameter '" . $name . "' does not exist."); + if (! isset($this->parameters[$name])) { + throw new InvalidArgumentException("Parameter '" . $name . "' does not exist."); } return $this->em->getConnection()->quote($this->parameters[$name]['value'], $this->parameters[$name]['type']); @@ -112,11 +116,11 @@ final public function getParameter($name) * * @param string $name Name of the parameter. * - * @return boolean + * @return bool */ final public function hasParameter($name) { - if (!isset($this->parameters[$name])) { + if (! isset($this->parameters[$name])) { return false; } @@ -136,7 +140,7 @@ final public function __toString() /** * Returns the database connection used by the entity manager * - * @return \Doctrine\DBAL\Connection + * @return Connection */ final protected function getConnection() { @@ -146,8 +150,7 @@ final protected function getConnection() /** * Gets the SQL query part to add to a query. * - * @param ClassMetaData $targetEntity - * @param string $targetTableAlias + * @param string $targetTableAlias * * @return string The constraint SQL if there is available, empty string otherwise. */ diff --git a/lib/Doctrine/ORM/Query/FilterCollection.php b/lib/Doctrine/ORM/Query/FilterCollection.php index c5f627e8396..43efd128cc9 100644 --- a/lib/Doctrine/ORM/Query/FilterCollection.php +++ b/lib/Doctrine/ORM/Query/FilterCollection.php @@ -1,4 +1,5 @@ */ class FilterCollection { @@ -34,59 +39,50 @@ class FilterCollection /** * A filter object is in CLEAN state when it has no changed parameters. */ - const FILTERS_STATE_CLEAN = 1; + public const FILTERS_STATE_CLEAN = 1; /** * A filter object is in DIRTY state when it has changed parameters. */ - const FILTERS_STATE_DIRTY = 2; + public const FILTERS_STATE_DIRTY = 2; /** * The used Configuration. * - * @var \Doctrine\ORM\Configuration + * @var Configuration */ private $config; /** * The EntityManager that "owns" this FilterCollection instance. * - * @var \Doctrine\ORM\EntityManager + * @var EntityManager */ private $em; /** * Instances of enabled filters. * - * @var \Doctrine\ORM\Query\Filter\SQLFilter[] + * @var SQLFilter[] */ private $enabledFilters = []; - /** - * @var string The filter hash from the last time the query was parsed. - */ + /** @var string The filter hash from the last time the query was parsed. */ private $filterHash; - /** - * @var integer The current state of this filter. - */ + /** @var int The current state of this filter. */ private $filtersState = self::FILTERS_STATE_CLEAN; - /** - * Constructor. - * - * @param EntityManagerInterface $em - */ public function __construct(EntityManagerInterface $em) { - $this->em = $em; + $this->em = $em; $this->config = $em->getConfiguration(); } /** * Gets all the enabled filters. * - * @return \Doctrine\ORM\Query\Filter\SQLFilter[] The enabled filters. + * @return SQLFilter[] The enabled filters. */ public function getEnabledFilters() { @@ -98,17 +94,17 @@ public function getEnabledFilters() * * @param string $name Name of the filter. * - * @return \Doctrine\ORM\Query\Filter\SQLFilter The enabled filter. + * @return SQLFilter The enabled filter. * - * @throws \InvalidArgumentException If the filter does not exist. + * @throws InvalidArgumentException If the filter does not exist. */ public function enable($name) { - if ( ! $this->has($name)) { - throw new \InvalidArgumentException("Filter '" . $name . "' does not exist."); + if (! $this->has($name)) { + throw new InvalidArgumentException("Filter '" . $name . "' does not exist."); } - if ( ! $this->isEnabled($name)) { + if (! $this->isEnabled($name)) { $filterClass = $this->config->getFilterClassName($name); assert($filterClass !== null); @@ -130,9 +126,9 @@ public function enable($name) * * @param string $name Name of the filter. * - * @return \Doctrine\ORM\Query\Filter\SQLFilter The disabled filter. + * @return SQLFilter The disabled filter. * - * @throws \InvalidArgumentException If the filter does not exist. + * @throws InvalidArgumentException If the filter does not exist. */ public function disable($name) { @@ -152,14 +148,14 @@ public function disable($name) * * @param string $name Name of the filter. * - * @return \Doctrine\ORM\Query\Filter\SQLFilter The filter. + * @return SQLFilter The filter. * - * @throws \InvalidArgumentException If the filter is not enabled. + * @throws InvalidArgumentException If the filter is not enabled. */ public function getFilter($name) { - if ( ! $this->isEnabled($name)) { - throw new \InvalidArgumentException("Filter '" . $name . "' is not enabled."); + if (! $this->isEnabled($name)) { + throw new InvalidArgumentException("Filter '" . $name . "' is not enabled."); } return $this->enabledFilters[$name]; @@ -174,7 +170,7 @@ public function getFilter($name) */ public function has($name) { - return null !== $this->config->getFilterClassName($name); + return $this->config->getFilterClassName($name) !== null; } /** @@ -182,7 +178,7 @@ public function has($name) * * @param string $name Name of the filter. * - * @return boolean True if the filter is enabled, false otherwise. + * @return bool True if the filter is enabled, false otherwise. */ public function isEnabled($name) { @@ -190,11 +186,11 @@ public function isEnabled($name) } /** - * @return boolean True, if the filter collection is clean. + * @return bool True, if the filter collection is clean. */ public function isClean() { - return self::FILTERS_STATE_CLEAN === $this->filtersState; + return $this->filtersState === self::FILTERS_STATE_CLEAN; } /** @@ -205,7 +201,7 @@ public function isClean() public function getHash() { // If there are only clean filters, the previous hash can be returned - if (self::FILTERS_STATE_CLEAN === $this->filtersState) { + if ($this->filtersState === self::FILTERS_STATE_CLEAN) { return $this->filterHash; } diff --git a/lib/Doctrine/ORM/Query/Lexer.php b/lib/Doctrine/ORM/Query/Lexer.php index 4f18e4aec0d..cdc6b6407c6 100644 --- a/lib/Doctrine/ORM/Query/Lexer.php +++ b/lib/Doctrine/ORM/Query/Lexer.php @@ -1,4 +1,5 @@ - * @author Janne Vanhala - * @author Roman Borschel - * @since 2.0 */ class Lexer extends AbstractLexer { // All tokens that are not valid identifiers must be < 100 - const T_NONE = 1; - const T_INTEGER = 2; - const T_STRING = 3; - const T_INPUT_PARAMETER = 4; - const T_FLOAT = 5; - const T_CLOSE_PARENTHESIS = 6; - const T_OPEN_PARENTHESIS = 7; - const T_COMMA = 8; - const T_DIVIDE = 9; - const T_DOT = 10; - const T_EQUALS = 11; - const T_GREATER_THAN = 12; - const T_LOWER_THAN = 13; - const T_MINUS = 14; - const T_MULTIPLY = 15; - const T_NEGATE = 16; - const T_PLUS = 17; - const T_OPEN_CURLY_BRACE = 18; - const T_CLOSE_CURLY_BRACE = 19; + public const T_NONE = 1; + public const T_INTEGER = 2; + public const T_STRING = 3; + public const T_INPUT_PARAMETER = 4; + public const T_FLOAT = 5; + public const T_CLOSE_PARENTHESIS = 6; + public const T_OPEN_PARENTHESIS = 7; + public const T_COMMA = 8; + public const T_DIVIDE = 9; + public const T_DOT = 10; + public const T_EQUALS = 11; + public const T_GREATER_THAN = 12; + public const T_LOWER_THAN = 13; + public const T_MINUS = 14; + public const T_MULTIPLY = 15; + public const T_NEGATE = 16; + public const T_PLUS = 17; + public const T_OPEN_CURLY_BRACE = 18; + public const T_CLOSE_CURLY_BRACE = 19; // All tokens that are identifiers or keywords that could be considered as identifiers should be >= 100 - const T_ALIASED_NAME = 100; - const T_FULLY_QUALIFIED_NAME = 101; - const T_IDENTIFIER = 102; + public const T_ALIASED_NAME = 100; + public const T_FULLY_QUALIFIED_NAME = 101; + public const T_IDENTIFIER = 102; // All keyword tokens should be >= 200 - const T_ALL = 200; - const T_AND = 201; - const T_ANY = 202; - const T_AS = 203; - const T_ASC = 204; - const T_AVG = 205; - const T_BETWEEN = 206; - const T_BOTH = 207; - const T_BY = 208; - const T_CASE = 209; - const T_COALESCE = 210; - const T_COUNT = 211; - const T_DELETE = 212; - const T_DESC = 213; - const T_DISTINCT = 214; - const T_ELSE = 215; - const T_EMPTY = 216; - const T_END = 217; - const T_ESCAPE = 218; - const T_EXISTS = 219; - const T_FALSE = 220; - const T_FROM = 221; - const T_GROUP = 222; - const T_HAVING = 223; - const T_HIDDEN = 224; - const T_IN = 225; - const T_INDEX = 226; - const T_INNER = 227; - const T_INSTANCE = 228; - const T_IS = 229; - const T_JOIN = 230; - const T_LEADING = 231; - const T_LEFT = 232; - const T_LIKE = 233; - const T_MAX = 234; - const T_MEMBER = 235; - const T_MIN = 236; - const T_NEW = 237; - const T_NOT = 238; - const T_NULL = 239; - const T_NULLIF = 240; - const T_OF = 241; - const T_OR = 242; - const T_ORDER = 243; - const T_OUTER = 244; - const T_PARTIAL = 245; - const T_SELECT = 246; - const T_SET = 247; - const T_SOME = 248; - const T_SUM = 249; - const T_THEN = 250; - const T_TRAILING = 251; - const T_TRUE = 252; - const T_UPDATE = 253; - const T_WHEN = 254; - const T_WHERE = 255; - const T_WITH = 256; + public const T_ALL = 200; + public const T_AND = 201; + public const T_ANY = 202; + public const T_AS = 203; + public const T_ASC = 204; + public const T_AVG = 205; + public const T_BETWEEN = 206; + public const T_BOTH = 207; + public const T_BY = 208; + public const T_CASE = 209; + public const T_COALESCE = 210; + public const T_COUNT = 211; + public const T_DELETE = 212; + public const T_DESC = 213; + public const T_DISTINCT = 214; + public const T_ELSE = 215; + public const T_EMPTY = 216; + public const T_END = 217; + public const T_ESCAPE = 218; + public const T_EXISTS = 219; + public const T_FALSE = 220; + public const T_FROM = 221; + public const T_GROUP = 222; + public const T_HAVING = 223; + public const T_HIDDEN = 224; + public const T_IN = 225; + public const T_INDEX = 226; + public const T_INNER = 227; + public const T_INSTANCE = 228; + public const T_IS = 229; + public const T_JOIN = 230; + public const T_LEADING = 231; + public const T_LEFT = 232; + public const T_LIKE = 233; + public const T_MAX = 234; + public const T_MEMBER = 235; + public const T_MIN = 236; + public const T_NEW = 237; + public const T_NOT = 238; + public const T_NULL = 239; + public const T_NULLIF = 240; + public const T_OF = 241; + public const T_OR = 242; + public const T_ORDER = 243; + public const T_OUTER = 244; + public const T_PARTIAL = 245; + public const T_SELECT = 246; + public const T_SET = 247; + public const T_SOME = 248; + public const T_SUM = 249; + public const T_THEN = 250; + public const T_TRAILING = 251; + public const T_TRUE = 252; + public const T_UPDATE = 253; + public const T_WHEN = 254; + public const T_WHERE = 255; + public const T_WITH = 256; /** * Creates a new query scanner object. @@ -136,7 +143,7 @@ protected function getCatchablePatterns() '[a-z_\\\][a-z0-9_]*(?:\\\[a-z_][a-z0-9_]*)*', // identifier or qualified name '(?:[0-9]+(?:[\.][0-9]+)*)(?:e[+-]?[0-9]+)?', // numbers "'(?:[^']|'')*'", // quoted strings - '\?[0-9]*|:[a-z_][a-z0-9_]*' // parameters + '\?[0-9]*|:[a-z_][a-z0-9_]*', // parameters ]; } @@ -157,7 +164,7 @@ protected function getType(&$value) switch (true) { // Recognize numeric values - case (is_numeric($value)): + case is_numeric($value): if (strpos($value, '.') !== false || stripos($value, 'e') !== false) { return self::T_FLOAT; } @@ -165,13 +172,13 @@ protected function getType(&$value) return self::T_INTEGER; // Recognize quoted strings - case ($value[0] === "'"): + case $value[0] === "'": $value = str_replace("''", "'", substr($value, 1, strlen($value) - 2)); return self::T_STRING; // Recognize identifiers, aliased or qualified names - case (ctype_alpha($value[0]) || $value[0] === '_' || $value[0] === '\\'): + case ctype_alpha($value[0]) || $value[0] === '_' || $value[0] === '\\': $name = 'Doctrine\ORM\Query\Lexer::T_' . strtoupper($value); if (defined($name)) { @@ -193,24 +200,51 @@ protected function getType(&$value) return self::T_IDENTIFIER; // Recognize input parameters - case ($value[0] === '?' || $value[0] === ':'): + case $value[0] === '?' || $value[0] === ':': return self::T_INPUT_PARAMETER; // Recognize symbols - case ($value === '.'): return self::T_DOT; - case ($value === ','): return self::T_COMMA; - case ($value === '('): return self::T_OPEN_PARENTHESIS; - case ($value === ')'): return self::T_CLOSE_PARENTHESIS; - case ($value === '='): return self::T_EQUALS; - case ($value === '>'): return self::T_GREATER_THAN; - case ($value === '<'): return self::T_LOWER_THAN; - case ($value === '+'): return self::T_PLUS; - case ($value === '-'): return self::T_MINUS; - case ($value === '*'): return self::T_MULTIPLY; - case ($value === '/'): return self::T_DIVIDE; - case ($value === '!'): return self::T_NEGATE; - case ($value === '{'): return self::T_OPEN_CURLY_BRACE; - case ($value === '}'): return self::T_CLOSE_CURLY_BRACE; + case $value === '.': + return self::T_DOT; + + case $value === ',': + return self::T_COMMA; + + case $value === '(': + return self::T_OPEN_PARENTHESIS; + + case $value === ')': + return self::T_CLOSE_PARENTHESIS; + + case $value === '=': + return self::T_EQUALS; + + case $value === '>': + return self::T_GREATER_THAN; + + case $value === '<': + return self::T_LOWER_THAN; + + case $value === '+': + return self::T_PLUS; + + case $value === '-': + return self::T_MINUS; + + case $value === '*': + return self::T_MULTIPLY; + + case $value === '/': + return self::T_DIVIDE; + + case $value === '!': + return self::T_NEGATE; + + case $value === '{': + return self::T_OPEN_CURLY_BRACE; + + case $value === '}': + return self::T_CLOSE_CURLY_BRACE; // Default default: diff --git a/lib/Doctrine/ORM/Query/Parameter.php b/lib/Doctrine/ORM/Query/Parameter.php index 4ef0f8e4329..6bfa97fa737 100644 --- a/lib/Doctrine/ORM/Query/Parameter.php +++ b/lib/Doctrine/ORM/Query/Parameter.php @@ -1,4 +1,5 @@ */ class Parameter { @@ -71,8 +70,6 @@ public static function normalizeName($name) private $typeSpecified; /** - * Constructor. - * * @param string $name Parameter name * @param mixed $value Parameter value * @param mixed $type Parameter type @@ -127,7 +124,7 @@ public function setValue($value, $type = null) $this->type = $type ?: ParameterTypeInferer::inferType($value); } - public function typeWasSpecified() : bool + public function typeWasSpecified(): bool { return $this->typeSpecified; } diff --git a/lib/Doctrine/ORM/Query/ParameterTypeInferer.php b/lib/Doctrine/ORM/Query/ParameterTypeInferer.php index b8acd9d04f0..08aa358f307 100644 --- a/lib/Doctrine/ORM/Query/ParameterTypeInferer.php +++ b/lib/Doctrine/ORM/Query/ParameterTypeInferer.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class ParameterTypeInferer { @@ -63,7 +66,7 @@ public static function inferType($value) return Type::DATETIME; } - if ($value instanceof \DateInterval) { + if ($value instanceof DateInterval) { return Type::DATEINTERVAL; } @@ -73,6 +76,6 @@ public static function inferType($value) : Connection::PARAM_STR_ARRAY; } - return \PDO::PARAM_STR; + return PDO::PARAM_STR; } } diff --git a/lib/Doctrine/ORM/Query/Parser.php b/lib/Doctrine/ORM/Query/Parser.php index a4428a3e7c8..8ed2af6ebb0 100644 --- a/lib/Doctrine/ORM/Query/Parser.php +++ b/lib/Doctrine/ORM/Query/Parser.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel - * @author Janne Vanhala - * @author Fabio B. Silva */ class Parser { @@ -50,7 +105,6 @@ class Parser * READ-ONLY: Maps BUILT-IN string function names to AST class names. * * @var array - * * @psalm-var array> */ private static $_STRING_FUNCTIONS = [ @@ -66,7 +120,6 @@ class Parser * READ-ONLY: Maps BUILT-IN numeric function names to AST class names. * * @var array - * * @psalm-var array> */ private static $_NUMERIC_FUNCTIONS = [ @@ -92,7 +145,6 @@ class Parser * READ-ONLY: Maps BUILT-IN datetime function names to AST class names. * * @var array - * * @psalm-var array> */ private static $_DATETIME_FUNCTIONS = [ @@ -108,49 +160,39 @@ class Parser * and still need to be validated. */ - /** - * @var array - */ + /** @var array */ private $deferredIdentificationVariables = []; - /** - * @var array - */ + /** @var array */ private $deferredPartialObjectExpressions = []; - /** - * @var array - */ + /** @var array */ private $deferredPathExpressions = []; - /** - * @var array - */ + /** @var array */ private $deferredResultVariables = []; - /** - * @var array - */ + /** @var array */ private $deferredNewObjectExpressions = []; /** * The lexer. * - * @var \Doctrine\ORM\Query\Lexer + * @var Lexer */ private $lexer; /** * The parser result. * - * @var \Doctrine\ORM\Query\ParserResult + * @var ParserResult */ private $parserResult; /** * The EntityManager. * - * @var \Doctrine\ORM\EntityManager + * @var EntityManager */ private $em; @@ -171,7 +213,7 @@ class Parser /** * Keeps the nesting level of defined ResultVariables. * - * @var integer + * @var int */ private $nestingLevel = 0; @@ -189,9 +231,7 @@ class Parser */ private $customOutputWalker; - /** - * @var array - */ + /** @var array */ private $identVariableExpressions = []; /** @@ -235,7 +275,7 @@ public function addCustomTreeWalker($className) /** * Gets the lexer used by the parser. * - * @return \Doctrine\ORM\Query\Lexer + * @return Lexer */ public function getLexer() { @@ -245,7 +285,7 @@ public function getLexer() /** * Gets the ParserResult that is being filled with information during parsing. * - * @return \Doctrine\ORM\Query\ParserResult + * @return ParserResult */ public function getParserResult() { @@ -255,7 +295,7 @@ public function getParserResult() /** * Gets the EntityManager used by the parser. * - * @return \Doctrine\ORM\EntityManager + * @return EntityManager */ public function getEntityManager() { @@ -319,6 +359,7 @@ public function match($token) // Short-circuit on first condition, usually types match if ($lookaheadType === $token) { $this->lexer->moveNext(); + return; } @@ -343,8 +384,8 @@ public function match($token) /** * Frees this parser, enabling it to be reused. * - * @param boolean $deep Whether to clean peek and reset errors. - * @param integer $position Position to reset. + * @param bool $deep Whether to clean peek and reset errors. + * @param int $position Position to reset. * * @return void */ @@ -358,7 +399,7 @@ public function free($deep = false, $position = 0) $this->lexer->resetPeek(); } - $this->lexer->token = null; + $this->lexer->token = null; $this->lexer->lookahead = null; } @@ -388,15 +429,15 @@ public function parse() } switch (true) { - case ($AST instanceof AST\UpdateStatement): + case $AST instanceof AST\UpdateStatement: $treeWalkerChain->walkUpdateStatement($AST); break; - case ($AST instanceof AST\DeleteStatement): + case $AST instanceof AST\DeleteStatement: $treeWalkerChain->walkDeleteStatement($AST); break; - case ($AST instanceof AST\SelectStatement): + case $AST instanceof AST\SelectStatement: default: $treeWalkerChain->walkSelectStatement($AST); } @@ -433,7 +474,7 @@ private function fixIdentificationVariableOrder($AST) assert($AST instanceof AST\SelectStatement); foreach ($this->queryComponents as $dqlAlias => $qComp) { - if ( ! isset($this->identVariableExpressions[$dqlAlias])) { + if (! isset($this->identVariableExpressions[$dqlAlias])) { continue; } @@ -454,7 +495,7 @@ private function fixIdentificationVariableOrder($AST) * * @return void * - * @throws \Doctrine\ORM\Query\QueryException + * @throws QueryException */ public function syntaxError($expected = '', $token = null) { @@ -462,11 +503,11 @@ public function syntaxError($expected = '', $token = null) $token = $this->lexer->lookahead; } - $tokenPos = (isset($token['position'])) ? $token['position'] : '-1'; + $tokenPos = $token['position'] ?? '-1'; $message = "line 0, col {$tokenPos}: Error: "; - $message .= ($expected !== '') ? "Expected {$expected}, got " : 'Unexpected '; - $message .= ($this->lexer->lookahead === null) ? 'end of string.' : "'{$token['value']}'"; + $message .= $expected !== '' ? "Expected {$expected}, got " : 'Unexpected '; + $message .= $this->lexer->lookahead === null ? 'end of string.' : "'{$token['value']}'"; throw QueryException::syntaxError($message, QueryException::dqlError($this->query->getDQL())); } @@ -479,7 +520,7 @@ public function syntaxError($expected = '', $token = null) * * @return void * - * @throws \Doctrine\ORM\Query\QueryException + * @throws QueryException */ public function semanticalError($message = '', $token = null) { @@ -494,10 +535,10 @@ public function semanticalError($message = '', $token = null) $dql = $this->query->getDQL(); $length = strlen($dql); $pos = $token['position'] + $distance; - $pos = strpos($dql, ' ', ($length > $pos) ? $pos : $length); - $length = ($pos !== false) ? $pos - $token['position'] : $distance; + $pos = strpos($dql, ' ', $length > $pos ? $pos : $length); + $length = $pos !== false ? $pos - $token['position'] : $distance; - $tokenPos = (isset($token['position']) && $token['position'] > 0) ? $token['position'] : '-1'; + $tokenPos = isset($token['position']) && $token['position'] > 0 ? $token['position'] : '-1'; $tokenStr = substr($dql, $token['position'], $length); // Building informative message @@ -509,13 +550,13 @@ public function semanticalError($message = '', $token = null) /** * Peeks beyond the matched closing parenthesis and returns the first token after that one. * - * @param boolean $resetPeek Reset peek after finding the closing parenthesis. + * @param bool $resetPeek Reset peek after finding the closing parenthesis. * * @return array */ private function peekBeyondClosingParenthesis($resetPeek = true) { - $token = $this->lexer->peek(); + $token = $this->lexer->peek(); $numUnmatched = 1; while ($numUnmatched > 0 && $token !== null) { @@ -547,7 +588,7 @@ private function peekBeyondClosingParenthesis($resetPeek = true) * * @param array $token * - * @return boolean TRUE if the token is a mathematical operator, FALSE otherwise. + * @return bool TRUE if the token is a mathematical operator, FALSE otherwise. */ private function isMathOperator($token) { @@ -557,7 +598,7 @@ private function isMathOperator($token) /** * Checks if the next-next (after lookahead) token starts a function. * - * @return boolean TRUE if the next-next tokens start a function, FALSE otherwise. + * @return bool TRUE if the next-next tokens start a function, FALSE otherwise. */ private function isFunction() { @@ -574,7 +615,7 @@ private function isFunction() * * @param int $tokenType * - * @return boolean TRUE if the token type is an aggregate function, FALSE otherwise. + * @return bool TRUE if the token type is an aggregate function, FALSE otherwise. */ private function isAggregateFunction($tokenType) { @@ -584,7 +625,7 @@ private function isAggregateFunction($tokenType) /** * Checks whether the current lookahead token of the lexer has the type T_ALL, T_ANY or T_SOME. * - * @return boolean + * @return bool */ private function isNextAllAnySome() { @@ -603,25 +644,28 @@ private function processDeferredIdentificationVariables() $identVariable = $deferredItem['expression']; // Check if IdentificationVariable exists in queryComponents - if ( ! isset($this->queryComponents[$identVariable])) { + if (! isset($this->queryComponents[$identVariable])) { $this->semanticalError( - "'$identVariable' is not defined.", $deferredItem['token'] + "'$identVariable' is not defined.", + $deferredItem['token'] ); } $qComp = $this->queryComponents[$identVariable]; // Check if queryComponent points to an AbstractSchemaName or a ResultVariable - if ( ! isset($qComp['metadata'])) { + if (! isset($qComp['metadata'])) { $this->semanticalError( - "'$identVariable' does not point to a Class.", $deferredItem['token'] + "'$identVariable' does not point to a Class.", + $deferredItem['token'] ); } // Validate if identification variable nesting level is lower or equal than the current one if ($qComp['nestingLevel'] > $deferredItem['nestingLevel']) { $this->semanticalError( - "'$identVariable' is used outside the scope of its declaration.", $deferredItem['token'] + "'$identVariable' is used outside the scope of its declaration.", + $deferredItem['token'] ); } } @@ -637,32 +681,30 @@ private function processDeferredIdentificationVariables() private function processDeferredNewObjectExpressions($AST) { foreach ($this->deferredNewObjectExpressions as $deferredItem) { - $expression = $deferredItem['expression']; - $token = $deferredItem['token']; - $className = $expression->className; - $args = $expression->args; - $fromClassName = isset($AST->fromClause->identificationVariableDeclarations[0]->rangeVariableDeclaration->abstractSchemaName) - ? $AST->fromClause->identificationVariableDeclarations[0]->rangeVariableDeclaration->abstractSchemaName - : null; + $expression = $deferredItem['expression']; + $token = $deferredItem['token']; + $className = $expression->className; + $args = $expression->args; + $fromClassName = $AST->fromClause->identificationVariableDeclarations[0]->rangeVariableDeclaration->abstractSchemaName ?? null; // If the namespace is not given then assumes the first FROM entity namespace if (strpos($className, '\\') === false && ! class_exists($className) && strpos($fromClassName, '\\') !== false) { - $namespace = substr($fromClassName, 0, strrpos($fromClassName, '\\')); - $fqcn = $namespace . '\\' . $className; + $namespace = substr($fromClassName, 0, strrpos($fromClassName, '\\')); + $fqcn = $namespace . '\\' . $className; if (class_exists($fqcn)) { - $expression->className = $fqcn; - $className = $fqcn; + $expression->className = $fqcn; + $className = $fqcn; } } - if ( ! class_exists($className)) { + if (! class_exists($className)) { $this->semanticalError(sprintf('Class "%s" is not defined.', $className), $token); } - $class = new \ReflectionClass($className); + $class = new ReflectionClass($className); - if ( ! $class->isInstantiable()) { + if (! $class->isInstantiable()) { $this->semanticalError(sprintf('Class "%s" can not be instantiated.', $className), $token); } @@ -685,7 +727,7 @@ private function processDeferredNewObjectExpressions($AST) private function processDeferredPartialObjectExpressions() { foreach ($this->deferredPartialObjectExpressions as $deferredItem) { - $expr = $deferredItem['expression']; + $expr = $deferredItem['expression']; $class = $this->queryComponents[$expr->identificationVariable]['metadata']; foreach ($expr->partialFieldSet as $field) { @@ -693,20 +735,23 @@ private function processDeferredPartialObjectExpressions() continue; } - if (isset($class->associationMappings[$field]) && + if ( + isset($class->associationMappings[$field]) && $class->associationMappings[$field]['isOwningSide'] && - $class->associationMappings[$field]['type'] & ClassMetadata::TO_ONE) { + $class->associationMappings[$field]['type'] & ClassMetadata::TO_ONE + ) { 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->name . '.', + $deferredItem['token'] ); } - if (array_intersect($class->identifier, $expr->partialFieldSet) != $class->identifier) { + 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->name . ' must contain the identifier.', $deferredItem['token'] ); } @@ -725,25 +770,28 @@ private function processDeferredResultVariables() $resultVariable = $deferredItem['expression']; // Check if ResultVariable exists in queryComponents - if ( ! isset($this->queryComponents[$resultVariable])) { + if (! isset($this->queryComponents[$resultVariable])) { $this->semanticalError( - "'$resultVariable' is not defined.", $deferredItem['token'] + "'$resultVariable' is not defined.", + $deferredItem['token'] ); } $qComp = $this->queryComponents[$resultVariable]; // Check if queryComponent points to an AbstractSchemaName or a ResultVariable - if ( ! isset($qComp['resultVariable'])) { + if (! isset($qComp['resultVariable'])) { $this->semanticalError( - "'$resultVariable' does not point to a ResultVariable.", $deferredItem['token'] + "'$resultVariable' does not point to a ResultVariable.", + $deferredItem['token'] ); } // Validate if identification variable nesting level is lower or equal than the current one if ($qComp['nestingLevel'] > $deferredItem['nestingLevel']) { $this->semanticalError( - "'$resultVariable' is used outside the scope of its declaration.", $deferredItem['token'] + "'$resultVariable' is used outside the scope of its declaration.", + $deferredItem['token'] ); } } @@ -773,7 +821,7 @@ private function processDeferredPathExpressions() } // Check if field or association exists - if ( ! isset($class->associationMappings[$field]) && ! isset($class->fieldMappings[$field])) { + if (! isset($class->associationMappings[$field]) && ! isset($class->fieldMappings[$field])) { $this->semanticalError( 'Class ' . $class->name . ' has no field or association named ' . $field, $deferredItem['token'] @@ -785,7 +833,7 @@ private function processDeferredPathExpressions() if (isset($class->associationMappings[$field])) { $assoc = $class->associationMappings[$field]; - $fieldType = ($assoc['type'] & ClassMetadata::TO_ONE) + $fieldType = $assoc['type'] & ClassMetadata::TO_ONE ? AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION : AST\PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION; } @@ -793,7 +841,7 @@ private function processDeferredPathExpressions() // Validate if PathExpression is one of the expected types $expectedType = $pathExpression->expectedType; - if ( ! ($expectedType & $fieldType)) { + if (! ($expectedType & $fieldType)) { // We need to recognize which was expected type(s) $expectedStringTypes = []; @@ -814,7 +862,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.'; @@ -831,7 +879,7 @@ private function processDeferredPathExpressions() */ private function processRootEntityAliasSelected() { - if ( ! count($this->identVariableExpressions)) { + if (! count($this->identVariableExpressions)) { return; } @@ -956,7 +1004,7 @@ public function AliasIdentificationVariable() $this->match(Lexer::T_IDENTIFIER); $aliasIdentVariable = $this->lexer->token['value']; - $exists = isset($this->queryComponents[$aliasIdentVariable]); + $exists = isset($this->queryComponents[$aliasIdentVariable]); if ($exists) { $this->semanticalError("'$aliasIdentVariable' is already defined.", $this->lexer->token); @@ -1015,7 +1063,7 @@ public function AliasResultVariable() $this->match(Lexer::T_IDENTIFIER); $resultVariable = $this->lexer->token['value']; - $exists = isset($this->queryComponents[$resultVariable]); + $exists = isset($this->queryComponents[$resultVariable]); if ($exists) { $this->semanticalError("'$resultVariable' is already defined.", $this->lexer->token); @@ -1048,15 +1096,15 @@ public function ResultVariable() /** * JoinAssociationPathExpression ::= IdentificationVariable "." (CollectionValuedAssociationField | SingleValuedAssociationField) * - * @return \Doctrine\ORM\Query\AST\JoinAssociationPathExpression + * @return JoinAssociationPathExpression */ public function JoinAssociationPathExpression() { $identVariable = $this->IdentificationVariable(); - if ( ! isset($this->queryComponents[$identVariable])) { + if (! isset($this->queryComponents[$identVariable])) { $this->semanticalError( - 'Identification Variable ' . $identVariable .' used in join path expression but was not defined before.' + 'Identification Variable ' . $identVariable . ' used in join path expression but was not defined before.' ); } @@ -1069,7 +1117,7 @@ public function JoinAssociationPathExpression() $qComp = $this->queryComponents[$identVariable]; $class = $qComp['metadata']; - if ( ! $class->hasAssociation($field)) { + if (! $class->hasAssociation($field)) { $this->semanticalError('Class ' . $class->name . ' has no association named ' . $field); } @@ -1082,14 +1130,14 @@ public function JoinAssociationPathExpression() * * PathExpression ::= IdentificationVariable {"." identifier}* * - * @param integer $expectedTypes + * @param int $expectedTypes * * @return PathExpression */ public function PathExpression($expectedTypes) { $identVariable = $this->IdentificationVariable(); - $field = null; + $field = null; if ($this->lexer->isNextToken(Lexer::T_DOT)) { $this->match(Lexer::T_DOT); @@ -1100,7 +1148,7 @@ public function PathExpression($expectedTypes) while ($this->lexer->isNextToken(Lexer::T_DOT)) { $this->match(Lexer::T_DOT); $this->match(Lexer::T_IDENTIFIER); - $field .= '.'.$this->lexer->token['value']; + $field .= '.' . $this->lexer->token['value']; } } @@ -1176,7 +1224,7 @@ public function CollectionValuedPathExpression() /** * SelectClause ::= "SELECT" ["DISTINCT"] SelectExpression {"," SelectExpression} * - * @return \Doctrine\ORM\Query\AST\SelectClause + * @return SelectClause */ public function SelectClause() { @@ -1191,7 +1239,7 @@ public function SelectClause() } // Process SelectExpressions (1..N) - $selectExpressions = []; + $selectExpressions = []; $selectExpressions[] = $this->SelectExpression(); while ($this->lexer->isNextToken(Lexer::T_COMMA)) { @@ -1206,7 +1254,7 @@ public function SelectClause() /** * SimpleSelectClause ::= "SELECT" ["DISTINCT"] SimpleSelectExpression * - * @return \Doctrine\ORM\Query\AST\SimpleSelectClause + * @return SimpleSelectClause */ public function SimpleSelectClause() { @@ -1225,13 +1273,13 @@ public function SimpleSelectClause() /** * UpdateClause ::= "UPDATE" AbstractSchemaName ["AS"] AliasIdentificationVariable "SET" UpdateItem {"," UpdateItem}* * - * @return \Doctrine\ORM\Query\AST\UpdateClause + * @return UpdateClause */ public function UpdateClause() { $this->match(Lexer::T_UPDATE); - $token = $this->lexer->lookahead; + $token = $this->lexer->lookahead; $abstractSchemaName = $this->AbstractSchemaName(); $this->validateAbstractSchemaName($abstractSchemaName); @@ -1258,7 +1306,7 @@ public function UpdateClause() $this->match(Lexer::T_SET); - $updateItems = []; + $updateItems = []; $updateItems[] = $this->UpdateItem(); while ($this->lexer->isNextToken(Lexer::T_COMMA)) { @@ -1267,7 +1315,7 @@ public function UpdateClause() $updateItems[] = $this->UpdateItem(); } - $updateClause = new AST\UpdateClause($abstractSchemaName, $updateItems); + $updateClause = new AST\UpdateClause($abstractSchemaName, $updateItems); $updateClause->aliasIdentificationVariable = $aliasIdentificationVariable; return $updateClause; @@ -1276,7 +1324,7 @@ public function UpdateClause() /** * DeleteClause ::= "DELETE" ["FROM"] AbstractSchemaName ["AS"] AliasIdentificationVariable * - * @return \Doctrine\ORM\Query\AST\DeleteClause + * @return DeleteClause */ public function DeleteClause() { @@ -1286,7 +1334,7 @@ public function DeleteClause() $this->match(Lexer::T_FROM); } - $token = $this->lexer->lookahead; + $token = $this->lexer->lookahead; $abstractSchemaName = $this->AbstractSchemaName(); $this->validateAbstractSchemaName($abstractSchemaName); @@ -1302,7 +1350,7 @@ public function DeleteClause() : 'alias_should_have_been_set'; $deleteClause->aliasIdentificationVariable = $aliasIdentificationVariable; - $class = $this->em->getClassMetadata($deleteClause->abstractSchemaName); + $class = $this->em->getClassMetadata($deleteClause->abstractSchemaName); // Building queryComponent $queryComponent = [ @@ -1322,13 +1370,13 @@ public function DeleteClause() /** * FromClause ::= "FROM" IdentificationVariableDeclaration {"," IdentificationVariableDeclaration}* * - * @return \Doctrine\ORM\Query\AST\FromClause + * @return FromClause */ public function FromClause() { $this->match(Lexer::T_FROM); - $identificationVariableDeclarations = []; + $identificationVariableDeclarations = []; $identificationVariableDeclarations[] = $this->IdentificationVariableDeclaration(); while ($this->lexer->isNextToken(Lexer::T_COMMA)) { @@ -1343,13 +1391,13 @@ public function FromClause() /** * SubselectFromClause ::= "FROM" SubselectIdentificationVariableDeclaration {"," SubselectIdentificationVariableDeclaration}* * - * @return \Doctrine\ORM\Query\AST\SubselectFromClause + * @return SubselectFromClause */ public function SubselectFromClause() { $this->match(Lexer::T_FROM); - $identificationVariables = []; + $identificationVariables = []; $identificationVariables[] = $this->SubselectIdentificationVariableDeclaration(); while ($this->lexer->isNextToken(Lexer::T_COMMA)) { @@ -1364,7 +1412,7 @@ public function SubselectFromClause() /** * WhereClause ::= "WHERE" ConditionalExpression * - * @return \Doctrine\ORM\Query\AST\WhereClause + * @return WhereClause */ public function WhereClause() { @@ -1376,7 +1424,7 @@ public function WhereClause() /** * HavingClause ::= "HAVING" ConditionalExpression * - * @return \Doctrine\ORM\Query\AST\HavingClause + * @return HavingClause */ public function HavingClause() { @@ -1388,7 +1436,7 @@ public function HavingClause() /** * GroupByClause ::= "GROUP" "BY" GroupByItem {"," GroupByItem}* * - * @return \Doctrine\ORM\Query\AST\GroupByClause + * @return GroupByClause */ public function GroupByClause() { @@ -1409,14 +1457,14 @@ public function GroupByClause() /** * OrderByClause ::= "ORDER" "BY" OrderByItem {"," OrderByItem}* * - * @return \Doctrine\ORM\Query\AST\OrderByClause + * @return OrderByClause */ public function OrderByClause() { $this->match(Lexer::T_ORDER); $this->match(Lexer::T_BY); - $orderByItems = []; + $orderByItems = []; $orderByItems[] = $this->OrderByItem(); while ($this->lexer->isNextToken(Lexer::T_COMMA)) { @@ -1454,7 +1502,7 @@ public function Subselect() /** * UpdateItem ::= SingleValuedPathExpression "=" NewValue * - * @return \Doctrine\ORM\Query\AST\UpdateItem + * @return UpdateItem */ public function UpdateItem() { @@ -1462,9 +1510,7 @@ public function UpdateItem() $this->match(Lexer::T_EQUALS); - $updateItem = new AST\UpdateItem($pathExpr, $this->NewValue()); - - return $updateItem; + return new AST\UpdateItem($pathExpr, $this->NewValue()); } /** @@ -1484,11 +1530,11 @@ public function GroupByItem() // Still need to decide between IdentificationVariable or ResultVariable $lookaheadValue = $this->lexer->lookahead['value']; - if ( ! isset($this->queryComponents[$lookaheadValue])) { + if (! isset($this->queryComponents[$lookaheadValue])) { $this->semanticalError('Cannot group by undefined identification or result variable.'); } - return (isset($this->queryComponents[$lookaheadValue]['metadata'])) + return isset($this->queryComponents[$lookaheadValue]['metadata']) ? $this->IdentificationVariable() : $this->ResultVariable(); } @@ -1499,7 +1545,7 @@ public function GroupByItem() * ScalarExpression | ResultVariable | FunctionDeclaration * ) ["ASC" | "DESC"] * - * @return \Doctrine\ORM\Query\AST\OrderByItem + * @return OrderByItem */ public function OrderByItem() { @@ -1513,7 +1559,7 @@ public function OrderByItem() $glimpse = $this->lexer->glimpse(); switch (true) { - case ($this->isMathOperator($peek)): + case $this->isMathOperator($peek): $expr = $this->SimpleArithmeticExpression(); break; @@ -1521,7 +1567,7 @@ public function OrderByItem() $expr = $this->SingleValuedPathExpression(); break; - case ($this->lexer->peek() && $this->isMathOperator($this->peekBeyondClosingParenthesis())): + case $this->lexer->peek() && $this->isMathOperator($this->peekBeyondClosingParenthesis()): $expr = $this->ScalarExpression(); break; @@ -1542,12 +1588,12 @@ public function OrderByItem() $item = new AST\OrderByItem($expr); switch (true) { - case ($this->lexer->isNextToken(Lexer::T_DESC)): + case $this->lexer->isNextToken(Lexer::T_DESC): $this->match(Lexer::T_DESC); $type = 'DESC'; break; - case ($this->lexer->isNextToken(Lexer::T_ASC)): + case $this->lexer->isNextToken(Lexer::T_ASC): $this->match(Lexer::T_ASC); break; @@ -1614,7 +1660,9 @@ public function IdentificationVariableDeclaration() } return new AST\IdentificationVariableDeclaration( - $rangeVariableDeclaration, $indexBy, $joins + $rangeVariableDeclaration, + $indexBy, + $joins ); } @@ -1681,7 +1729,7 @@ public function SubselectIdentificationVariableDeclaration() * (JoinAssociationDeclaration | RangeVariableDeclaration) * ["WITH" ConditionalExpression] * - * @return \Doctrine\ORM\Query\AST\Join + * @return Join */ public function Join() { @@ -1689,7 +1737,7 @@ public function Join() $joinType = AST\Join::JOIN_TYPE_INNER; switch (true) { - case ($this->lexer->isNextToken(Lexer::T_LEFT)): + case $this->lexer->isNextToken(Lexer::T_LEFT): $this->match(Lexer::T_LEFT); $joinType = AST\Join::JOIN_TYPE_LEFT; @@ -1700,9 +1748,10 @@ public function Join() $joinType = AST\Join::JOIN_TYPE_LEFTOUTER; } + break; - case ($this->lexer->isNextToken(Lexer::T_INNER)): + case $this->lexer->isNextToken(Lexer::T_INNER): $this->match(Lexer::T_INNER); break; @@ -1713,7 +1762,7 @@ public function Join() $this->match(Lexer::T_JOIN); $next = $this->lexer->glimpse(); - $joinDeclaration = ($next['type'] === Lexer::T_DOT) ? $this->JoinAssociationDeclaration() : $this->RangeVariableDeclaration(); + $joinDeclaration = $next['type'] === Lexer::T_DOT ? $this->JoinAssociationDeclaration() : $this->RangeVariableDeclaration(); $adhocConditions = $this->lexer->isNextToken(Lexer::T_WITH); $join = new AST\Join($joinType, $joinDeclaration); @@ -1735,7 +1784,7 @@ public function Join() /** * RangeVariableDeclaration ::= AbstractSchemaName ["AS"] AliasIdentificationVariable * - * @return \Doctrine\ORM\Query\AST\RangeVariableDeclaration + * @return RangeVariableDeclaration * * @throws QueryException */ @@ -1753,9 +1802,9 @@ public function RangeVariableDeclaration() $this->match(Lexer::T_AS); } - $token = $this->lexer->lookahead; + $token = $this->lexer->lookahead; $aliasIdentificationVariable = $this->AliasIdentificationVariable(); - $classMetadata = $this->em->getClassMetadata($abstractSchemaName); + $classMetadata = $this->em->getClassMetadata($abstractSchemaName); // Building queryComponent $queryComponent = [ @@ -1764,7 +1813,7 @@ public function RangeVariableDeclaration() 'relation' => null, 'map' => null, 'nestingLevel' => $this->nestingLevel, - 'token' => $token + 'token' => $token, ]; $this->queryComponents[$aliasIdentificationVariable] = $queryComponent; @@ -1801,7 +1850,7 @@ public function JoinAssociationDeclaration() 'relation' => $class->getAssociationMapping($field), 'map' => null, 'nestingLevel' => $this->nestingLevel, - 'token' => $this->lexer->lookahead + 'token' => $this->lexer->lookahead, ]; $this->queryComponents[$aliasIdentificationVariable] = $joinQueryComponent; @@ -1813,7 +1862,7 @@ public function JoinAssociationDeclaration() * PartialObjectExpression ::= "PARTIAL" IdentificationVariable "." PartialFieldSet * PartialFieldSet ::= "{" SimpleStateField {"," SimpleStateField}* "}" * - * @return \Doctrine\ORM\Query\AST\PartialObjectExpression + * @return PartialObjectExpression */ public function PartialObjectExpression() { @@ -1833,7 +1882,7 @@ public function PartialObjectExpression() while ($this->lexer->isNextToken(Lexer::T_DOT)) { $this->match(Lexer::T_DOT); $this->match(Lexer::T_IDENTIFIER); - $field .= '.'.$this->lexer->token['value']; + $field .= '.' . $this->lexer->token['value']; } $partialFieldSet[] = $field; @@ -1847,7 +1896,7 @@ public function PartialObjectExpression() while ($this->lexer->isNextToken(Lexer::T_DOT)) { $this->match(Lexer::T_DOT); $this->match(Lexer::T_IDENTIFIER); - $field .= '.'.$this->lexer->token['value']; + $field .= '.' . $this->lexer->token['value']; } $partialFieldSet[] = $field; @@ -1870,14 +1919,14 @@ public function PartialObjectExpression() /** * NewObjectExpression ::= "NEW" AbstractSchemaName "(" NewObjectArg {"," NewObjectArg}* ")" * - * @return \Doctrine\ORM\Query\AST\NewObjectExpression + * @return NewObjectExpression */ public function NewObjectExpression() { $this->match(Lexer::T_NEW); $className = $this->AbstractSchemaName(); // note that this is not yet validated - $token = $this->lexer->token; + $token = $this->lexer->token; $this->match(Lexer::T_OPEN_PARENTHESIS); @@ -1927,7 +1976,7 @@ public function NewObjectArg() /** * IndexBy ::= "INDEX" "BY" StateFieldPathExpression * - * @return \Doctrine\ORM\Query\AST\IndexBy + * @return IndexBy */ public function IndexBy() { @@ -1954,47 +2003,47 @@ public function ScalarExpression() $peek = $this->lexer->glimpse(); switch (true) { - case ($lookahead === Lexer::T_INTEGER): - case ($lookahead === Lexer::T_FLOAT): + case $lookahead === Lexer::T_INTEGER: + case $lookahead === Lexer::T_FLOAT: // SimpleArithmeticExpression : (- u.value ) or ( + u.value ) or ( - 1 ) or ( + 1 ) - case ($lookahead === Lexer::T_MINUS): - case ($lookahead === Lexer::T_PLUS): + case $lookahead === Lexer::T_MINUS: + case $lookahead === Lexer::T_PLUS: return $this->SimpleArithmeticExpression(); - case ($lookahead === Lexer::T_STRING): + case $lookahead === Lexer::T_STRING: return $this->StringPrimary(); - case ($lookahead === Lexer::T_TRUE): - case ($lookahead === Lexer::T_FALSE): + case $lookahead === Lexer::T_TRUE: + case $lookahead === Lexer::T_FALSE: $this->match($lookahead); return new AST\Literal(AST\Literal::BOOLEAN, $this->lexer->token['value']); - case ($lookahead === Lexer::T_INPUT_PARAMETER): + case $lookahead === Lexer::T_INPUT_PARAMETER: switch (true) { case $this->isMathOperator($peek): // :param + u.value return $this->SimpleArithmeticExpression(); + default: return $this->InputParameter(); } - - case ($lookahead === Lexer::T_CASE): - case ($lookahead === Lexer::T_COALESCE): - case ($lookahead === Lexer::T_NULLIF): + case $lookahead === Lexer::T_CASE: + case $lookahead === Lexer::T_COALESCE: + case $lookahead === Lexer::T_NULLIF: // Since NULLIF and COALESCE can be identified as a function, // we need to check these before checking for FunctionDeclaration return $this->CaseExpression(); - case ($lookahead === Lexer::T_OPEN_PARENTHESIS): + case $lookahead === Lexer::T_OPEN_PARENTHESIS: return $this->SimpleArithmeticExpression(); // this check must be done before checking for a filed path expression - case ($this->isFunction()): + case $this->isFunction(): $this->lexer->peek(); // "(" switch (true) { - case ($this->isMathOperator($this->peekBeyondClosingParenthesis())): + case $this->isMathOperator($this->peekBeyondClosingParenthesis()): // SUM(u.id) + COUNT(u.id) return $this->SimpleArithmeticExpression(); @@ -2005,7 +2054,7 @@ public function ScalarExpression() break; // it is no function, so it must be a field path - case ($lookahead === Lexer::T_IDENTIFIER): + case $lookahead === Lexer::T_IDENTIFIER: $this->lexer->peek(); // lookahead => '.' $this->lexer->peek(); // lookahead => token after '.' $peek = $this->lexer->peek(); // lookahead => token after the token after the '.' @@ -2066,7 +2115,7 @@ public function CaseExpression() /** * CoalesceExpression ::= "COALESCE" "(" ScalarExpression {"," ScalarExpression}* ")" * - * @return \Doctrine\ORM\Query\AST\CoalesceExpression + * @return CoalesceExpression */ public function CoalesceExpression() { @@ -2074,7 +2123,7 @@ public function CoalesceExpression() $this->match(Lexer::T_OPEN_PARENTHESIS); // Process ScalarExpressions (1..N) - $scalarExpressions = []; + $scalarExpressions = []; $scalarExpressions[] = $this->ScalarExpression(); while ($this->lexer->isNextToken(Lexer::T_COMMA)) { @@ -2091,7 +2140,7 @@ public function CoalesceExpression() /** * NullIfExpression ::= "NULLIF" "(" ScalarExpression "," ScalarExpression ")" * - * @return \Doctrine\ORM\Query\AST\NullIfExpression + * @return NullIfExpression */ public function NullIfExpression() { @@ -2110,7 +2159,7 @@ public function NullIfExpression() /** * GeneralCaseExpression ::= "CASE" WhenClause {WhenClause}* "ELSE" ScalarExpression "END" * - * @return \Doctrine\ORM\Query\AST\GeneralCaseExpression + * @return GeneralCaseExpression */ public function GeneralCaseExpression() { @@ -2158,7 +2207,7 @@ public function SimpleCaseExpression() /** * WhenClause ::= "WHEN" ConditionalExpression "THEN" ScalarExpression * - * @return \Doctrine\ORM\Query\AST\WhenClause + * @return WhenClause */ public function WhenClause() { @@ -2172,7 +2221,7 @@ public function WhenClause() /** * SimpleWhenClause ::= "WHEN" ScalarExpression "THEN" ScalarExpression * - * @return \Doctrine\ORM\Query\AST\SimpleWhenClause + * @return SimpleWhenClause */ public function SimpleWhenClause() { @@ -2189,7 +2238,7 @@ public function SimpleWhenClause() * PartialObjectExpression | "(" Subselect ")" | CaseExpression | NewObjectExpression * ) [["AS"] ["HIDDEN"] AliasResultVariable] * - * @return \Doctrine\ORM\Query\AST\SelectExpression + * @return SelectExpression */ public function SelectExpression() { @@ -2200,28 +2249,28 @@ public function SelectExpression() switch (true) { // ScalarExpression (u.name) - case ($lookaheadType === Lexer::T_IDENTIFIER && $peek['type'] === Lexer::T_DOT): + case $lookaheadType === Lexer::T_IDENTIFIER && $peek['type'] === Lexer::T_DOT: $expression = $this->ScalarExpression(); break; // IdentificationVariable (u) - case ($lookaheadType === Lexer::T_IDENTIFIER && $peek['type'] !== Lexer::T_OPEN_PARENTHESIS): + case $lookaheadType === Lexer::T_IDENTIFIER && $peek['type'] !== Lexer::T_OPEN_PARENTHESIS: $expression = $identVariable = $this->IdentificationVariable(); break; // CaseExpression (CASE ... or NULLIF(...) or COALESCE(...)) - case ($lookaheadType === Lexer::T_CASE): - case ($lookaheadType === Lexer::T_COALESCE): - case ($lookaheadType === Lexer::T_NULLIF): + case $lookaheadType === Lexer::T_CASE: + case $lookaheadType === Lexer::T_COALESCE: + case $lookaheadType === Lexer::T_NULLIF: $expression = $this->CaseExpression(); break; // DQL Function (SUM(u.value) or SUM(u.value) + 1) - case ($this->isFunction()): + case $this->isFunction(): $this->lexer->peek(); // "(" switch (true) { - case ($this->isMathOperator($this->peekBeyondClosingParenthesis())): + case $this->isMathOperator($this->peekBeyondClosingParenthesis()): // SUM(u.id) + COUNT(u.id) $expression = $this->ScalarExpression(); break; @@ -2235,31 +2284,31 @@ public function SelectExpression() break; // PartialObjectExpression (PARTIAL u.{id, name}) - case ($lookaheadType === Lexer::T_PARTIAL): + case $lookaheadType === Lexer::T_PARTIAL: $expression = $this->PartialObjectExpression(); $identVariable = $expression->identificationVariable; break; // Subselect - case ($lookaheadType === Lexer::T_OPEN_PARENTHESIS && $peek['type'] === Lexer::T_SELECT): + case $lookaheadType === Lexer::T_OPEN_PARENTHESIS && $peek['type'] === Lexer::T_SELECT: $this->match(Lexer::T_OPEN_PARENTHESIS); $expression = $this->Subselect(); $this->match(Lexer::T_CLOSE_PARENTHESIS); break; // Shortcut: ScalarExpression => SimpleArithmeticExpression - case ($lookaheadType === Lexer::T_OPEN_PARENTHESIS): - case ($lookaheadType === Lexer::T_INTEGER): - case ($lookaheadType === Lexer::T_STRING): - case ($lookaheadType === Lexer::T_FLOAT): + case $lookaheadType === Lexer::T_OPEN_PARENTHESIS: + case $lookaheadType === Lexer::T_INTEGER: + case $lookaheadType === Lexer::T_STRING: + case $lookaheadType === Lexer::T_FLOAT: // SimpleArithmeticExpression : (- u.value ) or ( + u.value ) - case ($lookaheadType === Lexer::T_MINUS): - case ($lookaheadType === Lexer::T_PLUS): + case $lookaheadType === Lexer::T_MINUS: + case $lookaheadType === Lexer::T_PLUS: $expression = $this->SimpleArithmeticExpression(); break; // NewObjectExpression (New ClassName(id, name)) - case ($lookaheadType === Lexer::T_NEW): + case $lookaheadType === Lexer::T_NEW: $expression = $this->NewObjectExpression(); break; @@ -2290,7 +2339,7 @@ public function SelectExpression() $aliasResultVariable = null; if ($mustHaveAliasResultVariable || $this->lexer->isNextToken(Lexer::T_IDENTIFIER)) { - $token = $this->lexer->lookahead; + $token = $this->lexer->lookahead; $aliasResultVariable = $this->AliasResultVariable(); // Include AliasResultVariable in query components. @@ -2318,7 +2367,7 @@ public function SelectExpression() * AggregateExpression | "(" Subselect ")" | ScalarExpression * ) [["AS"] AliasResultVariable] * - * @return \Doctrine\ORM\Query\AST\SimpleSelectExpression + * @return SimpleSelectExpression */ public function SimpleSelectExpression() { @@ -2327,31 +2376,34 @@ public function SimpleSelectExpression() switch ($this->lexer->lookahead['type']) { case Lexer::T_IDENTIFIER: switch (true) { - case ($peek['type'] === Lexer::T_DOT): + case $peek['type'] === Lexer::T_DOT: $expression = $this->StateFieldPathExpression(); return new AST\SimpleSelectExpression($expression); - case ($peek['type'] !== Lexer::T_OPEN_PARENTHESIS): + case $peek['type'] !== Lexer::T_OPEN_PARENTHESIS: $expression = $this->IdentificationVariable(); return new AST\SimpleSelectExpression($expression); - case ($this->isFunction()): + case $this->isFunction(): // SUM(u.id) + COUNT(u.id) if ($this->isMathOperator($this->peekBeyondClosingParenthesis())) { return new AST\SimpleSelectExpression($this->ScalarExpression()); } + // COUNT(u.id) if ($this->isAggregateFunction($this->lexer->lookahead['type'])) { return new AST\SimpleSelectExpression($this->AggregateExpression()); } + // IDENTITY(u) return new AST\SimpleSelectExpression($this->FunctionDeclaration()); default: // Do nothing } + break; case Lexer::T_OPEN_PARENTHESIS: @@ -2383,8 +2435,8 @@ public function SimpleSelectExpression() } if ($this->lexer->isNextToken(Lexer::T_IDENTIFIER)) { - $token = $this->lexer->lookahead; - $resultVariable = $this->AliasResultVariable(); + $token = $this->lexer->lookahead; + $resultVariable = $this->AliasResultVariable(); $expr->fieldIdentificationVariable = $resultVariable; // Include AliasResultVariable in query components. @@ -2405,7 +2457,7 @@ public function SimpleSelectExpression() */ public function ConditionalExpression() { - $conditionalTerms = []; + $conditionalTerms = []; $conditionalTerms[] = $this->ConditionalTerm(); while ($this->lexer->isNextToken(Lexer::T_OR)) { @@ -2416,7 +2468,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]; } @@ -2430,7 +2482,7 @@ public function ConditionalExpression() */ public function ConditionalTerm() { - $conditionalFactors = []; + $conditionalFactors = []; $conditionalFactors[] = $this->ConditionalFactor(); while ($this->lexer->isNextToken(Lexer::T_AND)) { @@ -2441,7 +2493,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]; } @@ -2467,11 +2519,11 @@ public function ConditionalFactor() // Phase 1 AST optimization: Prevent AST\ConditionalFactor // if only one AST\ConditionalPrimary is defined - if ( ! $not) { + if (! $not) { return $conditionalPrimary; } - $conditionalFactor = new AST\ConditionalFactor($conditionalPrimary); + $conditionalFactor = new AST\ConditionalFactor($conditionalPrimary); $conditionalFactor->not = $not; return $conditionalFactor; @@ -2480,13 +2532,13 @@ public function ConditionalFactor() /** * ConditionalPrimary ::= SimpleConditionalExpression | "(" ConditionalExpression ")" * - * @return \Doctrine\ORM\Query\AST\ConditionalPrimary + * @return ConditionalPrimary */ public function ConditionalPrimary() { - $condPrimary = new AST\ConditionalPrimary; + $condPrimary = new AST\ConditionalPrimary(); - if ( ! $this->lexer->isNextToken(Lexer::T_OPEN_PARENTHESIS)) { + if (! $this->lexer->isNextToken(Lexer::T_OPEN_PARENTHESIS)) { $condPrimary->simpleConditionalExpression = $this->SimpleConditionalExpression(); return $condPrimary; @@ -2495,11 +2547,13 @@ public function ConditionalPrimary() // Peek beyond the matching closing parenthesis ')' $peek = $this->peekBeyondClosingParenthesis(); - if ($peek !== null && ( + if ( + $peek !== null && ( in_array($peek['value'], ['=', '<', '<=', '<>', '>', '>=', '!=']) || in_array($peek['type'], [Lexer::T_NOT, Lexer::T_BETWEEN, Lexer::T_LIKE, Lexer::T_IN, Lexer::T_IS, Lexer::T_EXISTS]) || $this->isMathOperator($peek) - )) { + ) + ) { $condPrimary->simpleConditionalExpression = $this->SimpleConditionalExpression(); return $condPrimary; @@ -2525,9 +2579,9 @@ public function SimpleConditionalExpression() return $this->ExistsExpression(); } - $token = $this->lexer->lookahead; - $peek = $this->lexer->glimpse(); - $lookahead = $token; + $token = $this->lexer->lookahead; + $peek = $this->lexer->glimpse(); + $lookahead = $token; if ($this->lexer->isNextToken(Lexer::T_NOT)) { $token = $this->lexer->glimpse(); @@ -2549,6 +2603,7 @@ public function SimpleConditionalExpression() if ($token['type'] === Lexer::T_IS) { $lookahead = $this->lexer->peek(); } + break; default: @@ -2602,7 +2657,7 @@ public function SimpleConditionalExpression() return $this->NullComparisonExpression(); } - if ($token['type'] === Lexer::T_IS && $lookahead['type'] === Lexer::T_EMPTY) { + if ($token['type'] === Lexer::T_IS && $lookahead['type'] === Lexer::T_EMPTY) { return $this->EmptyCollectionComparisonExpression(); } @@ -2612,7 +2667,7 @@ public function SimpleConditionalExpression() /** * EmptyCollectionComparisonExpression ::= CollectionValuedPathExpression "IS" ["NOT"] "EMPTY" * - * @return \Doctrine\ORM\Query\AST\EmptyCollectionComparisonExpression + * @return EmptyCollectionComparisonExpression */ public function EmptyCollectionComparisonExpression() { @@ -2637,7 +2692,7 @@ public function EmptyCollectionComparisonExpression() * EntityExpression ::= SingleValuedAssociationPathExpression | SimpleEntityExpression * SimpleEntityExpression ::= IdentificationVariable | InputParameter * - * @return \Doctrine\ORM\Query\AST\CollectionMemberExpression + * @return CollectionMemberExpression */ public function CollectionMemberExpression() { @@ -2656,8 +2711,9 @@ public function CollectionMemberExpression() $this->match(Lexer::T_OF); } - $collMemberExpr = new AST\CollectionMemberExpression( - $entityExpr, $this->CollectionValuedPathExpression() + $collMemberExpr = new AST\CollectionMemberExpression( + $entityExpr, + $this->CollectionValuedPathExpression() ); $collMemberExpr->not = $not; @@ -2667,7 +2723,7 @@ public function CollectionMemberExpression() /** * Literal ::= string | char | integer | float | boolean * - * @return \Doctrine\ORM\Query\AST\Literal + * @return Literal */ public function Literal() { @@ -2676,6 +2732,7 @@ public function Literal() $this->match(Lexer::T_STRING); return new AST\Literal(AST\Literal::STRING, $this->lexer->token['value']); + case Lexer::T_INTEGER: case Lexer::T_FLOAT: $this->match( @@ -2683,6 +2740,7 @@ public function Literal() ); return new AST\Literal(AST\Literal::NUMERIC, $this->lexer->token['value']); + case Lexer::T_TRUE: case Lexer::T_FALSE: $this->match( @@ -2690,6 +2748,7 @@ public function Literal() ); return new AST\Literal(AST\Literal::BOOLEAN, $this->lexer->token['value']); + default: $this->syntaxError('Literal'); } @@ -2702,7 +2761,7 @@ public function Literal() */ public function InParameter() { - if ($this->lexer->lookahead['type'] == Lexer::T_INPUT_PARAMETER) { + if ($this->lexer->lookahead['type'] === Lexer::T_INPUT_PARAMETER) { return $this->InputParameter(); } @@ -2712,7 +2771,7 @@ public function InParameter() /** * InputParameter ::= PositionalParameter | NamedParameter * - * @return \Doctrine\ORM\Query\AST\InputParameter + * @return InputParameter */ public function InputParameter() { @@ -2724,11 +2783,11 @@ public function InputParameter() /** * ArithmeticExpression ::= SimpleArithmeticExpression | "(" Subselect ")" * - * @return \Doctrine\ORM\Query\AST\ArithmeticExpression + * @return ArithmeticExpression */ public function ArithmeticExpression() { - $expr = new AST\ArithmeticExpression; + $expr = new AST\ArithmeticExpression(); if ($this->lexer->isNextToken(Lexer::T_OPEN_PARENTHESIS)) { $peek = $this->lexer->glimpse(); @@ -2750,15 +2809,15 @@ public function ArithmeticExpression() /** * SimpleArithmeticExpression ::= ArithmeticTerm {("+" | "-") ArithmeticTerm}* * - * @return \Doctrine\ORM\Query\AST\SimpleArithmeticExpression + * @return SimpleArithmeticExpression */ public function SimpleArithmeticExpression() { - $terms = []; + $terms = []; $terms[] = $this->ArithmeticTerm(); while (($isPlus = $this->lexer->isNextToken(Lexer::T_PLUS)) || $this->lexer->isNextToken(Lexer::T_MINUS)) { - $this->match(($isPlus) ? Lexer::T_PLUS : Lexer::T_MINUS); + $this->match($isPlus ? Lexer::T_PLUS : Lexer::T_MINUS); $terms[] = $this->lexer->token['value']; $terms[] = $this->ArithmeticTerm(); @@ -2766,7 +2825,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]; } @@ -2776,15 +2835,15 @@ public function SimpleArithmeticExpression() /** * ArithmeticTerm ::= ArithmeticFactor {("*" | "/") ArithmeticFactor}* * - * @return \Doctrine\ORM\Query\AST\ArithmeticTerm + * @return ArithmeticTerm */ public function ArithmeticTerm() { - $factors = []; + $factors = []; $factors[] = $this->ArithmeticFactor(); while (($isMult = $this->lexer->isNextToken(Lexer::T_MULTIPLY)) || $this->lexer->isNextToken(Lexer::T_DIVIDE)) { - $this->match(($isMult) ? Lexer::T_MULTIPLY : Lexer::T_DIVIDE); + $this->match($isMult ? Lexer::T_MULTIPLY : Lexer::T_DIVIDE); $factors[] = $this->lexer->token['value']; $factors[] = $this->ArithmeticFactor(); @@ -2792,7 +2851,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]; } @@ -2802,14 +2861,14 @@ public function ArithmeticTerm() /** * ArithmeticFactor ::= [("+" | "-")] ArithmeticPrimary * - * @return \Doctrine\ORM\Query\AST\ArithmeticFactor + * @return ArithmeticFactor */ public function ArithmeticFactor() { $sign = null; if (($isPlus = $this->lexer->isNextToken(Lexer::T_PLUS)) || $this->lexer->isNextToken(Lexer::T_MINUS)) { - $this->match(($isPlus) ? Lexer::T_PLUS : Lexer::T_MINUS); + $this->match($isPlus ? Lexer::T_PLUS : Lexer::T_MINUS); $sign = $isPlus; } @@ -2898,8 +2957,10 @@ public function StringExpression() } // ResultVariable (string) - if ($this->lexer->isNextToken(Lexer::T_IDENTIFIER) && - isset($this->queryComponents[$this->lexer->lookahead['value']]['resultVariable'])) { + if ( + $this->lexer->isNextToken(Lexer::T_IDENTIFIER) && + isset($this->queryComponents[$this->lexer->lookahead['value']]['resultVariable']) + ) { return $this->ResultVariable(); } @@ -2917,11 +2978,11 @@ public function StringPrimary() case Lexer::T_IDENTIFIER: $peek = $this->lexer->glimpse(); - if ($peek['value'] == '.') { + if ($peek['value'] === '.') { return $this->StateFieldPathExpression(); } - if ($peek['value'] == '(') { + if ($peek['value'] === '(') { // do NOT directly go to FunctionsReturningString() because it doesn't check for custom functions. return $this->FunctionDeclaration(); } @@ -2941,6 +3002,7 @@ public function StringPrimary() case Lexer::T_COALESCE: case Lexer::T_NULLIF: return $this->CaseExpression(); + default: if ($this->isAggregateFunction($lookaheadType)) { return $this->AggregateExpression(); @@ -2986,14 +3048,14 @@ public function SimpleEntityExpression() * AggregateExpression ::= * ("AVG" | "MAX" | "MIN" | "SUM" | "COUNT") "(" ["DISTINCT"] SimpleArithmeticExpression ")" * - * @return \Doctrine\ORM\Query\AST\AggregateExpression + * @return AggregateExpression */ public function AggregateExpression() { $lookaheadType = $this->lexer->lookahead['type']; - $isDistinct = false; + $isDistinct = false; - if ( ! in_array($lookaheadType, [Lexer::T_COUNT, Lexer::T_AVG, Lexer::T_MAX, Lexer::T_MIN, Lexer::T_SUM])) { + if (! in_array($lookaheadType, [Lexer::T_COUNT, Lexer::T_AVG, Lexer::T_MAX, Lexer::T_MIN, Lexer::T_SUM])) { $this->syntaxError('One of: MAX, MIN, AVG, SUM, COUNT'); } @@ -3016,21 +3078,21 @@ public function AggregateExpression() /** * QuantifiedExpression ::= ("ALL" | "ANY" | "SOME") "(" Subselect ")" * - * @return \Doctrine\ORM\Query\AST\QuantifiedExpression + * @return QuantifiedExpression */ public function QuantifiedExpression() { $lookaheadType = $this->lexer->lookahead['type']; - $value = $this->lexer->lookahead['value']; + $value = $this->lexer->lookahead['value']; - if ( ! in_array($lookaheadType, [Lexer::T_ALL, Lexer::T_ANY, Lexer::T_SOME])) { + if (! in_array($lookaheadType, [Lexer::T_ALL, Lexer::T_ANY, Lexer::T_SOME])) { $this->syntaxError('ALL, ANY or SOME'); } $this->match($lookaheadType); $this->match(Lexer::T_OPEN_PARENTHESIS); - $qExpr = new AST\QuantifiedExpression($this->Subselect()); + $qExpr = new AST\QuantifiedExpression($this->Subselect()); $qExpr->type = $value; $this->match(Lexer::T_CLOSE_PARENTHESIS); @@ -3041,11 +3103,11 @@ public function QuantifiedExpression() /** * BetweenExpression ::= ArithmeticExpression ["NOT"] "BETWEEN" ArithmeticExpression "AND" ArithmeticExpression * - * @return \Doctrine\ORM\Query\AST\BetweenExpression + * @return BetweenExpression */ public function BetweenExpression() { - $not = false; + $not = false; $arithExpr1 = $this->ArithmeticExpression(); if ($this->lexer->isNextToken(Lexer::T_NOT)) { @@ -3058,7 +3120,7 @@ public function BetweenExpression() $this->match(Lexer::T_AND); $arithExpr3 = $this->ArithmeticExpression(); - $betweenExpr = new AST\BetweenExpression($arithExpr1, $arithExpr2, $arithExpr3); + $betweenExpr = new AST\BetweenExpression($arithExpr1, $arithExpr2, $arithExpr3); $betweenExpr->not = $not; return $betweenExpr; @@ -3067,7 +3129,7 @@ public function BetweenExpression() /** * ComparisonExpression ::= ArithmeticExpression ComparisonOperator ( QuantifiedExpression | ArithmeticExpression ) * - * @return \Doctrine\ORM\Query\AST\ComparisonExpression + * @return ComparisonExpression */ public function ComparisonExpression() { @@ -3075,7 +3137,7 @@ public function ComparisonExpression() $leftExpr = $this->ArithmeticExpression(); $operator = $this->ComparisonOperator(); - $rightExpr = ($this->isNextAllAnySome()) + $rightExpr = $this->isNextAllAnySome() ? $this->QuantifiedExpression() : $this->ArithmeticExpression(); @@ -3085,7 +3147,7 @@ public function ComparisonExpression() /** * InExpression ::= SingleValuedPathExpression ["NOT"] "IN" "(" (InParameter {"," InParameter}* | Subselect) ")" * - * @return \Doctrine\ORM\Query\AST\InExpression + * @return InExpression */ public function InExpression() { @@ -3102,7 +3164,7 @@ public function InExpression() if ($this->lexer->isNextToken(Lexer::T_SELECT)) { $inExpression->subselect = $this->Subselect(); } else { - $literals = []; + $literals = []; $literals[] = $this->InParameter(); while ($this->lexer->isNextToken(Lexer::T_COMMA)) { @@ -3121,7 +3183,7 @@ public function InExpression() /** * InstanceOfExpression ::= IdentificationVariable ["NOT"] "INSTANCE" ["OF"] (InstanceOfParameter | "(" InstanceOfParameter {"," InstanceOfParameter}* ")") * - * @return \Doctrine\ORM\Query\AST\InstanceOfExpression + * @return InstanceOfExpression */ public function InstanceOfExpression() { @@ -3185,12 +3247,12 @@ public function InstanceOfParameter() /** * LikeExpression ::= StringExpression ["NOT"] "LIKE" StringPrimary ["ESCAPE" char] * - * @return \Doctrine\ORM\Query\AST\LikeExpression + * @return LikeExpression */ public function LikeExpression() { $stringExpr = $this->StringExpression(); - $not = false; + $not = false; if ($this->lexer->isNextToken(Lexer::T_NOT)) { $this->match(Lexer::T_NOT); @@ -3215,7 +3277,7 @@ public function LikeExpression() $escapeChar = new AST\Literal(AST\Literal::STRING, $this->lexer->token['value']); } - $likeExpr = new AST\LikeExpression($stringExpr, $stringPattern, $escapeChar); + $likeExpr = new AST\LikeExpression($stringExpr, $stringPattern, $escapeChar); $likeExpr->not = $not; return $likeExpr; @@ -3224,7 +3286,7 @@ public function LikeExpression() /** * NullComparisonExpression ::= (InputParameter | NullIfExpression | CoalesceExpression | AggregateExpression | FunctionDeclaration | IdentificationVariable | SingleValuedPathExpression | ResultVariable) "IS" ["NOT"] "NULL" * - * @return \Doctrine\ORM\Query\AST\NullComparisonExpression + * @return NullComparisonExpression */ public function NullComparisonExpression() { @@ -3261,7 +3323,7 @@ public function NullComparisonExpression() $lookaheadValue = $this->lexer->lookahead['value']; // Validate existing component - if ( ! isset($this->queryComponents[$lookaheadValue])) { + if (! isset($this->queryComponents[$lookaheadValue])) { $this->semanticalError('Cannot add having condition on undefined result variable.'); } @@ -3272,7 +3334,7 @@ public function NullComparisonExpression() } // Validating ResultVariable - if ( ! isset($this->queryComponents[$lookaheadValue]['resultVariable'])) { + if (! isset($this->queryComponents[$lookaheadValue]['resultVariable'])) { $this->semanticalError('Cannot add having condition on a non result variable.'); } @@ -3298,7 +3360,7 @@ public function NullComparisonExpression() /** * ExistsExpression ::= ["NOT"] "EXISTS" "(" Subselect ")" * - * @return \Doctrine\ORM\Query\AST\ExistsExpression + * @return ExistsExpression */ public function ExistsExpression() { @@ -3312,7 +3374,7 @@ public function ExistsExpression() $this->match(Lexer::T_EXISTS); $this->match(Lexer::T_OPEN_PARENTHESIS); - $existsExpression = new AST\ExistsExpression($this->Subselect()); + $existsExpression = new AST\ExistsExpression($this->Subselect()); $existsExpression->not = $not; $this->match(Lexer::T_CLOSE_PARENTHESIS); @@ -3340,7 +3402,7 @@ public function ComparisonOperator() if ($this->lexer->isNextToken(Lexer::T_EQUALS)) { $this->match(Lexer::T_EQUALS); $operator .= '='; - } else if ($this->lexer->isNextToken(Lexer::T_GREATER_THAN)) { + } elseif ($this->lexer->isNextToken(Lexer::T_GREATER_THAN)) { $this->match(Lexer::T_GREATER_THAN); $operator .= '>'; } @@ -3372,11 +3434,11 @@ public function ComparisonOperator() /** * FunctionDeclaration ::= FunctionsReturningStrings | FunctionsReturningNumerics | FunctionsReturningDatetime * - * @return \Doctrine\ORM\Query\AST\Functions\FunctionNode + * @return FunctionNode */ public function FunctionDeclaration() { - $token = $this->lexer->lookahead; + $token = $this->lexer->lookahead; $funcName = strtolower($token['value']); $customFunctionDeclaration = $this->CustomFunctionDeclaration(); @@ -3386,13 +3448,13 @@ public function FunctionDeclaration() case $customFunctionDeclaration !== null: return $customFunctionDeclaration; - case (isset(self::$_STRING_FUNCTIONS[$funcName])): + case isset(self::$_STRING_FUNCTIONS[$funcName]): return $this->FunctionsReturningStrings(); - case (isset(self::$_NUMERIC_FUNCTIONS[$funcName])): + case isset(self::$_NUMERIC_FUNCTIONS[$funcName]): return $this->FunctionsReturningNumerics(); - case (isset(self::$_DATETIME_FUNCTIONS[$funcName])): + case isset(self::$_DATETIME_FUNCTIONS[$funcName]): return $this->FunctionsReturningDatetime(); default: @@ -3403,24 +3465,24 @@ public function FunctionDeclaration() /** * Helper function for FunctionDeclaration grammar rule. * - * @return \Doctrine\ORM\Query\AST\Functions\FunctionNode + * @return FunctionNode */ private function CustomFunctionDeclaration() { - $token = $this->lexer->lookahead; + $token = $this->lexer->lookahead; $funcName = strtolower($token['value']); // Check for custom functions afterwards $config = $this->em->getConfiguration(); switch (true) { - case ($config->getCustomStringFunction($funcName) !== null): + case $config->getCustomStringFunction($funcName) !== null: return $this->CustomFunctionsReturningStrings(); - case ($config->getCustomNumericFunction($funcName) !== null): + case $config->getCustomNumericFunction($funcName) !== null: return $this->CustomFunctionsReturningNumerics(); - case ($config->getCustomDatetimeFunction($funcName) !== null): + case $config->getCustomDatetimeFunction($funcName) !== null: return $this->CustomFunctionsReturningDatetime(); default: @@ -3440,7 +3502,7 @@ private function CustomFunctionDeclaration() * "BIT_AND" "(" ArithmeticPrimary "," ArithmeticPrimary ")" | * "BIT_OR" "(" ArithmeticPrimary "," ArithmeticPrimary ")" * - * @return \Doctrine\ORM\Query\AST\Functions\FunctionNode + * @return FunctionNode */ public function FunctionsReturningNumerics() { @@ -3454,7 +3516,7 @@ public function FunctionsReturningNumerics() } /** - * @return \Doctrine\ORM\Query\AST\Functions\FunctionNode + * @return FunctionNode */ public function CustomFunctionsReturningNumerics() { @@ -3479,7 +3541,7 @@ public function CustomFunctionsReturningNumerics() * "DATE_ADD" "(" ArithmeticPrimary "," ArithmeticPrimary "," StringPrimary ")" | * "DATE_SUB" "(" ArithmeticPrimary "," ArithmeticPrimary "," StringPrimary ")" * - * @return \Doctrine\ORM\Query\AST\Functions\FunctionNode + * @return FunctionNode */ public function FunctionsReturningDatetime() { @@ -3493,7 +3555,7 @@ public function FunctionsReturningDatetime() } /** - * @return \Doctrine\ORM\Query\AST\Functions\FunctionNode + * @return FunctionNode */ public function CustomFunctionsReturningDatetime() { @@ -3519,7 +3581,7 @@ public function CustomFunctionsReturningDatetime() * "UPPER" "(" StringPrimary ")" | * "IDENTITY" "(" SingleValuedAssociationPathExpression {"," string} ")" * - * @return \Doctrine\ORM\Query\AST\Functions\FunctionNode + * @return FunctionNode */ public function FunctionsReturningStrings() { @@ -3533,7 +3595,7 @@ public function FunctionsReturningStrings() } /** - * @return \Doctrine\ORM\Query\AST\Functions\FunctionNode + * @return FunctionNode */ public function CustomFunctionsReturningStrings() { diff --git a/lib/Doctrine/ORM/Query/ParserResult.php b/lib/Doctrine/ORM/Query/ParserResult.php index 4a4d0184e96..eca0e75e7d7 100644 --- a/lib/Doctrine/ORM/Query/ParserResult.php +++ b/lib/Doctrine/ORM/Query/ParserResult.php @@ -1,4 +1,5 @@ - * @author Janne Vanhala - * @author Roman Borschel - * @license http://www.opensource.org/licenses/mit-license.php MIT * @link http://www.doctrine-project.org - * @since 2.0 */ class ParserResult { /** * The SQL executor used for executing the SQL. * - * @var \Doctrine\ORM\Query\Exec\AbstractSqlExecutor + * @var AbstractSqlExecutor */ private $_sqlExecutor; /** * The ResultSetMapping that describes how to map the SQL result set. * - * @var \Doctrine\ORM\Query\ResultSetMapping + * @var ResultSetMapping */ private $_resultSetMapping; @@ -59,7 +57,7 @@ class ParserResult */ public function __construct() { - $this->_resultSetMapping = new ResultSetMapping; + $this->_resultSetMapping = new ResultSetMapping(); } /** @@ -75,8 +73,6 @@ public function getResultSetMapping() /** * Sets the ResultSetMapping of the parsed query. * - * @param ResultSetMapping $rsm - * * @return void */ public function setResultSetMapping(ResultSetMapping $rsm) @@ -87,7 +83,7 @@ public function setResultSetMapping(ResultSetMapping $rsm) /** * Sets the SQL executor that should be used for this ParserResult. * - * @param \Doctrine\ORM\Query\Exec\AbstractSqlExecutor $executor + * @param AbstractSqlExecutor $executor * * @return void */ @@ -99,7 +95,7 @@ public function setSqlExecutor($executor) /** * Gets the SQL executor used by this ParserResult. * - * @return \Doctrine\ORM\Query\Exec\AbstractSqlExecutor + * @return AbstractSqlExecutor */ public function getSqlExecutor() { @@ -110,8 +106,8 @@ public function getSqlExecutor() * Adds a DQL to SQL parameter mapping. One DQL parameter name/position can map to * several SQL parameter positions. * - * @param string|integer $dqlPosition - * @param integer $sqlPosition + * @param string|int $dqlPosition + * @param int $sqlPosition * * @return void */ @@ -133,7 +129,7 @@ public function getParameterMappings() /** * Gets the SQL parameter positions for a DQL parameter name/position. * - * @param string|integer $dqlPosition The name or position of the DQL parameter. + * @param string|int $dqlPosition The name or position of the DQL parameter. * * @return array The positions of the corresponding SQL parameters. */ diff --git a/lib/Doctrine/ORM/Query/Printer.php b/lib/Doctrine/ORM/Query/Printer.php index d92ad850f5b..6b43c09de14 100644 --- a/lib/Doctrine/ORM/Query/Printer.php +++ b/lib/Doctrine/ORM/Query/Printer.php @@ -1,4 +1,5 @@ - * @license http://www.opensource.org/licenses/mit-license.php MIT * @link http://www.phpdoctrine.org - * @since 2.0 */ class Printer { @@ -91,7 +91,7 @@ public function endProduction() */ public function println($str) { - if ( ! $this->_silent) { + 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..ce59d4f3c5f 100644 --- a/lib/Doctrine/ORM/Query/QueryException.php +++ b/lib/Doctrine/ORM/Query/QueryException.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel - * @author Benjamin Eberlei */ -class QueryException extends \Doctrine\ORM\ORMException +class QueryException extends ORMException { /** * @param string $dql @@ -44,8 +42,8 @@ public static function dqlError($dql) } /** - * @param string $message - * @param \Exception|null $previous + * @param string $message + * @param Exception|null $previous * * @return QueryException */ @@ -55,8 +53,8 @@ public static function syntaxError($message, $previous = null) } /** - * @param string $message - * @param \Exception|null $previous + * @param string $message + * @param Exception|null $previous * * @return QueryException */ @@ -95,8 +93,8 @@ public static function invalidParameterPosition($pos) } /** - * @param integer $expected - * @param integer $received + * @param int $expected + * @param int $received * * @return QueryException */ @@ -106,8 +104,8 @@ public static function tooManyParameters($expected, $received) } /** - * @param integer $expected - * @param integer $received + * @param int $expected + * @param int $received * * @return QueryException */ @@ -123,7 +121,7 @@ public static function tooFewParameters($expected, $received) */ public static function invalidParameterFormat($value) { - return new self('Invalid parameter format, '.$value.' given, but : or ? expected.'); + return new self('Invalid parameter format, ' . $value . ' given, but : or ? expected.'); } /** @@ -133,7 +131,7 @@ public static function invalidParameterFormat($value) */ public static function unknownParameter($key) { - return new self("Invalid parameter: token ".$key." is not defined in the query."); + return new self('Invalid parameter: token ' . $key . ' is not defined in the query.'); } /** @@ -141,7 +139,7 @@ public static function unknownParameter($key) */ public static function parameterTypeMismatch() { - return new self("DQL Query parameter and type numbers mismatch, but have to be exactly equal."); + return new self('DQL Query parameter and type numbers mismatch, but have to be exactly equal.'); } /** @@ -152,7 +150,7 @@ public static function parameterTypeMismatch() public static function invalidPathExpression($pathExpr) { return new self( - "Invalid PathExpression '" . $pathExpr->identificationVariable . "." . $pathExpr->field . "'." + "Invalid PathExpression '" . $pathExpr->identificationVariable . '.' . $pathExpr->field . "'." ); } @@ -174,8 +172,8 @@ public static function invalidLiteral($literal) public static function iterateWithFetchJoinCollectionNotAllowed($assoc) { return new self( - "Invalid query operation: Not allowed to iterate over fetch join collections ". - "in class ".$assoc['sourceEntity']." association ".$assoc['fieldName'] + 'Invalid query operation: Not allowed to iterate over fetch join collections ' . + 'in class ' . $assoc['sourceEntity'] . ' association ' . $assoc['fieldName'] ); } @@ -185,9 +183,9 @@ public static function iterateWithFetchJoinCollectionNotAllowed($assoc) public static function partialObjectsAreDangerous() { return new self( - "Loading partial objects is dangerous. Fetch full objects or consider " . - "using a different fetch mode. If you really want partial objects, " . - "set the doctrine.forcePartialLoad query hint to TRUE." + 'Loading partial objects is dangerous. Fetch full objects or consider ' . + 'using a different fetch mode. If you really want partial objects, ' . + 'set the doctrine.forcePartialLoad query hint to TRUE.' ); } @@ -199,15 +197,13 @@ public static function partialObjectsAreDangerous() public static function overwritingJoinConditionsNotYetSupported($assoc) { return new self( - "Unsupported query operation: It is not yet possible to overwrite the join ". - "conditions in class ".$assoc['sourceEntityName']." association ".$assoc['fieldName'].". ". - "Use WITH to append additional join conditions to the association." + 'Unsupported query operation: It is not yet possible to overwrite the join ' . + 'conditions in class ' . $assoc['sourceEntityName'] . ' association ' . $assoc['fieldName'] . '. ' . + 'Use WITH to append additional join conditions to the association.' ); } /** - * @param PathExpression $pathExpr - * * @return QueryException */ public static function associationPathInverseSideNotSupported(PathExpression $pathExpr) @@ -226,8 +222,8 @@ public static function associationPathInverseSideNotSupported(PathExpression $pa public static function iterateWithFetchJoinNotAllowed($assoc) { return new self( - "Iterate with fetch join in class " . $assoc['sourceEntity'] . - " using association " . $assoc['fieldName'] . " not allowed." + 'Iterate with fetch join in class ' . $assoc['sourceEntity'] . + ' using association ' . $assoc['fieldName'] . ' not allowed.' ); } @@ -237,9 +233,9 @@ public static function iterateWithFetchJoinNotAllowed($assoc) public static function associationPathCompositeKeyNotSupported() { return new self( - "A single-valued association path expression to an entity with a composite primary ". - "key is not supported. Explicitly name the components of the composite primary key ". - "in the query." + 'A single-valued association path expression to an entity with a composite primary ' . + 'key is not supported. Explicitly name the components of the composite primary key ' . + 'in the query.' ); } @@ -252,7 +248,7 @@ public static function associationPathCompositeKeyNotSupported() public static function instanceOfUnrelatedClass($className, $rootClass) { return new self("Cannot check if a child of '" . $rootClass . "' is instanceof '" . $className . "', " . - "inheritance hierarchy does not exists between these two classes."); + 'inheritance hierarchy does not exists between these two classes.'); } /** @@ -263,7 +259,7 @@ public static function instanceOfUnrelatedClass($className, $rootClass) public static function invalidQueryComponent($dqlAlias) { return new self( - "Invalid query component given for DQL alias '" . $dqlAlias . "', ". + "Invalid query component given for DQL alias '" . $dqlAlias . "', " . "requires 'metadata', 'parent', 'relation', 'map', 'nestingLevel' and 'token' keys." ); } diff --git a/lib/Doctrine/ORM/Query/QueryExpressionVisitor.php b/lib/Doctrine/ORM/Query/QueryExpressionVisitor.php index 0381ac037d4..bb2901cf540 100644 --- a/lib/Doctrine/ORM/Query/QueryExpressionVisitor.php +++ b/lib/Doctrine/ORM/Query/QueryExpressionVisitor.php @@ -1,4 +1,5 @@ - * @since 2.4 */ class QueryExpressionVisitor extends ExpressionVisitor { - /** - * @var array - */ + /** @var array */ private static $operatorMap = [ Comparison::GT => Expr\Comparison::GT, Comparison::GTE => Expr\Comparison::GTE, Comparison::LT => Expr\Comparison::LT, - Comparison::LTE => Expr\Comparison::LTE + Comparison::LTE => Expr\Comparison::LTE, ]; - /** - * @var array - */ + /** @var array */ private $queryAliases; - /** - * @var Expr - */ + /** @var Expr */ private $expr; - /** - * @var array - */ + /** @var array */ private $parameters = []; /** @@ -67,14 +62,14 @@ class QueryExpressionVisitor extends ExpressionVisitor public function __construct($queryAliases) { $this->queryAliases = $queryAliases; - $this->expr = new Expr(); + $this->expr = new Expr(); } /** * Gets bound parameters. * Filled after {@link dispach()}. * - * @return \Doctrine\Common\Collections\Collection + * @return Collection */ public function getParameters() { @@ -100,7 +95,7 @@ public function clearParameters() */ private static function convertComparisonOperator($criteriaOperator) { - return isset(self::$operatorMap[$criteriaOperator]) ? self::$operatorMap[$criteriaOperator] : null; + return self::$operatorMap[$criteriaOperator] ?? null; } /** @@ -114,7 +109,7 @@ public function walkCompositeExpression(CompositeExpression $expr) $expressionList[] = $this->dispatch($child); } - switch($expr->getType()) { + switch ($expr->getType()) { case CompositeExpression::TYPE_AND: return new Expr\Andx($expressionList); @@ -122,7 +117,7 @@ public function walkCompositeExpression(CompositeExpression $expr) return new Expr\Orx($expressionList); default: - throw new \RuntimeException("Unknown composite " . $expr->getType()); + throw new RuntimeException('Unknown composite ' . $expr->getType()); } } @@ -131,15 +126,14 @@ public function walkCompositeExpression(CompositeExpression $expr) */ public function walkComparison(Comparison $comparison) { - - if ( ! isset($this->queryAliases[0])) { + if (! isset($this->queryAliases[0])) { throw new QueryException('No aliases are set before invoking walkComparison().'); } $field = $this->queryAliases[0] . '.' . $comparison->getField(); - foreach($this->queryAliases as $alias) { - if(strpos($comparison->getField() . '.', $alias . '.') === 0) { + foreach ($this->queryAliases as $alias) { + if (strpos($comparison->getField() . '.', $alias . '.') === 0) { $field = $comparison->getField(); break; } @@ -154,7 +148,7 @@ public function walkComparison(Comparison $comparison) } } - $parameter = new Parameter($parameterName, $this->walkValue($comparison->getValue())); + $parameter = new Parameter($parameterName, $this->walkValue($comparison->getValue())); $placeholder = ':' . $parameterName; switch ($comparison->getOperator()) { @@ -162,42 +156,52 @@ public function walkComparison(Comparison $comparison) $this->parameters[] = $parameter; return $this->expr->in($field, $placeholder); + case Comparison::NIN: $this->parameters[] = $parameter; return $this->expr->notIn($field, $placeholder); + case Comparison::EQ: case Comparison::IS: if ($this->walkValue($comparison->getValue()) === null) { return $this->expr->isNull($field); } + $this->parameters[] = $parameter; return $this->expr->eq($field, $placeholder); + case Comparison::NEQ: if ($this->walkValue($comparison->getValue()) === null) { return $this->expr->isNotNull($field); } + $this->parameters[] = $parameter; return $this->expr->neq($field, $placeholder); + case Comparison::CONTAINS: $parameter->setValue('%' . $parameter->getValue() . '%', $parameter->getType()); $this->parameters[] = $parameter; return $this->expr->like($field, $placeholder); + case Comparison::MEMBER_OF: return $this->expr->isMemberOf($comparison->getField(), $comparison->getValue()->getValue()); + case Comparison::STARTS_WITH: $parameter->setValue($parameter->getValue() . '%', $parameter->getType()); $this->parameters[] = $parameter; return $this->expr->like($field, $placeholder); + case Comparison::ENDS_WITH: $parameter->setValue('%' . $parameter->getValue(), $parameter->getType()); $this->parameters[] = $parameter; return $this->expr->like($field, $placeholder); + default: $operator = self::convertComparisonOperator($comparison->getOperator()); if ($operator) { @@ -210,7 +214,7 @@ public function walkComparison(Comparison $comparison) ); } - throw new \RuntimeException("Unknown comparison operator: " . $comparison->getOperator()); + throw new RuntimeException('Unknown comparison operator: ' . $comparison->getOperator()); } } diff --git a/lib/Doctrine/ORM/Query/ResultSetMapping.php b/lib/Doctrine/ORM/Query/ResultSetMapping.php index 477678c2ed0..36028215360 100644 --- a/lib/Doctrine/ORM/Query/ResultSetMapping.php +++ b/lib/Doctrine/ORM/Query/ResultSetMapping.php @@ -1,4 +1,5 @@ Users should use the public methods. * - * @author Roman Borschel - * @since 2.0 * @todo Think about whether the number of lookup maps can be reduced. */ class ResultSetMapping @@ -39,7 +41,7 @@ class ResultSetMapping * Whether the result is mixed (contains scalar values together with field values). * * @ignore - * @var boolean + * @var bool */ public $isMixed = false; @@ -47,7 +49,7 @@ class ResultSetMapping * Whether the result is a select statement. * * @ignore - * @var boolean + * @var bool */ public $isSelect = true; @@ -190,7 +192,7 @@ class ResultSetMapping */ public function addEntityResult($class, $alias, $resultAlias = null) { - $this->aliasMap[$alias] = $class; + $this->aliasMap[$alias] = $class; $this->entityMappings[$alias] = $resultAlias; if ($resultAlias !== null) { @@ -234,7 +236,9 @@ public function addIndexBy($alias, $fieldName) $found = false; foreach (array_merge($this->metaMappings, $this->fieldMappings) as $columnName => $columnFieldName) { - if ( ! ($columnFieldName === $fieldName && $this->columnOwnerMap[$columnName] === $alias)) continue; + if (! ($columnFieldName === $fieldName && $this->columnOwnerMap[$columnName] === $alias)) { + continue; + } $this->addIndexByColumn($alias, $columnName); $found = true; @@ -292,7 +296,7 @@ public function addIndexByColumn($alias, $resultColumnName) * * @param string $alias * - * @return boolean + * @return bool * * @todo Rename: isIndexed($alias) */ @@ -307,7 +311,7 @@ public function hasIndexBy($alias) * * @param string $columnName The name of the column in the SQL result set. * - * @return boolean + * @return bool * * @todo Rename: isField */ @@ -341,7 +345,7 @@ public function addFieldResult($alias, $columnName, $fieldName, $declaringClass // field name => class name of declaring class $this->declaringClasses[$columnName] = $declaringClass ?: $this->aliasMap[$alias]; - if ( ! $this->isMixed && $this->scalarMappings) { + if (! $this->isMixed && $this->scalarMappings) { $this->isMixed = true; } @@ -386,7 +390,7 @@ public function addScalarResult($columnName, $alias, $type = 'string') $this->scalarMappings[$columnName] = $alias; $this->typeMappings[$columnName] = $type; - if ( ! $this->isMixed && $this->fieldMappings) { + if (! $this->isMixed && $this->fieldMappings) { $this->isMixed = true; } @@ -409,7 +413,7 @@ public function addMetadataParameterMapping($parameter, $attribute) * * @param string $columnName The name of the column in the SQL result set. * - * @return boolean + * @return bool * * @todo Rename: isScalar */ @@ -468,7 +472,7 @@ public function getRelation($alias) /** * @param string $alias * - * @return boolean + * @return bool */ public function isRelation($alias) { @@ -504,7 +508,7 @@ public function getParentAlias($alias) * * @param string $alias * - * @return boolean + * @return bool */ public function hasParentAlias($alias) { @@ -534,7 +538,7 @@ public function getAliasMap() /** * Gets the number of different entities that appear in the mapped result. * - * @return integer + * @return int */ public function getEntityResultCount() { @@ -548,7 +552,7 @@ public function getEntityResultCount() * case a mixed result means that scalar values are mixed with objects/array in * the result. * - * @return boolean + * @return bool */ public function isMixedResult() { @@ -570,7 +574,7 @@ public function isMixedResult() */ public function addMetaResult($alias, $columnName, $fieldName, $isIdentifierColumn = false, $type = null) { - $this->metaMappings[$columnName] = $fieldName; + $this->metaMappings[$columnName] = $fieldName; $this->columnOwnerMap[$columnName] = $alias; if ($isIdentifierColumn) { diff --git a/lib/Doctrine/ORM/Query/ResultSetMappingBuilder.php b/lib/Doctrine/ORM/Query/ResultSetMappingBuilder.php index 5fe71d6b181..8fd3502b5a3 100644 --- a/lib/Doctrine/ORM/Query/ResultSetMappingBuilder.php +++ b/lib/Doctrine/ORM/Query/ResultSetMappingBuilder.php @@ -1,4 +1,5 @@ - * @since 2.1 */ class ResultSetMappingBuilder extends ResultSetMapping { @@ -37,38 +40,28 @@ class ResultSetMappingBuilder extends ResultSetMapping * Picking this rename mode will register entity columns as is, * as they are in the database. This can cause clashes when multiple * entities are fetched that have columns with the same name. - * - * @var int */ - const COLUMN_RENAMING_NONE = 1; + public const COLUMN_RENAMING_NONE = 1; /** * Picking custom renaming allows the user to define the renaming * of specific columns with a rename array that contains column names as * keys and result alias as values. - * - * @var int */ - const COLUMN_RENAMING_CUSTOM = 2; + public const COLUMN_RENAMING_CUSTOM = 2; /** * Incremental renaming uses a result set mapping internal counter to add a * number to each column result, leading to uniqueness. This only works if * you use {@see generateSelectClause()} to generate the SELECT clause for * you. - * - * @var int */ - const COLUMN_RENAMING_INCREMENT = 3; + public const COLUMN_RENAMING_INCREMENT = 3; - /** - * @var int - */ + /** @var int */ private $sqlCounter = 0; - /** - * @var EntityManagerInterface - */ + /** @var EntityManagerInterface */ private $em; /** @@ -79,8 +72,7 @@ class ResultSetMappingBuilder extends ResultSetMapping private $defaultRenameMode; /** - * @param EntityManagerInterface $em - * @param integer $defaultRenameMode + * @param int $defaultRenameMode */ public function __construct(EntityManagerInterface $em, $defaultRenameMode = self::COLUMN_RENAMING_NONE) { @@ -138,24 +130,23 @@ public function addJoinedEntityFromClassMetadata($class, $alias, $parentAlias, $ * * @return void * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ protected function addAllClassFields($class, $alias, $columnAliasMap = []) { $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->getColumnNames() as $columnName) { $propertyName = $classMetadata->getFieldName($columnName); $columnAlias = $platform->getSQLResultCasing($columnAliasMap[$columnName]); if (isset($this->fieldMappings[$columnAlias])) { - throw new \InvalidArgumentException("The column '$columnName' conflicts with another column in the mapper."); + throw new InvalidArgumentException("The column '$columnName' conflicts with another column in the mapper."); } $this->addFieldResult($alias, $columnAlias, $propertyName); @@ -169,10 +160,10 @@ protected function addAllClassFields($class, $alias, $columnAliasMap = []) foreach ($associationMapping['joinColumns'] as $joinColumn) { $columnName = $joinColumn['name']; $columnAlias = $platform->getSQLResultCasing($columnAliasMap[$columnName]); - $columnType = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em); + $columnType = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em); if (isset($this->metaMappings[$columnAlias])) { - throw new \InvalidArgumentException("The column '$columnAlias' conflicts with another column in the mapper."); + throw new InvalidArgumentException("The column '$columnAlias' conflicts with another column in the mapper."); } $this->addMetaResult($alias, $columnAlias, $columnName, $isIdentifier, $columnType); @@ -183,8 +174,10 @@ protected function addAllClassFields($class, $alias, $columnAliasMap = []) private function isInheritanceSupported(ClassMetadataInfo $classMetadata) { - if ($classMetadata->isInheritanceTypeSingleTable() - && in_array($classMetadata->name, $classMetadata->discriminatorMap, true)) { + if ( + $classMetadata->isInheritanceTypeSingleTable() + && in_array($classMetadata->name, $classMetadata->discriminatorMap, true) + ) { return true; } @@ -211,7 +204,6 @@ private function getColumnAlias($columnName, $mode, array $customRenameColumns) case self::COLUMN_RENAMING_NONE: return $columnName; - } } @@ -244,7 +236,7 @@ private function getColumnAliasMap($className, $mode, array $customRenameColumns foreach ($class->associationMappings as $associationMapping) { if ($associationMapping['isOwningSide'] && $associationMapping['type'] & ClassMetadataInfo::TO_ONE) { foreach ($associationMapping['joinColumns'] as $joinColumn) { - $columnName = $joinColumn['name']; + $columnName = $joinColumn['name']; $columnAlias[$columnName] = $this->getColumnAlias($columnName, $mode, $customRenameColumns); } } @@ -256,8 +248,7 @@ private function getColumnAliasMap($className, $mode, array $customRenameColumns /** * Adds the mappings of the results of native SQL queries to the result set. * - * @param ClassMetadataInfo $class - * @param array $queryMapping + * @param array $queryMapping * * @return ResultSetMappingBuilder */ @@ -273,16 +264,15 @@ public function addNamedNativeQueryMapping(ClassMetadataInfo $class, array $quer /** * Adds the class mapping of the results of native SQL queries to the result set. * - * @param ClassMetadataInfo $class - * @param string $resultClassName + * @param string $resultClassName * * @return self */ public function addNamedNativeQueryResultClassMapping(ClassMetadataInfo $class, $resultClassName) { - $classMetadata = $this->em->getClassMetadata($resultClassName); - $shortName = $classMetadata->reflClass->getShortName(); - $alias = strtolower($shortName[0]).'0'; + $classMetadata = $this->em->getClassMetadata($resultClassName); + $shortName = $classMetadata->reflClass->getShortName(); + $alias = strtolower($shortName[0]) . '0'; $this->addEntityResult($class->name, $alias); @@ -304,8 +294,8 @@ public function addNamedNativeQueryResultClassMapping(ClassMetadataInfo $class, $targetClass = $this->em->getClassMetadata($associationMapping['targetEntity']); foreach ($associationMapping['joinColumns'] as $joinColumn) { - $columnName = $joinColumn['name']; - $columnType = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em); + $columnName = $joinColumn['name']; + $columnType = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em); $this->addMetaResult($alias, $columnName, $columnName, $classMetadata->isIdentifier($columnName), $columnType); } @@ -318,30 +308,28 @@ public function addNamedNativeQueryResultClassMapping(ClassMetadataInfo $class, /** * Adds the result set mapping of the results of native SQL queries to the result set. * - * @param ClassMetadataInfo $class - * @param string $resultSetMappingName + * @param string $resultSetMappingName * * @return self */ public function addNamedNativeQueryResultSetMapping(ClassMetadataInfo $class, $resultSetMappingName) { - $counter = 0; - $resultMapping = $class->getSqlResultSetMapping($resultSetMappingName); - $rootShortName = $class->reflClass->getShortName(); - $rootAlias = strtolower($rootShortName[0]) . $counter; - + $counter = 0; + $resultMapping = $class->getSqlResultSetMapping($resultSetMappingName); + $rootShortName = $class->reflClass->getShortName(); + $rootAlias = strtolower($rootShortName[0]) . $counter; if (isset($resultMapping['entities'])) { foreach ($resultMapping['entities'] as $key => $entityMapping) { - $classMetadata = $this->em->getClassMetadata($entityMapping['entityClass']); + $classMetadata = $this->em->getClassMetadata($entityMapping['entityClass']); - if ($class->reflClass->name == $classMetadata->reflClass->name) { + if ($class->reflClass->name === $classMetadata->reflClass->name) { $this->addEntityResult($classMetadata->name, $rootAlias); $this->addNamedNativeQueryEntityResultMapping($classMetadata, $entityMapping, $rootAlias); } else { - $shortName = $classMetadata->reflClass->getShortName(); - $joinAlias = strtolower($shortName[0]) . ++ $counter; - $associations = $class->getAssociationsByTargetClass($classMetadata->name); + $shortName = $classMetadata->reflClass->getShortName(); + $joinAlias = strtolower($shortName[0]) . ++$counter; + $associations = $class->getAssociationsByTargetClass($classMetadata->name); $this->addNamedNativeQueryEntityResultMapping($classMetadata, $entityMapping, $joinAlias); @@ -349,7 +337,6 @@ public function addNamedNativeQueryResultSetMapping(ClassMetadataInfo $class, $r $this->addJoinedEntityResult($mapping['targetEntity'], $joinAlias, $rootAlias, $relation); } } - } } @@ -369,14 +356,13 @@ 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 array $entityMapping + * @param string $alias * * @return self * * @throws MappingException - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public function addNamedNativeQueryEntityResultMapping(ClassMetadataInfo $classMetadata, array $entityMapping, $alias) { @@ -388,7 +374,7 @@ public function addNamedNativeQueryEntityResultMapping(ClassMetadataInfo $classM $this->addMetaResult($alias, $discriminatorColumn, $discriminatorColumn, false, $discriminatorType); } - if (isset($entityMapping['fields']) && !empty($entityMapping['fields'])) { + if (isset($entityMapping['fields']) && ! empty($entityMapping['fields'])) { foreach ($entityMapping['fields'] as $field) { $fieldName = $field['name']; $relation = null; @@ -400,7 +386,7 @@ public function addNamedNativeQueryEntityResultMapping(ClassMetadataInfo $classM if (isset($classMetadata->associationMappings[$relation])) { if ($relation) { $associationMapping = $classMetadata->associationMappings[$relation]; - $joinAlias = $alias.$relation; + $joinAlias = $alias . $relation; $parentAlias = $alias; $this->addJoinedEntityResult($associationMapping['targetEntity'], $joinAlias, $parentAlias, $relation); @@ -409,14 +395,13 @@ public function addNamedNativeQueryEntityResultMapping(ClassMetadataInfo $classM $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 (! isset($classMetadata->fieldMappings[$fieldName])) { + throw new InvalidArgumentException("Entity '" . $classMetadata->name . "' has no field '" . $fieldName . "'. "); } $this->addFieldResult($alias, $field['column'], $fieldName, $classMetadata->name); } } - } else { foreach ($classMetadata->getColumnNames() as $columnName) { $propertyName = $classMetadata->getFieldName($columnName); @@ -440,27 +425,27 @@ public function addNamedNativeQueryEntityResultMapping(ClassMetadataInfo $classM */ public function generateSelectClause($tableAliases = []) { - $sql = ""; + $sql = ''; foreach ($this->columnOwnerMap as $columnName => $dqlAlias) { $tableAlias = $tableAliases[$dqlAlias] ?? $dqlAlias; if ($sql) { - $sql .= ", "; + $sql .= ', '; } - $sql .= $tableAlias . "."; + $sql .= $tableAlias . '.'; if (isset($this->fieldMappings[$columnName])) { $class = $this->em->getClassMetadata($this->declaringClasses[$columnName]); $sql .= $class->fieldMappings[$this->fieldMappings[$columnName]]['columnName']; - } else if (isset($this->metaMappings[$columnName])) { + } elseif (isset($this->metaMappings[$columnName])) { $sql .= $this->metaMappings[$columnName]; - } else if (isset($this->discriminatorColumns[$dqlAlias])) { + } elseif (isset($this->discriminatorColumns[$dqlAlias])) { $sql .= $this->discriminatorColumns[$dqlAlias]; } - $sql .= " AS " . $columnName; + $sql .= ' AS ' . $columnName; } return $sql; diff --git a/lib/Doctrine/ORM/Query/SqlWalker.php b/lib/Doctrine/ORM/Query/SqlWalker.php index 4a15b2c9b39..2de1d5c2b6d 100644 --- a/lib/Doctrine/ORM/Query/SqlWalker.php +++ b/lib/Doctrine/ORM/Query/SqlWalker.php @@ -1,4 +1,5 @@ - * @author Roman Borschel - * @author Benjamin Eberlei - * @author Alexander - * @author Fabio B. Silva - * @since 2.0 */ class SqlWalker implements TreeWalker { - /** - * @var string - */ - const HINT_DISTINCT = 'doctrine.distinct'; + public const HINT_DISTINCT = 'doctrine.distinct'; /** * Used to mark a query as containing a PARTIAL expression, which needs to be known by SLC. */ public const HINT_PARTIAL = 'doctrine.partial'; - /** - * @var ResultSetMapping - */ + /** @var ResultSetMapping */ private $rsm; /** * Counter for generating unique column aliases. * - * @var integer + * @var int */ private $aliasCounter = 0; /** * Counter for generating unique table aliases. * - * @var integer + * @var int */ private $tableAliasCounter = 0; /** * Counter for generating unique scalar result. * - * @var integer + * @var int */ private $scalarResultCounter = 1; /** * Counter for generating unique parameter indexes. * - * @var integer + * @var int */ private $sqlParamIndex = 0; /** * Counter for generating indexes. * - * @var integer + * @var int */ private $newObjectCounter = 0; - /** - * @var ParserResult - */ + /** @var ParserResult */ private $parserResult; - /** - * @var \Doctrine\ORM\EntityManager - */ + /** @var EntityManager */ private $em; - /** - * @var \Doctrine\DBAL\Connection - */ + /** @var Connection */ private $conn; - /** - * @var Query - */ + /** @var Query */ private $query; - /** - * @var array - */ + /** @var array */ private $tableAliasMap = []; /** @@ -142,7 +144,6 @@ class SqlWalker implements TreeWalker * Map of all components/classes that appear in the DQL query. * * @var array - * * @psalm-var array */ private $queryComponents; @@ -165,21 +166,21 @@ class SqlWalker implements TreeWalker * Flag that indicates whether to generate SQL table aliases in the SQL. * These should only be generated for SELECT queries, not for UPDATE/DELETE. * - * @var boolean + * @var bool */ private $useSqlTableAliases = true; /** * The database platform abstraction. * - * @var \Doctrine\DBAL\Platforms\AbstractPlatform + * @var AbstractPlatform */ private $platform; /** * The quote strategy. * - * @var \Doctrine\ORM\Mapping\QuoteStrategy + * @var QuoteStrategy */ private $quoteStrategy; @@ -188,14 +189,14 @@ class SqlWalker implements TreeWalker */ public function __construct($query, $parserResult, array $queryComponents) { - $this->query = $query; - $this->parserResult = $parserResult; - $this->queryComponents = $queryComponents; - $this->rsm = $parserResult->getResultSetMapping(); - $this->em = $query->getEntityManager(); - $this->conn = $this->em->getConnection(); - $this->platform = $this->conn->getDatabasePlatform(); - $this->quoteStrategy = $this->em->getConfiguration()->getQuoteStrategy(); + $this->query = $query; + $this->parserResult = $parserResult; + $this->queryComponents = $queryComponents; + $this->rsm = $parserResult->getResultSetMapping(); + $this->em = $query->getEntityManager(); + $this->conn = $this->em->getConnection(); + $this->platform = $this->conn->getDatabasePlatform(); + $this->quoteStrategy = $this->em->getConfiguration()->getQuoteStrategy(); } /** @@ -211,7 +212,7 @@ public function getQuery() /** * Gets the Connection used by the walker. * - * @return \Doctrine\DBAL\Connection + * @return Connection */ public function getConnection() { @@ -221,7 +222,7 @@ public function getConnection() /** * Gets the EntityManager used by the walker. * - * @return \Doctrine\ORM\EntityManager + * @return EntityManager */ public function getEntityManager() { @@ -270,17 +271,17 @@ public function setQueryComponent($dqlAlias, array $queryComponent) public function getExecutor($AST) { switch (true) { - case ($AST instanceof AST\DeleteStatement): + case $AST instanceof AST\DeleteStatement: $primaryClass = $this->em->getClassMetadata($AST->deleteClause->abstractSchemaName); - return ($primaryClass->isInheritanceTypeJoined()) + return $primaryClass->isInheritanceTypeJoined() ? new Exec\MultiTableDeleteExecutor($AST, $this) : new Exec\SingleTableDeleteUpdateExecutor($AST, $this); - case ($AST instanceof AST\UpdateStatement): + case $AST instanceof AST\UpdateStatement: $primaryClass = $this->em->getClassMetadata($AST->updateClause->abstractSchemaName); - return ($primaryClass->isInheritanceTypeJoined()) + return $primaryClass->isInheritanceTypeJoined() ? new Exec\MultiTableUpdateExecutor($AST, $this) : new Exec\SingleTableDeleteUpdateExecutor($AST, $this); @@ -299,9 +300,9 @@ public function getExecutor($AST) */ public function getSQLTableAlias($tableName, $dqlAlias = '') { - $tableName .= ($dqlAlias) ? '@[' . $dqlAlias . ']' : ''; + $tableName .= $dqlAlias ? '@[' . $dqlAlias . ']' : ''; - if ( ! isset($this->tableAliasMap[$tableName])) { + if (! isset($this->tableAliasMap[$tableName])) { $this->tableAliasMap[$tableName] = (preg_match('/[a-z]/i', $tableName[0]) ? strtolower($tableName[0]) : 't') . $this->tableAliasCounter++ . '_'; } @@ -321,7 +322,7 @@ public function getSQLTableAlias($tableName, $dqlAlias = '') */ public function setSQLTableAlias($tableName, $alias, $dqlAlias = '') { - $tableName .= ($dqlAlias) ? '@[' . $dqlAlias . ']' : ''; + $tableName .= $dqlAlias ? '@[' . $dqlAlias . ']' : ''; $this->tableAliasMap[$tableName] = $alias; @@ -410,10 +411,10 @@ private function _generateOrderedCollectionOrderByItems() $orderedColumns = []; foreach ($this->selectedClasses as $selectedClass) { - $dqlAlias = $selectedClass['dqlAlias']; - $qComp = $this->queryComponents[$dqlAlias]; + $dqlAlias = $selectedClass['dqlAlias']; + $qComp = $this->queryComponents[$dqlAlias]; - if ( ! isset($qComp['relation']['orderBy'])) { + if (! isset($qComp['relation']['orderBy'])) { continue; } @@ -421,7 +422,7 @@ private function _generateOrderedCollectionOrderByItems() foreach ($qComp['relation']['orderBy'] as $fieldName => $orientation) { $columnName = $this->quoteStrategy->getColumnName($fieldName, $qComp['metadata'], $this->platform); - $tableName = ($qComp['metadata']->isInheritanceTypeJoined()) + $tableName = $qComp['metadata']->isInheritanceTypeJoined() ? $persister->getOwningTable($fieldName) : $qComp['metadata']->getTableName(); @@ -433,7 +434,7 @@ private function _generateOrderedCollectionOrderByItems() } $this->orderedColumnsMap[$orderedColumn] = $orientation; - $orderedColumns[] = $orderedColumn . ' ' . $orientation; + $orderedColumns[] = $orderedColumn . ' ' . $orientation; } } @@ -454,7 +455,9 @@ private function _generateDiscriminatorColumnConditionSQL(array $dqlAliases) foreach ($dqlAliases as $dqlAlias) { $class = $this->queryComponents[$dqlAlias]['metadata']; - if ( ! $class->isInheritanceTypeSingleTable()) continue; + if (! $class->isInheritanceTypeSingleTable()) { + continue; + } $conn = $this->em->getConnection(); $values = []; @@ -467,7 +470,7 @@ private function _generateDiscriminatorColumnConditionSQL(array $dqlAliases) $values[] = $conn->quote($this->em->getClassMetadata($subclassName)->discriminatorValue); } - $sqlTableAlias = ($this->useSqlTableAliases) + $sqlTableAlias = $this->useSqlTableAliases ? $this->getSQLTableAlias($class->getTableName(), $dqlAlias) . '.' : ''; @@ -476,7 +479,7 @@ private function _generateDiscriminatorColumnConditionSQL(array $dqlAliases) $sql = implode(' AND ', $sqlParts); - return (count($sqlParts) > 1) ? '(' . $sql . ')' : $sql; + return count($sqlParts) > 1 ? '(' . $sql . ')' : $sql; } /** @@ -489,11 +492,11 @@ private function _generateDiscriminatorColumnConditionSQL(array $dqlAliases) */ private function generateFilterConditionSQL(ClassMetadata $targetEntity, $targetTableAlias) { - if (!$this->em->hasFilters()) { + if (! $this->em->hasFilters()) { return ''; } - switch($targetEntity->inheritanceType) { + switch ($targetEntity->inheritanceType) { case ClassMetadata::INHERITANCE_TYPE_NONE: break; case ClassMetadata::INHERITANCE_TYPE_JOINED: @@ -502,6 +505,7 @@ private function generateFilterConditionSQL(ClassMetadata $targetEntity, $target if ($targetEntity->name !== $targetEntity->rootEntityName) { return ''; } + break; case ClassMetadata::INHERITANCE_TYPE_SINGLE_TABLE: // With STI the table will only be queried once, make sure that the filters @@ -547,7 +551,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; } @@ -572,7 +576,7 @@ public function walkSelectStatement(AST\SelectStatement $AST) } foreach ($this->selectedClasses as $selectedClass) { - if ( ! $selectedClass['class']->isVersioned) { + if (! $selectedClass['class']->isVersioned) { throw OptimisticLockException::lockFailed($selectedClass['class']->name); } } @@ -654,12 +658,12 @@ public function walkPathExpression($pathExpr) { $sql = ''; - /* @var $pathExpr Query\AST\PathExpression */ + /** @var Query\AST\PathExpression $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']; if ($this->useSqlTableAliases) { $sql .= $this->walkIdentificationVariable($dqlAlias, $fieldName) . '.'; @@ -672,8 +676,8 @@ public function walkPathExpression($pathExpr) // 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']; + $dqlAlias = $pathExpr->identificationVariable; + $class = $this->queryComponents[$dqlAlias]['metadata']; if (isset($class->associationMappings[$fieldName]['inherited'])) { $class = $this->em->getClassMetadata($class->associationMappings[$fieldName]['inherited']); @@ -681,7 +685,7 @@ public function walkPathExpression($pathExpr) $assoc = $class->associationMappings[$fieldName]; - if ( ! $assoc['isOwningSide']) { + if (! $assoc['isOwningSide']) { throw QueryException::associationPathInverseSideNotSupported($pathExpr); } @@ -709,17 +713,17 @@ public function walkPathExpression($pathExpr) */ public function walkSelectClause($selectClause) { - $sql = 'SELECT ' . (($selectClause->isDistinct) ? 'DISTINCT ' : ''); + $sql = 'SELECT ' . ($selectClause->isDistinct ? 'DISTINCT ' : ''); $sqlSelectExpressions = array_filter(array_map([$this, 'walkSelectExpression'], $selectClause->selectExpressions)); - if ($this->query->getHint(Query::HINT_INTERNAL_ITERATION) == true && $selectClause->isDistinct) { + if ($this->query->getHint(Query::HINT_INTERNAL_ITERATION) === true && $selectClause->isDistinct) { $this->query->setHint(self::HINT_DISTINCT, true); } $addMetaColumns = ! $this->query->getHint(Query::HINT_FORCE_PARTIAL_LOAD) && - $this->query->getHydrationMode() == Query::HYDRATE_OBJECT + $this->query->getHydrationMode() === Query::HYDRATE_OBJECT || - $this->query->getHydrationMode() != Query::HYDRATE_OBJECT && + $this->query->getHydrationMode() !== Query::HYDRATE_OBJECT && $this->query->getHint(Query::HINT_INCLUDE_META_COLUMNS); foreach ($this->selectedClasses as $selectedClass) { @@ -753,20 +757,22 @@ public function walkSelectClause($selectClause) } // Add foreign key columns to SQL, if necessary - if ( ! $addMetaColumns && ! $class->containsForeignIdentifier) { + if (! $addMetaColumns && ! $class->containsForeignIdentifier) { continue; } // Add foreign key columns of class and also parent classes foreach ($class->associationMappings as $assoc) { - if ( ! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) - || ( ! $addMetaColumns && !isset($assoc['id']))) { + if ( + ! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) + || ( ! $addMetaColumns && ! isset($assoc['id'])) + ) { continue; } $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); $isIdentifier = (isset($assoc['id']) && $assoc['id'] === true); - $owningClass = (isset($assoc['inherited'])) ? $this->em->getClassMetadata($assoc['inherited']) : $class; + $owningClass = isset($assoc['inherited']) ? $this->em->getClassMetadata($assoc['inherited']) : $class; $sqlTableAlias = $this->getSQLTableAlias($owningClass->getTableName(), $dqlAlias); foreach ($assoc['joinColumns'] as $joinColumn) { @@ -782,7 +788,7 @@ public function walkSelectClause($selectClause) } // Add foreign key columns to SQL, if necessary - if ( ! $addMetaColumns) { + if (! $addMetaColumns) { continue; } @@ -793,7 +799,9 @@ public function walkSelectClause($selectClause) foreach ($subClass->associationMappings as $assoc) { // Skip if association is inherited - if (isset($assoc['inherited'])) continue; + if (isset($assoc['inherited'])) { + continue; + } if ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) { $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); @@ -813,9 +821,7 @@ public function walkSelectClause($selectClause) } } - $sql .= implode(', ', $sqlSelectExpressions); - - return $sql; + return $sql . implode(', ', $sqlSelectExpressions); } /** @@ -824,7 +830,7 @@ public function walkSelectClause($selectClause) public function walkFromClause($fromClause) { $identificationVarDecls = $fromClause->identificationVariableDeclarations; - $sqlParts = []; + $sqlParts = []; foreach ($identificationVarDecls as $identificationVariableDecl) { $sqlParts[] = $this->walkIdentificationVariableDeclaration($identificationVariableDecl); @@ -893,11 +899,8 @@ public function walkRangeVariableDeclaration($rangeVariableDeclaration) * Generate appropriate SQL for RangeVariableDeclaration AST node * * @param AST\RangeVariableDeclaration $rangeVariableDeclaration - * @param bool $buildNestedJoins - * - * @return string */ - private function generateRangeVariableDeclarationSQL($rangeVariableDeclaration, bool $buildNestedJoins) : string + private function generateRangeVariableDeclarationSQL($rangeVariableDeclaration, bool $buildNestedJoins): string { $class = $this->em->getClassMetadata($rangeVariableDeclaration->abstractSchemaName); $dqlAlias = $rangeVariableDeclaration->aliasIdentificationVariable; @@ -912,13 +915,13 @@ private function generateRangeVariableDeclarationSQL($rangeVariableDeclaration, $this->query->getHint(Query::HINT_LOCK_MODE) ); - if ( ! $class->isInheritanceTypeJoined()) { + if (! $class->isInheritanceTypeJoined()) { return $sql; } $classTableInheritanceJoins = $this->_generateClassTableInheritanceJoins($class, $dqlAlias); - if ( ! $buildNestedJoins) { + if (! $buildNestedJoins) { return $sql . $classTableInheritanceJoins; } @@ -953,10 +956,10 @@ public function walkJoinAssociationDeclaration($joinAssociationDeclaration, $joi $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; + $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) { + 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); } } @@ -967,7 +970,7 @@ public function walkJoinAssociationDeclaration($joinAssociationDeclaration, $joi // 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): + case $assoc['type'] & ClassMetadata::TO_ONE: $conditions = []; foreach ($assoc['joinColumns'] as $joinColumn) { @@ -1003,14 +1006,14 @@ public function walkJoinAssociationDeclaration($joinAssociationDeclaration, $joi ]; break; - case ($assoc['type'] == ClassMetadata::MANY_TO_MANY): + 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); $conditions = []; - $relationColumns = ($relation['isOwningSide']) + $relationColumns = $relation['isOwningSide'] ? $assoc['joinTable']['joinColumns'] : $assoc['joinTable']['inverseJoinColumns']; @@ -1024,10 +1027,10 @@ public function walkJoinAssociationDeclaration($joinAssociationDeclaration, $joi $sql .= $joinTableName . ' ' . $joinTableAlias . ' ON ' . implode(' AND ', $conditions); // Join target table - $sql .= ($joinType == AST\Join::JOIN_TYPE_LEFT || $joinType == AST\Join::JOIN_TYPE_LEFTOUTER) ? ' LEFT JOIN ' : ' INNER JOIN '; + $sql .= $joinType === AST\Join::JOIN_TYPE_LEFT || $joinType === AST\Join::JOIN_TYPE_LEFTOUTER ? ' LEFT JOIN ' : ' INNER JOIN '; $conditions = []; - $relationColumns = ($relation['isOwningSide']) + $relationColumns = $relation['isOwningSide'] ? $assoc['joinTable']['inverseJoinColumns'] : $assoc['joinTable']['joinColumns']; @@ -1059,11 +1062,11 @@ public function walkJoinAssociationDeclaration($joinAssociationDeclaration, $joi break; default: - throw new \BadMethodCallException('Type of association must be one of *_TO_ONE or MANY_TO_MANY'); + 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) . ')'); + $withCondition = $condExpr === null ? '' : ('(' . $this->walkConditionalExpression($condExpr) . ')'); if ($targetClass->isInheritanceTypeJoined()) { $ctiJoins = $this->_generateClassTableInheritanceJoins($targetClass, $joinedDqlAlias); @@ -1085,7 +1088,7 @@ 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'])) { + } elseif (isset($relation['indexBy'])) { $this->rsm->addIndexBy($joinedDqlAlias, $relation['indexBy']); } @@ -1121,7 +1124,7 @@ public function walkOrderByItem($orderByItem) { $type = strtoupper($orderByItem->type); $expr = $orderByItem->expression; - $sql = ($expr instanceof AST\Node) + $sql = $expr instanceof AST\Node ? $expr->dispatch($this) : $this->walkResultVariable($this->queryComponents[$expr]['token']['value']); @@ -1150,12 +1153,12 @@ public function walkJoin($join) $joinType = $join->joinType; $joinDeclaration = $join->joinAssociationDeclaration; - $sql = ($joinType == AST\Join::JOIN_TYPE_LEFT || $joinType == AST\Join::JOIN_TYPE_LEFTOUTER) + $sql = $joinType === AST\Join::JOIN_TYPE_LEFT || $joinType === AST\Join::JOIN_TYPE_LEFTOUTER ? ' LEFT JOIN ' : ' INNER JOIN '; switch (true) { - case ($joinDeclaration instanceof AST\RangeVariableDeclaration): + case $joinDeclaration instanceof AST\RangeVariableDeclaration: $class = $this->em->getClassMetadata($joinDeclaration->abstractSchemaName); $dqlAlias = $joinDeclaration->aliasIdentificationVariable; $tableAlias = $this->getSQLTableAlias($class->table['name'], $dqlAlias); @@ -1166,11 +1169,11 @@ public function walkJoin($join) } $isUnconditionalJoin = empty($conditions); - $condExprConjunction = ($class->isInheritanceTypeJoined() && $joinType != AST\Join::JOIN_TYPE_LEFT && $joinType != AST\Join::JOIN_TYPE_LEFTOUTER && $isUnconditionalJoin) + $condExprConjunction = $class->isInheritanceTypeJoined() && $joinType !== AST\Join::JOIN_TYPE_LEFT && $joinType !== AST\Join::JOIN_TYPE_LEFTOUTER && $isUnconditionalJoin ? ' AND ' : ' ON '; - $sql .= $this->generateRangeVariableDeclarationSQL($joinDeclaration, !$isUnconditionalJoin); + $sql .= $this->generateRangeVariableDeclarationSQL($joinDeclaration, ! $isUnconditionalJoin); // Apply remaining inheritance restrictions $discrSql = $this->_generateDiscriminatorColumnConditionSQL([$dqlAlias]); @@ -1192,7 +1195,7 @@ public function walkJoin($join) break; - case ($joinDeclaration instanceof AST\JoinAssociationDeclaration): + case $joinDeclaration instanceof AST\JoinAssociationDeclaration: $sql .= $this->walkJoinAssociationDeclaration($joinDeclaration, $joinType, $join->conditionalExpression); break; } @@ -1217,9 +1220,7 @@ public function walkCoalesceExpression($coalesceExpression) $scalarExpressions[] = $this->walkSimpleArithmeticExpression($scalarExpression); } - $sql .= implode(', ', $scalarExpressions) . ')'; - - return $sql; + return $sql . implode(', ', $scalarExpressions) . ')'; } /** @@ -1245,8 +1246,6 @@ public function walkNullIfExpression($nullIfExpression) /** * Walks down a GeneralCaseExpression AST node and generates the corresponding SQL. * - * @param AST\GeneralCaseExpression $generalCaseExpression - * * @return string The SQL. */ public function walkGeneralCaseExpression(AST\GeneralCaseExpression $generalCaseExpression) @@ -1294,7 +1293,7 @@ public function walkSelectExpression($selectExpression) $hidden = $selectExpression->hiddenAliasResultVariable; switch (true) { - case ($expr instanceof AST\PathExpression): + case $expr instanceof AST\PathExpression: if ($expr->type !== AST\PathExpression::TYPE_STATE_FIELD) { throw QueryException::invalidPathExpression($expr); } @@ -1305,7 +1304,7 @@ public function walkSelectExpression($selectExpression) $class = $qComp['metadata']; $resultAlias = $selectExpression->fieldIdentificationVariable ?: $fieldName; - $tableName = ($class->isInheritanceTypeJoined()) + $tableName = $class->isInheritanceTypeJoined() ? $this->em->getUnitOfWork()->getEntityPersister($class->name)->getOwningTable($fieldName) : $class->getTableName(); @@ -1324,24 +1323,24 @@ public function walkSelectExpression($selectExpression) $this->scalarResultAliasMap[$resultAlias] = $columnAlias; - if ( ! $hidden) { + if (! $hidden) { $this->rsm->addScalarResult($columnAlias, $resultAlias, $fieldMapping['type']); $this->scalarFields[$dqlAlias][$fieldName] = $columnAlias; } break; - case ($expr instanceof AST\AggregateExpression): - case ($expr instanceof AST\Functions\FunctionNode): - case ($expr instanceof AST\SimpleArithmeticExpression): - case ($expr instanceof AST\ArithmeticTerm): - case ($expr instanceof AST\ArithmeticFactor): - case ($expr instanceof AST\ParenthesisExpression): - case ($expr instanceof AST\Literal): - case ($expr instanceof AST\NullIfExpression): - case ($expr instanceof AST\CoalesceExpression): - case ($expr instanceof AST\GeneralCaseExpression): - case ($expr instanceof AST\SimpleCaseExpression): + case $expr instanceof AST\AggregateExpression: + case $expr instanceof AST\Functions\FunctionNode: + case $expr instanceof AST\SimpleArithmeticExpression: + case $expr instanceof AST\ArithmeticTerm: + case $expr instanceof AST\ArithmeticFactor: + case $expr instanceof AST\ParenthesisExpression: + case $expr instanceof AST\Literal: + case $expr instanceof AST\NullIfExpression: + case $expr instanceof AST\CoalesceExpression: + case $expr instanceof AST\GeneralCaseExpression: + case $expr instanceof AST\SimpleCaseExpression: $columnAlias = $this->getSQLColumnAlias('sclr'); $resultAlias = $selectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++; @@ -1365,7 +1364,7 @@ public function walkSelectExpression($selectExpression) break; - case ($expr instanceof AST\Subselect): + case $expr instanceof AST\Subselect: $columnAlias = $this->getSQLColumnAlias('sclr'); $resultAlias = $selectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++; @@ -1373,14 +1372,15 @@ public function walkSelectExpression($selectExpression) $this->scalarResultAliasMap[$resultAlias] = $columnAlias; - if ( ! $hidden) { + if (! $hidden) { // We cannot resolve field type here; assume 'string'. $this->rsm->addScalarResult($columnAlias, $resultAlias, 'string'); } + break; - case ($expr instanceof AST\NewObjectExpression): - $sql .= $this->walkNewObject($expr,$selectExpression->fieldIdentificationVariable); + case $expr instanceof AST\NewObjectExpression: + $sql .= $this->walkNewObject($expr, $selectExpression->fieldIdentificationVariable); break; default: @@ -1388,10 +1388,10 @@ public function walkSelectExpression($selectExpression) if ($expr instanceof AST\PartialObjectExpression) { $this->query->setHint(self::HINT_PARTIAL, true); - $dqlAlias = $expr->identificationVariable; + $dqlAlias = $expr->identificationVariable; $partialFieldSet = $expr->partialFieldSet; } else { - $dqlAlias = $expr; + $dqlAlias = $expr; $partialFieldSet = []; } @@ -1399,11 +1399,11 @@ public function walkSelectExpression($selectExpression) $class = $queryComp['metadata']; $resultAlias = $selectExpression->fieldIdentificationVariable ?: null; - if ( ! isset($this->selectedClasses[$dqlAlias])) { + if (! isset($this->selectedClasses[$dqlAlias])) { $this->selectedClasses[$dqlAlias] = [ 'class' => $class, 'dqlAlias' => $dqlAlias, - 'resultAlias' => $resultAlias + 'resultAlias' => $resultAlias, ]; } @@ -1415,7 +1415,7 @@ public function walkSelectExpression($selectExpression) continue; } - $tableName = (isset($mapping['inherited'])) + $tableName = isset($mapping['inherited']) ? $this->em->getClassMetadata($mapping['inherited'])->getTableName() : $class->getTableName(); @@ -1427,10 +1427,10 @@ public function walkSelectExpression($selectExpression) if (isset($mapping['requireSQLConversion'])) { $type = Type::getType($mapping['type']); - $col = $type->convertToPHPValueSQL($col, $this->platform); + $col = $type->convertToPHPValueSQL($col, $this->platform); } - $sqlParts[] = $col . ' AS '. $columnAlias; + $sqlParts[] = $col . ' AS ' . $columnAlias; $this->scalarResultAliasMap[$resultAlias][] = $columnAlias; @@ -1447,7 +1447,7 @@ public function walkSelectExpression($selectExpression) $sqlTableAlias = $this->getSQLTableAlias($subClass->getTableName(), $dqlAlias); foreach ($subClass->fieldMappings as $fieldName => $mapping) { - if (isset($mapping['inherited']) || ($partialFieldSet && !in_array($fieldName, $partialFieldSet))) { + if (isset($mapping['inherited']) || ($partialFieldSet && ! in_array($fieldName, $partialFieldSet))) { continue; } @@ -1458,7 +1458,7 @@ public function walkSelectExpression($selectExpression) if (isset($mapping['requireSQLConversion'])) { $type = Type::getType($mapping['type']); - $col = $type->convertToPHPValueSQL($col, $this->platform); + $col = $type->convertToPHPValueSQL($col, $this->platform); } $sqlParts[] = $col . ' AS ' . $columnAlias; @@ -1492,7 +1492,7 @@ public function walkSubselect($subselect) $useAliasesBefore = $this->useSqlTableAliases; $rootAliasesBefore = $this->rootAliases; - $this->rootAliases = []; // reset the rootAliases for the subselect + $this->rootAliases = []; // reset the rootAliases for the subselect $this->useSqlTableAliases = true; $sql = $this->walkSimpleSelectClause($subselect->simpleSelectClause); @@ -1534,8 +1534,6 @@ public function walkSimpleSelectClause($simpleSelectClause) } /** - * @param \Doctrine\ORM\Query\AST\ParenthesisExpression $parenthesisExpression - * * @return string */ public function walkParenthesisExpression(AST\ParenthesisExpression $parenthesisExpression) @@ -1544,14 +1542,15 @@ public function walkParenthesisExpression(AST\ParenthesisExpression $parenthesis } /** - * @param AST\NewObjectExpression $newObjectExpression - * @param null|string $newObjectResultAlias + * @param AST\NewObjectExpression $newObjectExpression + * @param string|null $newObjectResultAlias + * * @return string The SQL. */ - public function walkNewObject($newObjectExpression, $newObjectResultAlias=null) + public function walkNewObject($newObjectExpression, $newObjectResultAlias = null) { $sqlSelectExpressions = []; - $objIndex = $newObjectResultAlias?:$this->newObjectCounter++; + $objIndex = $newObjectResultAlias ?: $this->newObjectCounter++; foreach ($newObjectExpression->args as $argIndex => $e) { $resultAlias = $this->scalarResultCounter++; @@ -1559,15 +1558,15 @@ public function walkNewObject($newObjectExpression, $newObjectResultAlias=null) $fieldType = 'string'; switch (true) { - case ($e instanceof AST\NewObjectExpression): + case $e instanceof AST\NewObjectExpression: $sqlSelectExpressions[] = $e->dispatch($this); break; - case ($e instanceof AST\Subselect): + case $e instanceof AST\Subselect: $sqlSelectExpressions[] = '(' . $e->dispatch($this) . ') AS ' . $columnAlias; break; - case ($e instanceof AST\PathExpression): + case $e instanceof AST\PathExpression: $dqlAlias = $e->identificationVariable; $qComp = $this->queryComponents[$dqlAlias]; $class = $qComp['metadata']; @@ -1584,7 +1583,7 @@ public function walkNewObject($newObjectExpression, $newObjectResultAlias=null) $sqlSelectExpressions[] = $col . ' AS ' . $columnAlias; break; - case ($e instanceof AST\Literal): + case $e instanceof AST\Literal: switch ($e->type) { case AST\Literal::BOOLEAN: $fieldType = 'boolean'; @@ -1609,7 +1608,7 @@ public function walkNewObject($newObjectExpression, $newObjectResultAlias=null) $this->rsm->newObjectMappings[$columnAlias] = [ 'className' => $newObjectExpression->className, 'objIndex' => $objIndex, - 'argIndex' => $argIndex + 'argIndex' => $argIndex, ]; } @@ -1625,37 +1624,37 @@ public function walkSimpleSelectExpression($simpleSelectExpression) $sql = ' '; switch (true) { - case ($expr instanceof AST\PathExpression): + case $expr instanceof AST\PathExpression: $sql .= $this->walkPathExpression($expr); break; - case ($expr instanceof AST\Subselect): + case $expr instanceof AST\Subselect: $alias = $simpleSelectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++; - $columnAlias = 'sclr' . $this->aliasCounter++; + $columnAlias = 'sclr' . $this->aliasCounter++; $this->scalarResultAliasMap[$alias] = $columnAlias; $sql .= '(' . $this->walkSubselect($expr) . ') AS ' . $columnAlias; break; - case ($expr instanceof AST\Functions\FunctionNode): - case ($expr instanceof AST\SimpleArithmeticExpression): - case ($expr instanceof AST\ArithmeticTerm): - case ($expr instanceof AST\ArithmeticFactor): - case ($expr instanceof AST\Literal): - case ($expr instanceof AST\NullIfExpression): - case ($expr instanceof AST\CoalesceExpression): - case ($expr instanceof AST\GeneralCaseExpression): - case ($expr instanceof AST\SimpleCaseExpression): + case $expr instanceof AST\Functions\FunctionNode: + case $expr instanceof AST\SimpleArithmeticExpression: + case $expr instanceof AST\ArithmeticTerm: + case $expr instanceof AST\ArithmeticFactor: + case $expr instanceof AST\Literal: + case $expr instanceof AST\NullIfExpression: + case $expr instanceof AST\CoalesceExpression: + case $expr instanceof AST\GeneralCaseExpression: + case $expr instanceof AST\SimpleCaseExpression: $alias = $simpleSelectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++; - $columnAlias = $this->getSQLColumnAlias('sclr'); + $columnAlias = $this->getSQLColumnAlias('sclr'); $this->scalarResultAliasMap[$alias] = $columnAlias; $sql .= $expr->dispatch($this) . ' AS ' . $columnAlias; break; - case ($expr instanceof AST\ParenthesisExpression): + case $expr instanceof AST\ParenthesisExpression: $sql .= $this->walkParenthesisExpression($expr); break; @@ -1696,7 +1695,7 @@ public function walkGroupByClause($groupByClause) public function walkGroupByItem($groupByItem) { // StateFieldPathExpression - if ( ! is_string($groupByItem)) { + if (! is_string($groupByItem)) { return $this->walkPathExpression($groupByItem); } @@ -1764,9 +1763,7 @@ public function walkUpdateClause($updateClause) $this->setSQLTableAlias($tableName, $tableName, $updateClause->aliasIdentificationVariable); $this->rootAliases[] = $updateClause->aliasIdentificationVariable; - $sql .= ' SET ' . implode(', ', array_map([$this, 'walkUpdateItem'], $updateClause->updateItems)); - - return $sql; + return $sql . ' SET ' . implode(', ', array_map([$this, 'walkUpdateItem'], $updateClause->updateItems)); } /** @@ -1774,18 +1771,18 @@ public function walkUpdateClause($updateClause) */ public function walkUpdateItem($updateItem) { - $useTableAliasesBefore = $this->useSqlTableAliases; + $useTableAliasesBefore = $this->useSqlTableAliases; $this->useSqlTableAliases = false; $sql = $this->walkPathExpression($updateItem->pathExpression) . ' = '; $newValue = $updateItem->newValue; switch (true) { - case ($newValue instanceof AST\Node): + case $newValue instanceof AST\Node: $sql .= $newValue->dispatch($this); break; - case ($newValue === null): + case $newValue === null: $sql .= 'NULL'; break; @@ -1804,13 +1801,13 @@ public function walkUpdateItem($updateItem) */ public function walkWhereClause($whereClause) { - $condSql = null !== $whereClause ? $this->walkConditionalExpression($whereClause->conditionalExpression) : ''; + $condSql = $whereClause !== null ? $this->walkConditionalExpression($whereClause->conditionalExpression) : ''; $discrSql = $this->_generateDiscriminatorColumnConditionSQL($this->rootAliases); if ($this->em->hasFilters()) { $filterClauses = []; foreach ($this->rootAliases as $dqlAlias) { - $class = $this->queryComponents[$dqlAlias]['metadata']; + $class = $this->queryComponents[$dqlAlias]['metadata']; $tableAlias = $this->getSQLTableAlias($class->table['name'], $dqlAlias); if ($filterExpr = $this->generateFilterConditionSQL($class, $tableAlias)) { @@ -1828,7 +1825,7 @@ public function walkWhereClause($whereClause) } if ($condSql) { - return ' WHERE ' . (( ! $discrSql) ? $condSql : '(' . $condSql . ') AND ' . $discrSql); + return ' WHERE ' . (! $discrSql ? $condSql : '(' . $condSql . ') AND ' . $discrSql); } if ($discrSql) { @@ -1845,7 +1842,7 @@ public function walkConditionalExpression($condExpr) { // Phase 2 AST optimization: Skip processing of ConditionalExpression // if only one ConditionalTerm is defined - if ( ! ($condExpr instanceof AST\ConditionalExpression)) { + if (! ($condExpr instanceof AST\ConditionalExpression)) { return $this->walkConditionalTerm($condExpr); } @@ -1859,7 +1856,7 @@ public function walkConditionalTerm($condTerm) { // Phase 2 AST optimization: Skip processing of ConditionalTerm // if only one ConditionalFactor is defined - if ( ! ($condTerm instanceof AST\ConditionalTerm)) { + if (! ($condTerm instanceof AST\ConditionalTerm)) { return $this->walkConditionalFactor($condTerm); } @@ -1873,7 +1870,7 @@ public function walkConditionalFactor($factor) { // Phase 2 AST optimization: Skip processing of ConditionalFactor // if only one ConditionalPrimary is defined - return ( ! ($factor instanceof AST\ConditionalFactor)) + return ! ($factor instanceof AST\ConditionalFactor) ? $this->walkConditionalPrimary($factor) : ($factor->not ? 'NOT ' : '') . $this->walkConditionalPrimary($factor->conditionalPrimary); } @@ -1899,7 +1896,7 @@ public function walkConditionalPrimary($primary) */ public function walkExistsExpression($existsExpr) { - $sql = ($existsExpr->not) ? 'NOT ' : ''; + $sql = $existsExpr->not ? 'NOT ' : ''; $sql .= 'EXISTS (' . $this->walkSubselect($existsExpr->subselect) . ')'; @@ -1911,7 +1908,7 @@ public function walkExistsExpression($existsExpr) */ public function walkCollectionMemberExpression($collMemberExpr) { - $sql = $collMemberExpr->not ? 'NOT ' : ''; + $sql = $collMemberExpr->not ? 'NOT ' : ''; $sql .= 'EXISTS (SELECT 1 FROM '; $entityExpr = $collMemberExpr->entityExpression; @@ -1924,23 +1921,23 @@ public function walkCollectionMemberExpression($collMemberExpr) switch (true) { // InputParameter - case ($entityExpr instanceof AST\InputParameter): + case $entityExpr instanceof AST\InputParameter: $dqlParamKey = $entityExpr->name; $entitySql = '?'; break; // SingleValuedAssociationPathExpression | IdentificationVariable - case ($entityExpr instanceof AST\PathExpression): + case $entityExpr instanceof AST\PathExpression: $entitySql = $this->walkPathExpression($entityExpr); break; default: - throw new \BadMethodCallException("Not implemented"); + throw new BadMethodCallException('Not implemented'); } $assoc = $class->associationMappings[$fieldName]; - if ($assoc['type'] == ClassMetadata::ONE_TO_MANY) { + if ($assoc['type'] === ClassMetadata::ONE_TO_MANY) { $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); $targetTableAlias = $this->getSQLTableAlias($targetClass->getTableName()); $sourceTableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias); @@ -1961,7 +1958,7 @@ public function walkCollectionMemberExpression($collMemberExpr) $this->parserResult->addParameterMapping($dqlParamKey, $this->sqlParamIndex++); } - $sqlParts[] = $targetTableAlias . '.' . $targetColumnName . ' = ' . $entitySql; + $sqlParts[] = $targetTableAlias . '.' . $targetColumnName . ' = ' . $entitySql; } $sql .= implode(' AND ', $sqlParts); @@ -1969,7 +1966,7 @@ public function walkCollectionMemberExpression($collMemberExpr) $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); $owningAssoc = $assoc['isOwningSide'] ? $assoc : $targetClass->associationMappings[$assoc['mappedBy']]; - $joinTable = $owningAssoc['joinTable']; + $joinTable = $owningAssoc['joinTable']; // SQL table aliases $joinTableAlias = $this->getSQLTableAlias($joinTable['name']); @@ -2021,7 +2018,7 @@ public function walkCollectionMemberExpression($collMemberExpr) */ public function walkEmptyCollectionComparisonExpression($emptyCollCompExpr) { - $sizeFunc = new AST\Functions\SizeFunction('size'); + $sizeFunc = new AST\Functions\SizeFunction('size'); $sizeFunc->collectionPathExpression = $emptyCollCompExpr->expression; return $sizeFunc->getSql($this) . ($emptyCollCompExpr->not ? ' > 0' : ' = 0'); @@ -2055,7 +2052,7 @@ public function walkInExpression($inExpr) { $sql = $this->walkArithmeticExpression($inExpr->expression) . ($inExpr->not ? ' NOT' : '') . ' IN ('; - $sql .= ($inExpr->subselect) + $sql .= $inExpr->subselect ? $this->walkSubselect($inExpr->subselect) : implode(', ', array_map([$this, 'walkInParameter'], $inExpr->literals)); @@ -2066,13 +2063,14 @@ public function walkInExpression($inExpr) /** * {@inheritdoc} - * @throws \Doctrine\ORM\Query\QueryException + * + * @throws QueryException */ public function walkInstanceOfExpression($instanceOfExpr) { $sql = ''; - $dqlAlias = $instanceOfExpr->identificationVariable; + $dqlAlias = $instanceOfExpr->identificationVariable; $discrClass = $class = $this->queryComponents[$dqlAlias]['metadata']; if ($class->discriminatorColumn) { @@ -2111,7 +2109,7 @@ public function walkLiteral($literal) return $this->conn->quote($literal->value); case AST\Literal::BOOLEAN: - return $this->conn->getDatabasePlatform()->convertBooleans('true' === strtolower($literal->value)); + return $this->conn->getDatabasePlatform()->convertBooleans(strtolower($literal->value) === 'true'); case AST\Literal::NUMERIC: return $literal->value; @@ -2144,7 +2142,7 @@ public function walkBetweenExpression($betweenExpr) public function walkLikeExpression($likeExpr) { $stringExpr = $likeExpr->stringExpression; - $leftExpr = (is_string($stringExpr) && isset($this->queryComponents[$stringExpr]['resultVariable'])) + $leftExpr = is_string($stringExpr) && isset($this->queryComponents[$stringExpr]['resultVariable']) ? $this->walkResultVariable($stringExpr) : $stringExpr->dispatch($this); @@ -2184,13 +2182,13 @@ public function walkComparisonExpression($compExpr) $rightExpr = $compExpr->rightExpression; $sql = ''; - $sql .= ($leftExpr instanceof AST\Node) + $sql .= $leftExpr instanceof AST\Node ? $leftExpr->dispatch($this) : (is_numeric($leftExpr) ? $leftExpr : $this->conn->quote($leftExpr)); $sql .= ' ' . $compExpr->operator . ' '; - $sql .= ($rightExpr instanceof AST\Node) + $sql .= $rightExpr instanceof AST\Node ? $rightExpr->dispatch($this) : (is_numeric($rightExpr) ? $rightExpr : $this->conn->quote($rightExpr)); @@ -2218,7 +2216,7 @@ public function walkInputParameter($inputParam) */ public function walkArithmeticExpression($arithmeticExpr) { - return ($arithmeticExpr->isSimpleArithmeticExpression()) + return $arithmeticExpr->isSimpleArithmeticExpression() ? $this->walkSimpleArithmeticExpression($arithmeticExpr->simpleArithmeticExpression) : '(' . $this->walkSubselect($arithmeticExpr->subselect) . ')'; } @@ -2228,7 +2226,7 @@ public function walkArithmeticExpression($arithmeticExpr) */ public function walkSimpleArithmeticExpression($simpleArithmeticExpr) { - if ( ! ($simpleArithmeticExpr instanceof AST\SimpleArithmeticExpression)) { + if (! ($simpleArithmeticExpr instanceof AST\SimpleArithmeticExpression)) { return $this->walkArithmeticTerm($simpleArithmeticExpr); } @@ -2241,14 +2239,14 @@ public function walkSimpleArithmeticExpression($simpleArithmeticExpr) public function walkArithmeticTerm($term) { if (is_string($term)) { - return (isset($this->queryComponents[$term])) + return isset($this->queryComponents[$term]) ? $this->walkResultVariable($this->queryComponents[$term]['token']['value']) : $term; } // Phase 2 AST optimization: Skip processing of ArithmeticTerm // if only one ArithmeticFactor is defined - if ( ! ($term instanceof AST\ArithmeticTerm)) { + if (! ($term instanceof AST\ArithmeticTerm)) { return $this->walkArithmeticFactor($term); } @@ -2261,14 +2259,14 @@ public function walkArithmeticTerm($term) public function walkArithmeticFactor($factor) { if (is_string($factor)) { - return (isset($this->queryComponents[$factor])) + return isset($this->queryComponents[$factor]) ? $this->walkResultVariable($this->queryComponents[$factor]['token']['value']) : $factor; } // Phase 2 AST optimization: Skip processing of ArithmeticFactor // if only one ArithmeticPrimary is defined - if ( ! ($factor instanceof AST\ArithmeticFactor)) { + if (! ($factor instanceof AST\ArithmeticFactor)) { return $this->walkArithmeticPrimary($factor); } @@ -2302,7 +2300,7 @@ public function walkArithmeticPrimary($primary) */ public function walkStringPrimary($stringPrimary) { - return (is_string($stringPrimary)) + return is_string($stringPrimary) ? $this->conn->quote($stringPrimary) : $stringPrimary->dispatch($this); } @@ -2322,19 +2320,18 @@ public function walkResultVariable($resultVariable) } /** - * @param ClassMetadataInfo $rootClass - * @param AST\InstanceOfExpression $instanceOfExpr * @return string The list in parentheses of valid child discriminators from the given class + * * @throws QueryException */ private function getChildDiscriminatorsFromClassMetadata(ClassMetadataInfo $rootClass, AST\InstanceOfExpression $instanceOfExpr): string { $sqlParameterList = []; - $discriminators = []; + $discriminators = []; foreach ($instanceOfExpr->value as $parameter) { if ($parameter instanceof AST\InputParameter) { $this->rsm->discriminatorParameters[$parameter->name] = $parameter->name; - $sqlParameterList[] = $this->walkInParameter($parameter); + $sqlParameterList[] = $this->walkInParameter($parameter); continue; } diff --git a/lib/Doctrine/ORM/Query/TreeWalker.php b/lib/Doctrine/ORM/Query/TreeWalker.php index 9ddd86b0432..7e66e79e445 100644 --- a/lib/Doctrine/ORM/Query/TreeWalker.php +++ b/lib/Doctrine/ORM/Query/TreeWalker.php @@ -1,4 +1,5 @@ - * @since 2.0 */ interface TreeWalker { /** * Initializes TreeWalker with important information about the ASTs to be walked. * - * @param \Doctrine\ORM\AbstractQuery $query The parsed Query. - * @param \Doctrine\ORM\Query\ParserResult $parserResult The result of the parsing process. - * @param array $queryComponents The query components (symbol table). + * @param AbstractQuery $query The parsed Query. + * @param ParserResult $parserResult The result of the parsing process. + * @param array $queryComponents The query components (symbol table). */ public function __construct($query, $parserResult, array $queryComponents); @@ -56,8 +56,6 @@ public function setQueryComponent($dqlAlias, array $queryComponent); /** * Walks down a SelectStatement AST node, thereby generating the appropriate SQL. * - * @param AST\SelectStatement $AST - * * @return string The SQL. */ function walkSelectStatement(AST\SelectStatement $AST); @@ -209,8 +207,6 @@ function walkGroupByItem($groupByItem); /** * Walks down an UpdateStatement AST node, thereby generating the appropriate SQL. * - * @param AST\UpdateStatement $AST - * * @return string The SQL. */ function walkUpdateStatement(AST\UpdateStatement $AST); @@ -218,8 +214,6 @@ function walkUpdateStatement(AST\UpdateStatement $AST); /** * Walks down a DeleteStatement AST node, thereby generating the appropriate SQL. * - * @param AST\DeleteStatement $AST - * * @return string The SQL. */ function walkDeleteStatement(AST\DeleteStatement $AST); @@ -227,8 +221,6 @@ function walkDeleteStatement(AST\DeleteStatement $AST); /** * Walks down a DeleteClause AST node, thereby generating the appropriate SQL. * - * @param AST\DeleteClause $deleteClause - * * @return string The SQL. */ function walkDeleteClause(AST\DeleteClause $deleteClause); diff --git a/lib/Doctrine/ORM/Query/TreeWalkerAdapter.php b/lib/Doctrine/ORM/Query/TreeWalkerAdapter.php index 99c99973b76..7fb9e859998 100644 --- a/lib/Doctrine/ORM/Query/TreeWalkerAdapter.php +++ b/lib/Doctrine/ORM/Query/TreeWalkerAdapter.php @@ -1,4 +1,5 @@ - * @since 2.0 */ abstract class TreeWalkerAdapter implements TreeWalker { /** * The original Query. * - * @var \Doctrine\ORM\AbstractQuery + * @var AbstractQuery */ private $_query; /** * The ParserResult of the original query that was produced by the Parser. * - * @var \Doctrine\ORM\Query\ParserResult + * @var ParserResult */ private $_parserResult; @@ -54,8 +57,8 @@ abstract class TreeWalkerAdapter implements TreeWalker */ public function __construct($query, $parserResult, array $queryComponents) { - $this->_query = $query; - $this->_parserResult = $parserResult; + $this->_query = $query; + $this->_parserResult = $parserResult; $this->_queryComponents = $queryComponents; } @@ -92,7 +95,7 @@ protected function _getQueryComponents() /** * Retrieves the Query Instance responsible for the current walkers execution. * - * @return \Doctrine\ORM\AbstractQuery + * @return AbstractQuery */ protected function _getQuery() { @@ -102,7 +105,7 @@ protected function _getQuery() /** * Retrieves the ParserResult. * - * @return \Doctrine\ORM\Query\ParserResult + * @return ParserResult */ protected function _getParserResult() { diff --git a/lib/Doctrine/ORM/Query/TreeWalkerChain.php b/lib/Doctrine/ORM/Query/TreeWalkerChain.php index 5118d92d445..bc669ad306e 100644 --- a/lib/Doctrine/ORM/Query/TreeWalkerChain.php +++ b/lib/Doctrine/ORM/Query/TreeWalkerChain.php @@ -1,4 +1,5 @@ - * @since 2.0 */ class TreeWalkerChain implements TreeWalker { @@ -40,14 +43,14 @@ class TreeWalkerChain implements TreeWalker /** * The original Query. * - * @var \Doctrine\ORM\AbstractQuery + * @var AbstractQuery */ private $_query; /** * The ParserResult of the original query that was produced by the Parser. * - * @var \Doctrine\ORM\Query\ParserResult + * @var ParserResult */ private $_parserResult; @@ -89,10 +92,10 @@ public function setQueryComponent($dqlAlias, array $queryComponent) */ public function __construct($query, $parserResult, array $queryComponents) { - $this->_query = $query; - $this->_parserResult = $parserResult; + $this->_query = $query; + $this->_parserResult = $parserResult; $this->_queryComponents = $queryComponents; - $this->_walkers = new TreeWalkerChainIterator($this, $query, $parserResult); + $this->_walkers = new TreeWalkerChainIterator($this, $query, $parserResult); } /** diff --git a/lib/Doctrine/ORM/Query/TreeWalkerChainIterator.php b/lib/Doctrine/ORM/Query/TreeWalkerChainIterator.php index 955eb721008..82079c378f9 100644 --- a/lib/Doctrine/ORM/Query/TreeWalkerChainIterator.php +++ b/lib/Doctrine/ORM/Query/TreeWalkerChainIterator.php @@ -1,4 +1,5 @@ - * @template-implements \ArrayAccess + * @template-implements Iterator + * @template-implements ArrayAccess */ -class TreeWalkerChainIterator implements \Iterator, \ArrayAccess +class TreeWalkerChainIterator implements Iterator, ArrayAccess { - /** - * @var class-string[] - */ + /** @var class-string[] */ private $walkers = []; - /** - * @var TreeWalkerChain - */ + /** @var TreeWalkerChain */ private $treeWalkerChain; - /** - * @var AbstractQuery - */ + /** @var AbstractQuery */ private $query; - /** - * @var ParserResult - */ + /** @var ParserResult */ private $parserResult; /** @@ -51,8 +50,8 @@ class TreeWalkerChainIterator implements \Iterator, \ArrayAccess public function __construct(TreeWalkerChain $treeWalkerChain, $query, $parserResult) { $this->treeWalkerChain = $treeWalkerChain; - $this->query = $query; - $this->parserResult = $parserResult; + $this->query = $query; + $this->parserResult = $parserResult; } /** @@ -128,7 +127,7 @@ public function offsetGet($offset) */ public function offsetSet($offset, $value) { - if (null === $offset) { + if ($offset === null) { $this->walkers[] = $value; } else { $this->walkers[$offset] = $value; diff --git a/lib/Doctrine/ORM/QueryBuilder.php b/lib/Doctrine/ORM/QueryBuilder.php index f590f4d5ebb..4e1d50b4f0f 100644 --- a/lib/Doctrine/ORM/QueryBuilder.php +++ b/lib/Doctrine/ORM/QueryBuilder.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class QueryBuilder { /* The query types. */ - const SELECT = 0; - const DELETE = 1; - const UPDATE = 2; + public const SELECT = 0; + public const DELETE = 1; + public const UPDATE = 2; /* The builder states. */ - const STATE_DIRTY = 0; - const STATE_CLEAN = 1; + public const STATE_DIRTY = 0; + public const STATE_CLEAN = 1; /** * The EntityManager used by this QueryBuilder. @@ -66,20 +82,20 @@ class QueryBuilder 'where' => null, 'groupBy' => [], 'having' => null, - 'orderBy' => [] + 'orderBy' => [], ]; /** * The type of query this is. Can be select, update or delete. * - * @var integer + * @var int */ private $_type = self::SELECT; /** * The state of the query object. Can be dirty or clean. * - * @var integer + * @var int */ private $_state = self::STATE_CLEAN; @@ -93,7 +109,7 @@ class QueryBuilder /** * The query parameters. * - * @var \Doctrine\Common\Collections\ArrayCollection + * @var ArrayCollection */ private $parameters; @@ -107,7 +123,7 @@ class QueryBuilder /** * The maximum number of results to retrieve. * - * @var integer|null + * @var int|null */ private $_maxResults = null; @@ -119,10 +135,10 @@ class QueryBuilder private $joinRootAliases = []; /** - * Whether to use second level cache, if available. - * - * @var boolean - */ + * Whether to use second level cache, if available. + * + * @var bool + */ protected $cacheable = false; /** @@ -135,13 +151,11 @@ class QueryBuilder /** * Second level query cache mode. * - * @var integer|null + * @var int|null */ protected $cacheMode; - /** - * @var integer - */ + /** @var int */ protected $lifetime = 0; /** @@ -151,7 +165,7 @@ class QueryBuilder */ public function __construct(EntityManagerInterface $em) { - $this->_em = $em; + $this->_em = $em; $this->parameters = new ArrayCollection(); } @@ -178,22 +192,21 @@ public function expr() } /** - * * Enable/disable second level query (result) caching for this query. * - * @param boolean $cacheable + * @param bool $cacheable * * @return self */ public function setCacheable($cacheable) { - $this->cacheable = (boolean) $cacheable; + $this->cacheable = (bool) $cacheable; return $this; } /** - * @return boolean TRUE if the query results are enable for second level cache, FALSE otherwise. + * @return bool TRUE if the query results are enable for second level cache, FALSE otherwise. */ public function isCacheable() { @@ -213,17 +226,17 @@ public function setCacheRegion($cacheRegion) } /** - * Obtain the name of the second level query cache region in which query results will be stored - * - * @return string|null The cache region name; NULL indicates the default region. - */ + * Obtain the name of the second level query cache region in which query results will be stored + * + * @return string|null The cache region name; NULL indicates the default region. + */ public function getCacheRegion() { return $this->cacheRegion; } /** - * @return integer + * @return int */ public function getLifetime() { @@ -233,19 +246,19 @@ public function getLifetime() /** * Sets the life-time for this query into second level cache. * - * @param integer $lifetime + * @param int $lifetime * * @return self */ public function setLifetime($lifetime) { - $this->lifetime = (integer) $lifetime; + $this->lifetime = (int) $lifetime; return $this; } /** - * @return integer + * @return int */ public function getCacheMode() { @@ -253,13 +266,13 @@ public function getCacheMode() } /** - * @param integer $cacheMode + * @param int $cacheMode * * @return self */ public function setCacheMode($cacheMode) { - $this->cacheMode = (integer) $cacheMode; + $this->cacheMode = (int) $cacheMode; return $this; } @@ -267,7 +280,7 @@ public function setCacheMode($cacheMode) /** * Gets the type of the currently built query. * - * @return integer + * @return int */ public function getType() { @@ -287,7 +300,7 @@ public function getEntityManager() /** * Gets the state of this query builder instance. * - * @return integer Either QueryBuilder::STATE_DIRTY or QueryBuilder::STATE_CLEAN. + * @return int Either QueryBuilder::STATE_DIRTY or QueryBuilder::STATE_CLEAN. */ public function getState() { @@ -413,16 +426,17 @@ private function findRootAlias($alias, $parentAlias) * * * @deprecated Please use $qb->getRootAliases() instead. - * @throws \RuntimeException * * @return string + * + * @throws RuntimeException */ public function getRootAlias() { $aliases = $this->getRootAliases(); - if ( ! isset($aliases[0])) { - throw new \RuntimeException('No alias was set before invoking getRootAlias().'); + if (! isset($aliases[0])) { + throw new RuntimeException('No alias was set before invoking getRootAlias().'); } return $aliases[0]; @@ -531,9 +545,9 @@ public function getRootEntities() * ->setParameter('user_id', 1); * * - * @param string|integer $key The parameter position or name. - * @param mixed $value The parameter value. - * @param string|integer|null $type PDO::PARAM_* or \Doctrine\DBAL\Types\Type::* constant + * @param string|int $key The parameter position or name. + * @param mixed $value The parameter value. + * @param string|int|null $type PDO::PARAM_* or \Doctrine\DBAL\Types\Type::* constant * * @return self */ @@ -566,7 +580,7 @@ public function setParameter($key, $value, $type = null) * ))); * * - * @param \Doctrine\Common\Collections\ArrayCollection|array $parameters The query parameters to set. + * @param ArrayCollection|array $parameters The query parameters to set. * * @return self */ @@ -594,7 +608,7 @@ public function setParameters($parameters) /** * Gets all defined query parameters for the query being constructed. * - * @return \Doctrine\Common\Collections\ArrayCollection The currently defined query parameters. + * @return ArrayCollection The currently defined query parameters. */ public function getParameters() { @@ -613,7 +627,7 @@ public function getParameter($key) $key = Query\Parameter::normalizeName($key); $filteredParameters = $this->parameters->filter( - function (Query\Parameter $parameter) use ($key) : bool { + static function (Query\Parameter $parameter) use ($key): bool { $parameterName = $parameter->getName(); return $key === $parameterName; @@ -651,7 +665,7 @@ public function getFirstResult() /** * Sets the maximum number of results to retrieve (the "limit"). * - * @param integer|null $maxResults The maximum number of results to retrieve. + * @param int|null $maxResults The maximum number of results to retrieve. * * @return self */ @@ -666,7 +680,7 @@ public function setMaxResults($maxResults) * Gets the maximum number of results the query object was set to retrieve (the "limit"). * Returns NULL if {@link setMaxResults} was not applied to this query builder. * - * @return integer|null Maximum number of results. + * @return int|null Maximum number of results. */ public function getMaxResults() { @@ -687,24 +701,24 @@ public function getMaxResults() */ public function add($dqlPartName, $dqlPart, $append = false) { - if ($append && ($dqlPartName === "where" || $dqlPartName === "having")) { - throw new \InvalidArgumentException( - "Using \$append = true does not have an effect with 'where' or 'having' ". - "parts. See QueryBuilder#andWhere() for an example for correct usage." + if ($append && ($dqlPartName === 'where' || $dqlPartName === 'having')) { + throw new InvalidArgumentException( + "Using \$append = true does not have an effect with 'where' or 'having' " . + 'parts. See QueryBuilder#andWhere() for an example for correct usage.' ); } $isMultiple = is_array($this->_dqlParts[$dqlPartName]) - && !($dqlPartName == 'join' && !$append); + && ! ($dqlPartName === 'join' && ! $append); // Allow adding any part retrieved from self::getDQLParts(). - if (is_array($dqlPart) && $dqlPartName != 'join') { + if (is_array($dqlPart) && $dqlPartName !== 'join') { $dqlPart = reset($dqlPart); } // This is introduced for backwards compatibility reasons. // TODO: Remove for 3.0 - if ($dqlPartName == 'join') { + if ($dqlPartName === 'join') { $newDqlPart = []; foreach ($dqlPart as $k => $v) { @@ -725,7 +739,7 @@ public function add($dqlPartName, $dqlPart, $append = false) $this->_dqlParts[$dqlPartName][] = $dqlPart; } } else { - $this->_dqlParts[$dqlPartName] = ($isMultiple) ? [$dqlPart] : $dqlPart; + $this->_dqlParts[$dqlPartName] = $isMultiple ? [$dqlPart] : $dqlPart; } $this->_state = self::STATE_DIRTY; @@ -830,7 +844,7 @@ public function delete($delete = null, $alias = null) { $this->_type = self::DELETE; - if ( ! $delete) { + if (! $delete) { return $this; } @@ -857,7 +871,7 @@ public function update($update = null, $alias = null) { $this->_type = self::UPDATE; - if ( ! $update) { + if (! $update) { return $this; } @@ -912,14 +926,14 @@ public function indexBy($alias, $indexBy) { $rootAliases = $this->getRootAliases(); - if (!in_array($alias, $rootAliases)) { + if (! in_array($alias, $rootAliases)) { throw new Query\QueryException( sprintf('Specified root alias %s must be set before invoking indexBy().', $alias) ); } foreach ($this->_dqlParts['from'] as &$fromClause) { - /* @var Expr\From $fromClause */ + assert($fromClause instanceof Expr\From); if ($fromClause->getAlias() !== $alias) { continue; } @@ -985,7 +999,12 @@ public function innerJoin($join, $alias, $conditionType = null, $condition = nul $rootAlias = $this->findRootAlias($alias, $parentAlias); $join = new Expr\Join( - Expr\Join::INNER_JOIN, $join, $alias, $conditionType, $condition, $indexBy + Expr\Join::INNER_JOIN, + $join, + $alias, + $conditionType, + $condition, + $indexBy ); return $this->add('join', [$rootAlias => $join], true); @@ -1020,7 +1039,12 @@ public function leftJoin($join, $alias, $conditionType = null, $condition = null $rootAlias = $this->findRootAlias($alias, $parentAlias); $join = new Expr\Join( - Expr\Join::LEFT_JOIN, $join, $alias, $conditionType, $condition, $indexBy + Expr\Join::LEFT_JOIN, + $join, + $alias, + $conditionType, + $condition, + $indexBy ); return $this->add('join', [$rootAlias => $join], true); @@ -1074,7 +1098,7 @@ public function set($key, $value) */ public function where($predicates) { - if ( ! (func_num_args() == 1 && $predicates instanceof Expr\Composite)) { + if (! (func_num_args() === 1 && $predicates instanceof Expr\Composite)) { $predicates = new Expr\Andx(func_get_args()); } @@ -1093,11 +1117,11 @@ public function where($predicates) * ->andWhere('u.is_active = 1'); * * + * @see where() + * * @param mixed $where The query restrictions. * * @return self - * - * @see where() */ public function andWhere() { @@ -1126,11 +1150,11 @@ public function andWhere() * ->orWhere('u.id = 2'); * * + * @see where() + * * @param mixed $where The WHERE statement. * * @return self - * - * @see where() */ public function orWhere() { @@ -1197,7 +1221,7 @@ public function addGroupBy($groupBy) */ public function having($having) { - if ( ! (func_num_args() == 1 && ($having instanceof Expr\Andx || $having instanceof Expr\Orx))) { + if (! (func_num_args() === 1 && ($having instanceof Expr\Andx || $having instanceof Expr\Orx))) { $having = new Expr\Andx(func_get_args()); } @@ -1261,7 +1285,7 @@ public function orHaving($having) */ public function orderBy($sort, $order = null) { - $orderBy = ($sort instanceof Expr\OrderBy) ? $sort : new Expr\OrderBy($sort, $order); + $orderBy = $sort instanceof Expr\OrderBy ? $sort : new Expr\OrderBy($sort, $order); return $this->add('orderBy', $orderBy); } @@ -1276,7 +1300,7 @@ public function orderBy($sort, $order = null) */ public function addOrderBy($sort, $order = null) { - $orderBy = ($sort instanceof Expr\OrderBy) ? $sort : new Expr\OrderBy($sort, $order); + $orderBy = $sort instanceof Expr\OrderBy ? $sort : new Expr\OrderBy($sort, $order); return $this->add('orderBy', $orderBy, true); } @@ -1288,8 +1312,6 @@ public function addOrderBy($sort, $order = null) * Adds orderings. * Overrides firstResult and maxResults if they're set. * - * @param Criteria $criteria - * * @return self * * @throws Query\QueryException @@ -1297,7 +1319,7 @@ public function addOrderBy($sort, $order = null) public function addCriteria(Criteria $criteria) { $allAliases = $this->getAllAliases(); - if ( ! isset($allAliases[0])) { + if (! isset($allAliases[0])) { throw new Query\QueryException('No aliases are set before invoking addCriteria().'); } @@ -1312,16 +1334,15 @@ public function addCriteria(Criteria $criteria) if ($criteria->getOrderings()) { foreach ($criteria->getOrderings() as $sort => $order) { - $hasValidAlias = false; - foreach($allAliases as $alias) { - if(strpos($sort . '.', $alias . '.') === 0) { + foreach ($allAliases as $alias) { + if (strpos($sort . '.', $alias . '.') === 0) { $hasValidAlias = true; break; } } - if(!$hasValidAlias) { + if (! $hasValidAlias) { $sort = $allAliases[0] . '.' . $sort; } @@ -1333,6 +1354,7 @@ public function addCriteria(Criteria $criteria) if (($firstResult = $criteria->getFirstResult()) !== null) { $this->setFirstResult($firstResult); } + if (($maxResults = $criteria->getMaxResults()) !== null) { $this->setMaxResults($maxResults); } @@ -1391,7 +1413,7 @@ private function _getDQLForUpdate() private function _getDQLForSelect() { $dql = 'SELECT' - . ($this->_dqlParts['distinct']===true ? ' DISTINCT' : '') + . ($this->_dqlParts['distinct'] === true ? ' DISTINCT' : '') . $this->_getReducedDQLQueryPart('select', ['pre' => ' ', 'separator' => ', ']); $fromParts = $this->getDQLPart('from'); @@ -1399,7 +1421,7 @@ private function _getDQLForSelect() $fromClauses = []; // Loop through all FROM clauses - if ( ! empty($fromParts)) { + if (! empty($fromParts)) { $dql .= ' FROM '; foreach ($fromParts as $from) { @@ -1435,7 +1457,7 @@ private function _getReducedDQLQueryPart($queryPartName, $options = []) $queryPart = $this->getDQLPart($queryPartName); if (empty($queryPart)) { - return ($options['empty'] ?? ''); + return $options['empty'] ?? ''; } return ($options['pre'] ?? '') @@ -1452,7 +1474,7 @@ private function _getReducedDQLQueryPart($queryPartName, $options = []) */ public function resetDQLParts($parts = null) { - if (null === $parts) { + if ($parts === null) { $parts = array_keys($this->_dqlParts); } @@ -1503,7 +1525,7 @@ public function __clone() $this->_dqlParts[$part][$idx] = clone $element; } } - } else if (is_object($elements)) { + } elseif (is_object($elements)) { $this->_dqlParts[$part] = clone $elements; } } diff --git a/lib/Doctrine/ORM/Repository/DefaultRepositoryFactory.php b/lib/Doctrine/ORM/Repository/DefaultRepositoryFactory.php index ddd4c1a63b6..53a1b017cb1 100644 --- a/lib/Doctrine/ORM/Repository/DefaultRepositoryFactory.php +++ b/lib/Doctrine/ORM/Repository/DefaultRepositoryFactory.php @@ -1,4 +1,5 @@ - * @since 2.4 */ final class DefaultRepositoryFactory implements RepositoryFactory { @@ -54,8 +54,8 @@ public function getRepository(EntityManagerInterface $entityManager, $entityName /** * Create a new repository instance for an entity class. * - * @param \Doctrine\ORM\EntityManagerInterface $entityManager The EntityManager instance. - * @param string $entityName The name of the entity. + * @param EntityManagerInterface $entityManager The EntityManager instance. + * @param string $entityName The name of the entity. * * @return ObjectRepository */ diff --git a/lib/Doctrine/ORM/Repository/RepositoryFactory.php b/lib/Doctrine/ORM/Repository/RepositoryFactory.php index 29a928dd1f6..7c55a9900b5 100644 --- a/lib/Doctrine/ORM/Repository/RepositoryFactory.php +++ b/lib/Doctrine/ORM/Repository/RepositoryFactory.php @@ -1,4 +1,5 @@ - * @since 2.4 */ interface RepositoryFactory { /** * Gets the repository for an entity class. * - * @param \Doctrine\ORM\EntityManagerInterface $entityManager The EntityManager instance. - * @param string $entityName The name of the entity. + * @param EntityManagerInterface $entityManager The EntityManager instance. + * @param string $entityName The name of the entity. * * @return ObjectRepository */ diff --git a/lib/Doctrine/ORM/Tools/AttachEntityListenersListener.php b/lib/Doctrine/ORM/Tools/AttachEntityListenersListener.php index f05c52226dc..74e5a4cb804 100644 --- a/lib/Doctrine/ORM/Tools/AttachEntityListenersListener.php +++ b/lib/Doctrine/ORM/Tools/AttachEntityListenersListener.php @@ -1,4 +1,5 @@ - * - * @since 2.5 */ class AttachEntityListenersListener { - /** - * @var array[] - */ + /** @var array[] */ private $entityListeners = []; /** @@ -51,22 +47,20 @@ public function addEntityListener($entityClass, $listenerClass, $eventName, $lis $this->entityListeners[ltrim($entityClass, '\\')][] = [ 'event' => $eventName, 'class' => $listenerClass, - 'method' => $listenerCallback ?: $eventName + 'method' => $listenerCallback ?: $eventName, ]; } /** * Processes event and attach the entity listener. * - * @param \Doctrine\ORM\Event\LoadClassMetadataEventArgs $event - * * @return void */ public function loadClassMetadata(LoadClassMetadataEventArgs $event) { $metadata = $event->getClassMetadata(); - if ( ! isset($this->entityListeners[$metadata->name])) { + if (! isset($this->entityListeners[$metadata->name])) { return; } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/CollectionRegionCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/CollectionRegionCommand.php index 1c75ccccacc..07c37576317 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/CollectionRegionCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/CollectionRegionCommand.php @@ -1,4 +1,5 @@ */ class CollectionRegionCommand extends Command { @@ -82,25 +86,25 @@ protected function execute(InputInterface $input, OutputInterface $output) { $ui = new SymfonyStyle($input, $output); - $em = $this->getHelper('em')->getEntityManager(); - $ownerClass = $input->getArgument('owner-class'); - $assoc = $input->getArgument('association'); - $ownerId = $input->getArgument('owner-id'); - $cache = $em->getCache(); + $em = $this->getHelper('em')->getEntityManager(); + $ownerClass = $input->getArgument('owner-class'); + $assoc = $input->getArgument('association'); + $ownerId = $input->getArgument('owner-id'); + $cache = $em->getCache(); - if ( ! $cache instanceof Cache) { - throw new \InvalidArgumentException('No second-level cache is configured on the given EntityManager.'); + if (! $cache instanceof Cache) { + throw new InvalidArgumentException('No second-level cache is configured on the given EntityManager.'); } if (( ! $ownerClass || ! $assoc) && ! $input->getOption('all')) { - throw new \InvalidArgumentException('Missing arguments "--owner-class" "--association"'); + throw new InvalidArgumentException('Missing arguments "--owner-class" "--association"'); } if ($input->getOption('flush')) { - $collectionRegion = $cache->getCollectionCacheRegion($ownerClass, $assoc); + $collectionRegion = $cache->getCollectionCacheRegion($ownerClass, $assoc); - if ( ! $collectionRegion instanceof DefaultRegion) { - throw new \InvalidArgumentException(sprintf( + if (! $collectionRegion instanceof DefaultRegion) { + throw new InvalidArgumentException(sprintf( 'The option "--flush" expects a "Doctrine\ORM\Cache\Region\DefaultRegion", but got "%s".', is_object($collectionRegion) ? get_class($collectionRegion) : gettype($collectionRegion) )); diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/EntityRegionCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/EntityRegionCommand.php index c246910c145..d386638e58f 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/EntityRegionCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/EntityRegionCommand.php @@ -1,4 +1,5 @@ */ class EntityRegionCommand extends Command { @@ -86,19 +90,19 @@ protected function execute(InputInterface $input, OutputInterface $output) $entityId = $input->getArgument('entity-id'); $cache = $em->getCache(); - if ( ! $cache instanceof Cache) { - throw new \InvalidArgumentException('No second-level cache is configured on the given EntityManager.'); + if (! $cache instanceof Cache) { + throw new InvalidArgumentException('No second-level cache is configured on the given EntityManager.'); } - if ( ! $entityClass && ! $input->getOption('all')) { - throw new \InvalidArgumentException('Invalid argument "--entity-class"'); + if (! $entityClass && ! $input->getOption('all')) { + throw new InvalidArgumentException('Invalid argument "--entity-class"'); } if ($input->getOption('flush')) { - $entityRegion = $cache->getEntityCacheRegion($entityClass); + $entityRegion = $cache->getEntityCacheRegion($entityClass); - if ( ! $entityRegion instanceof DefaultRegion) { - throw new \InvalidArgumentException(sprintf( + if (! $entityRegion instanceof DefaultRegion) { + throw new InvalidArgumentException(sprintf( 'The option "--flush" expects a "Doctrine\ORM\Cache\Region\DefaultRegion", but got "%s".', is_object($entityRegion) ? get_class($entityRegion) : gettype($entityRegion) )); diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/MetadataCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/MetadataCommand.php index 56472662199..47984542608 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/MetadataCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/MetadataCommand.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class MetadataCommand extends Command { @@ -74,29 +72,29 @@ protected function execute(InputInterface $input, OutputInterface $output) { $ui = new SymfonyStyle($input, $output); - $em = $this->getHelper('em')->getEntityManager(); + $em = $this->getHelper('em')->getEntityManager(); $cacheDriver = $em->getConfiguration()->getMetadataCacheImpl(); - if ( ! $cacheDriver) { - throw new \InvalidArgumentException('No Metadata cache driver is configured on given EntityManager.'); + if (! $cacheDriver) { + throw new InvalidArgumentException('No Metadata cache driver is configured on given EntityManager.'); } if ($cacheDriver instanceof ApcCache) { - throw new \LogicException("Cannot clear APC Cache from Console, its shared in the Webserver memory and not accessible from the CLI."); + throw new LogicException('Cannot clear APC Cache from Console, its shared in the Webserver memory and not accessible from the CLI.'); } if ($cacheDriver instanceof XcacheCache) { - throw new \LogicException("Cannot clear XCache Cache from Console, its shared in the Webserver memory and not accessible from the CLI."); + throw new LogicException('Cannot clear XCache Cache from Console, its shared in the Webserver memory and not accessible from the CLI.'); } $ui->comment('Clearing all Metadata cache entries'); $result = $cacheDriver->deleteAll(); - $message = ($result) ? 'Successfully deleted cache entries.' : 'No cache entries were deleted.'; + $message = $result ? 'Successfully deleted cache entries.' : 'No cache entries were deleted.'; - if (true === $input->getOption('flush')) { + if ($input->getOption('flush') === true) { $result = $cacheDriver->flushAll(); - $message = ($result) ? 'Successfully flushed cache entries.' : $message; + $message = $result ? 'Successfully flushed cache entries.' : $message; } $ui->success($message); diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/QueryCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/QueryCommand.php index 5345091248e..7e500a2cd1d 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/QueryCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/QueryCommand.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class QueryCommand extends Command { @@ -74,28 +72,29 @@ protected function execute(InputInterface $input, OutputInterface $output) { $ui = new SymfonyStyle($input, $output); - $em = $this->getHelper('em')->getEntityManager(); + $em = $this->getHelper('em')->getEntityManager(); $cacheDriver = $em->getConfiguration()->getQueryCacheImpl(); - if ( ! $cacheDriver) { - throw new \InvalidArgumentException('No Query cache driver is configured on given EntityManager.'); + if (! $cacheDriver) { + throw new InvalidArgumentException('No Query cache driver is configured on given EntityManager.'); } if ($cacheDriver instanceof ApcCache) { - throw new \LogicException("Cannot clear APC Cache from Console, its shared in the Webserver memory and not accessible from the CLI."); + throw new LogicException('Cannot clear APC Cache from Console, its shared in the Webserver memory and not accessible from the CLI.'); } + if ($cacheDriver instanceof XcacheCache) { - throw new \LogicException("Cannot clear XCache Cache from Console, its shared in the Webserver memory and not accessible from the CLI."); + throw new LogicException('Cannot clear XCache Cache from Console, its shared in the Webserver memory and not accessible from the CLI.'); } $ui->comment('Clearing all Query cache entries'); $result = $cacheDriver->deleteAll(); - $message = ($result) ? 'Successfully deleted cache entries.' : 'No cache entries were deleted.'; + $message = $result ? 'Successfully deleted cache entries.' : 'No cache entries were deleted.'; - if (true === $input->getOption('flush')) { + if ($input->getOption('flush') === true) { $result = $cacheDriver->flushAll(); - $message = ($result) ? 'Successfully flushed cache entries.' : $message; + $message = $result ? 'Successfully flushed cache entries.' : $message; } $ui->success($message); diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/QueryRegionCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/QueryRegionCommand.php index 36ffa125038..4d18d684498 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/QueryRegionCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/QueryRegionCommand.php @@ -1,4 +1,5 @@ */ class QueryRegionCommand extends Command { @@ -88,16 +92,16 @@ protected function execute(InputInterface $input, OutputInterface $output) $name = Cache::DEFAULT_QUERY_REGION_NAME; } - if ( ! $cache instanceof Cache) { - throw new \InvalidArgumentException('No second-level cache is configured on the given EntityManager.'); + if (! $cache instanceof Cache) { + throw new InvalidArgumentException('No second-level cache is configured on the given EntityManager.'); } if ($input->getOption('flush')) { $queryCache = $cache->getQueryCache($name); $queryRegion = $queryCache->getRegion(); - if ( ! $queryRegion instanceof DefaultRegion) { - throw new \InvalidArgumentException(sprintf( + if (! $queryRegion instanceof DefaultRegion) { + throw new InvalidArgumentException(sprintf( 'The option "--flush" expects a "Doctrine\ORM\Cache\Region\DefaultRegion", but got "%s".', is_object($queryRegion) ? get_class($queryRegion) : gettype($queryRegion) )); diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/ResultCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/ResultCommand.php index 714dacacd24..55aeb5fb3b3 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/ResultCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/ResultCommand.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class ResultCommand extends Command { @@ -74,29 +72,29 @@ protected function execute(InputInterface $input, OutputInterface $output) { $ui = new SymfonyStyle($input, $output); - $em = $this->getHelper('em')->getEntityManager(); + $em = $this->getHelper('em')->getEntityManager(); $cacheDriver = $em->getConfiguration()->getResultCacheImpl(); - if ( ! $cacheDriver) { - throw new \InvalidArgumentException('No Result cache driver is configured on given EntityManager.'); + if (! $cacheDriver) { + throw new InvalidArgumentException('No Result cache driver is configured on given EntityManager.'); } if ($cacheDriver instanceof ApcCache) { - throw new \LogicException("Cannot clear APC Cache from Console, its shared in the Webserver memory and not accessible from the CLI."); + throw new LogicException('Cannot clear APC Cache from Console, its shared in the Webserver memory and not accessible from the CLI.'); } if ($cacheDriver instanceof XcacheCache) { - throw new \LogicException("Cannot clear XCache Cache from Console, its shared in the Webserver memory and not accessible from the CLI."); + throw new LogicException('Cannot clear XCache Cache from Console, its shared in the Webserver memory and not accessible from the CLI.'); } $ui->comment('Clearing all Result cache entries'); $result = $cacheDriver->deleteAll(); - $message = ($result) ? 'Successfully deleted cache entries.' : 'No cache entries were deleted.'; + $message = $result ? 'Successfully deleted cache entries.' : 'No cache entries were deleted.'; - if (true === $input->getOption('flush')) { + if ($input->getOption('flush') === true) { $result = $cacheDriver->flushAll(); - $message = ($result) ? 'Successfully flushed cache entries.' : $message; + $message = $result ? 'Successfully flushed cache entries.' : $message; } $ui->success($message); diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommand.php index e9f2b5e05b6..1c5b11f9609 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommand.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - * * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement + * + * @link www.doctrine-project.org */ class ConvertDoctrine1SchemaCommand extends Command { - /** - * @var EntityGenerator|null - */ + /** @var EntityGenerator|null */ private $entityGenerator = null; - /** - * @var ClassMetadataExporter|null - */ + /** @var ClassMetadataExporter|null */ private $metadataExporter = null; /** @@ -59,7 +61,7 @@ class ConvertDoctrine1SchemaCommand extends Command */ public function getEntityGenerator() { - if ($this->entityGenerator == null) { + if ($this->entityGenerator === null) { $this->entityGenerator = new EntityGenerator(); } @@ -67,8 +69,6 @@ public function getEntityGenerator() } /** - * @param EntityGenerator $entityGenerator - * * @return void */ public function setEntityGenerator(EntityGenerator $entityGenerator) @@ -81,7 +81,7 @@ public function setEntityGenerator(EntityGenerator $entityGenerator) */ public function getMetadataExporter() { - if ($this->metadataExporter == null) { + if ($this->metadataExporter === null) { $this->metadataExporter = new ClassMetadataExporter(); } @@ -89,8 +89,6 @@ public function getMetadataExporter() } /** - * @param ClassMetadataExporter $metadataExporter - * * @return void */ public function setMetadataExporter(ClassMetadataExporter $metadataExporter) @@ -129,8 +127,8 @@ protected function execute(InputInterface $input, OutputInterface $output) // Process destination directory $destPath = realpath($input->getArgument('dest-path')); - $toType = $input->getArgument('to-type'); - $extend = $input->getOption('extend'); + $toType = $input->getArgument('to-type'); + $extend = $input->getOption('extend'); $numSpaces = (int) $input->getOption('num-spaces'); $this->convertDoctrine1Schema($fromPaths, $destPath, $toType, $numSpaces, $extend, $output); @@ -139,46 +137,45 @@ protected function execute(InputInterface $input, OutputInterface $output) } /** - * @param array $fromPaths - * @param string $destPath - * @param string $toType - * @param int $numSpaces - * @param string|null $extend - * @param OutputInterface $output + * @param array $fromPaths + * @param string $destPath + * @param string $toType + * @param int $numSpaces + * @param string|null $extend * - * @throws \InvalidArgumentException + * @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( + 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( + 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( + 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( + if (! is_writable($destPath)) { + throw new InvalidArgumentException( sprintf("Doctrine 2.X mapping destination directory '%s' does not have write permissions.", $destPath) ); } - $cme = $this->getMetadataExporter(); + $cme = $this->getMetadataExporter(); $exporter = $cme->getExporter($toType, $destPath); if ($exporter instanceof AnnotationExporter) { @@ -193,7 +190,7 @@ public function convertDoctrine1Schema(array $fromPaths, $destPath, $toType, $nu } $converter = new ConvertDoctrine1Schema($fromPaths); - $metadata = $converter->getMetadata(); + $metadata = $converter->getMetadata(); if ($metadata) { $output->writeln(''); @@ -206,7 +203,9 @@ public function convertDoctrine1Schema(array $fromPaths, $destPath, $toType, $nu $exporter->export(); $output->writeln(PHP_EOL . sprintf( - 'Converting Doctrine 1.X schema to "%s" mapping type in "%s"', $toType, $destPath + '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 eea9f34527a..6fa9f513ae0 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ConvertMappingCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ConvertMappingCommand.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class ConvertMappingCommand extends Command { @@ -115,19 +121,20 @@ protected function execute(InputInterface $input, OutputInterface $output) $metadata = MetadataFilter::filter($metadata, $input->getOption('filter')); // Process destination directory - if ( ! is_dir($destPath = $input->getArgument('dest-path'))) { + if (! is_dir($destPath = $input->getArgument('dest-path'))) { mkdir($destPath, 0775, true); } + $destPath = realpath($destPath); - if ( ! file_exists($destPath)) { - throw new \InvalidArgumentException( + if (! file_exists($destPath)) { + throw new InvalidArgumentException( sprintf("Mapping destination directory '%s' does not exist.", $input->getArgument('dest-path')) ); } - if ( ! is_writable($destPath)) { - throw new \InvalidArgumentException( + if (! is_writable($destPath)) { + throw new InvalidArgumentException( sprintf("Mapping destination directory '%s' does not have write permissions.", $destPath) ); } @@ -150,6 +157,7 @@ protected function execute(InputInterface $input, OutputInterface $output) if (empty($metadata)) { $ui->success('No Metadata Classes to process.'); + return; } @@ -176,7 +184,7 @@ protected function execute(InputInterface $input, OutputInterface $output) * @param string $toType * @param string $destPath * - * @return \Doctrine\ORM\Tools\Export\Driver\AbstractExporter + * @return AbstractExporter */ protected function getExporter($toType, $destPath) { diff --git a/lib/Doctrine/ORM/Tools/Console/Command/EnsureProductionSettingsCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/EnsureProductionSettingsCommand.php index eb0ff17567d..fc47f506acf 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/EnsureProductionSettingsCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/EnsureProductionSettingsCommand.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class EnsureProductionSettingsCommand extends Command { diff --git a/lib/Doctrine/ORM/Tools/Console/Command/GenerateEntitiesCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/GenerateEntitiesCommand.php index e3f982e3532..5fff5d7b070 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/GenerateEntitiesCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/GenerateEntitiesCommand.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - * * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement + * + * @link www.doctrine-project.org */ class GenerateEntitiesCommand extends Command { @@ -101,20 +103,21 @@ protected function execute(InputInterface $input, OutputInterface $output) // Process destination directory $destPath = realpath($input->getArgument('dest-path')); - if ( ! file_exists($destPath)) { - throw new \InvalidArgumentException( + if (! file_exists($destPath)) { + throw new InvalidArgumentException( sprintf("Entities destination directory '%s' does not exist.", $input->getArgument('dest-path')) ); } - if ( ! is_writable($destPath)) { - throw new \InvalidArgumentException( + if (! is_writable($destPath)) { + throw new InvalidArgumentException( sprintf("Entities destination directory '%s' does not have write permissions.", $destPath) ); } if (empty($metadatas)) { $ui->success('No Metadata Classes to process.'); + return 0; } @@ -125,7 +128,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $entityGenerator->setRegenerateEntityIfExists($input->getOption('regenerate-entities')); $entityGenerator->setUpdateEntityIfExists($input->getOption('update-entities')); $entityGenerator->setNumSpaces((int) $input->getOption('num-spaces')); - $entityGenerator->setBackupExisting(!$input->getOption('no-backup')); + $entityGenerator->setBackupExisting(! $input->getOption('no-backup')); if (($extend = $input->getOption('extend')) !== null) { $entityGenerator->setClassToExtend($extend); diff --git a/lib/Doctrine/ORM/Tools/Console/Command/GenerateProxiesCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/GenerateProxiesCommand.php index 2cace34345c..a2c131266f5 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/GenerateProxiesCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/GenerateProxiesCommand.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class GenerateProxiesCommand extends Command { @@ -60,8 +65,8 @@ protected function execute(InputInterface $input, OutputInterface $output) { $ui = new SymfonyStyle($input, $output); - /** @var EntityManagerInterface $em */ $em = $this->getHelper('em')->getEntityManager(); + assert($em instanceof EntityManagerInterface); $metadatas = $em->getMetadataFactory()->getAllMetadata(); $metadatas = MetadataFilter::filter($metadatas, $input->getOption('filter')); @@ -71,26 +76,27 @@ protected function execute(InputInterface $input, OutputInterface $output) $destPath = $em->getConfiguration()->getProxyDir(); } - if ( ! is_dir($destPath)) { + if (! is_dir($destPath)) { mkdir($destPath, 0775, true); } $destPath = realpath($destPath); - if ( ! file_exists($destPath)) { - throw new \InvalidArgumentException( + if (! file_exists($destPath)) { + throw new InvalidArgumentException( sprintf("Proxies destination directory '%s' does not exist.", $em->getConfiguration()->getProxyDir()) ); } - if ( ! is_writable($destPath)) { - throw new \InvalidArgumentException( + if (! is_writable($destPath)) { + throw new InvalidArgumentException( sprintf("Proxies destination directory '%s' does not have write permissions.", $destPath) ); } if (empty($metadatas)) { $ui->success('No Metadata Classes to process.'); + return 0; } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/GenerateRepositoriesCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/GenerateRepositoriesCommand.php index 379c93597f6..55ac06fc668 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/GenerateRepositoriesCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/GenerateRepositoriesCommand.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - * * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement + * + * @link www.doctrine-project.org */ class GenerateRepositoriesCommand extends Command { @@ -73,20 +75,21 @@ protected function execute(InputInterface $input, OutputInterface $output) // Process destination directory $destPath = realpath($input->getArgument('dest-path')); - if ( ! file_exists($destPath)) { - throw new \InvalidArgumentException( + if (! file_exists($destPath)) { + throw new InvalidArgumentException( sprintf("Entities destination directory '%s' does not exist.", $input->getArgument('dest-path')) ); } - if ( ! is_writable($destPath)) { - throw new \InvalidArgumentException( + if (! is_writable($destPath)) { + throw new InvalidArgumentException( sprintf("Entities destination directory '%s' does not have write permissions.", $destPath) ); } if (empty($metadatas)) { $ui->success('No Metadata Classes to process.'); + return 0; } @@ -107,6 +110,7 @@ protected function execute(InputInterface $input, OutputInterface $output) if ($numRepositories === 0) { $ui->text('No Repository classes were found to be processed.'); + return 0; } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/InfoCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/InfoCommand.php index 89f6c318576..832cd5aee95 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/InfoCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/InfoCommand.php @@ -1,4 +1,5 @@ */ class InfoCommand extends Command { @@ -56,25 +60,25 @@ protected function execute(InputInterface $input, OutputInterface $output) { $ui = new SymfonyStyle($input, $output); - /* @var $entityManager \Doctrine\ORM\EntityManager */ $entityManager = $this->getHelper('em')->getEntityManager(); + assert($entityManager instanceof EntityManager); $entityClassNames = $entityManager->getConfiguration() ->getMetadataDriverImpl() ->getAllClassNames(); - if ( ! $entityClassNames) { + if (! $entityClassNames) { $ui->caution( [ 'You do not have any mapped Doctrine ORM entities according to the current configuration.', - 'If you have entities or mapping files you should check your mapping configuration for errors.' + 'If you have entities or mapping files you should check your mapping configuration for errors.', ] ); return 1; } - $ui->text(sprintf("Found %d mapped entities:", count($entityClassNames))); + $ui->text(sprintf('Found %d mapped entities:', count($entityClassNames))); $ui->newLine(); $failure = false; @@ -82,13 +86,13 @@ protected function execute(InputInterface $input, OutputInterface $output) foreach ($entityClassNames as $entityClassName) { try { $entityManager->getClassMetadata($entityClassName); - $ui->text(sprintf("[OK] %s", $entityClassName)); + $ui->text(sprintf('[OK] %s', $entityClassName)); } catch (MappingException $e) { $ui->text( [ - sprintf("[FAIL] %s", $entityClassName), - sprintf("%s", $e->getMessage()), - '' + sprintf('[FAIL] %s', $entityClassName), + sprintf('%s', $e->getMessage()), + '', ] ); diff --git a/lib/Doctrine/ORM/Tools/Console/Command/MappingDescribeCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/MappingDescribeCommand.php index 64a121b8f19..ae16c16902b 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/MappingDescribeCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/MappingDescribeCommand.php @@ -1,4 +1,5 @@ */ final class MappingDescribeCommand extends Command { @@ -67,8 +86,8 @@ protected function execute(InputInterface $input, OutputInterface $output) { $ui = new SymfonyStyle($input, $output); - /* @var $entityManager \Doctrine\ORM\EntityManagerInterface */ $entityManager = $this->getHelper('em')->getEntityManager(); + assert($entityManager instanceof EntityManagerInterface); $this->displayEntity($input->getArgument('entityName'), $entityManager, $ui); @@ -78,9 +97,7 @@ protected function execute(InputInterface $input, OutputInterface $output) /** * Display all the mapping information for a single Entity. * - * @param string $entityName Full or partial entity class name - * @param EntityManagerInterface $entityManager - * @param SymfonyStyle $ui + * @param string $entityName Full or partial entity class name */ private function displayEntity($entityName, EntityManagerInterface $entityManager, SymfonyStyle $ui) { @@ -131,19 +148,17 @@ private function displayEntity($entityName, EntityManagerInterface $entityManage /** * Return all mapped entity class names * - * @param EntityManagerInterface $entityManager - * * @return string[] */ - private function getMappedEntities(EntityManagerInterface $entityManager) : array + private function getMappedEntities(EntityManagerInterface $entityManager): array { $entityClassNames = $entityManager->getConfiguration() ->getMetadataDriverImpl() ->getAllClassNames(); - if ( ! $entityClassNames) { - throw new \InvalidArgumentException( - 'You do not have any mapped Doctrine ORM entities according to the current configuration. '. + if (! $entityClassNames) { + throw new InvalidArgumentException( + 'You do not have any mapped Doctrine ORM entities according to the current configuration. ' . 'If you have entities or mapping files you should check your mapping configuration for errors.' ); } @@ -155,10 +170,9 @@ private function getMappedEntities(EntityManagerInterface $entityManager) : arra * Return the class metadata for the given entity * name * - * @param string $entityName Full or partial entity name - * @param EntityManagerInterface $entityManager + * @param string $entityName Full or partial entity name * - * @return \Doctrine\ORM\Mapping\ClassMetadata + * @return ClassMetadata */ private function getClassMetadata($entityName, EntityManagerInterface $entityManager) { @@ -169,22 +183,23 @@ private function getClassMetadata($entityName, EntityManagerInterface $entityMan $matches = array_filter( $this->getMappedEntities($entityManager), - function ($mappedEntity) use ($entityName) { + static function ($mappedEntity) use ($entityName) { return preg_match('{' . preg_quote($entityName) . '}', $mappedEntity); } ); - if ( ! $matches) { - throw new \InvalidArgumentException(sprintf( + if (! $matches) { + throw new InvalidArgumentException(sprintf( 'Could not find any mapped Entity classes matching "%s"', $entityName )); } if (count($matches) > 1) { - throw new \InvalidArgumentException(sprintf( + throw new InvalidArgumentException(sprintf( 'Entity name "%s" is ambiguous, possible matches: "%s"', - $entityName, implode(', ', $matches) + $entityName, + implode(', ', $matches) )); } @@ -200,11 +215,11 @@ function ($mappedEntity) use ($entityName) { */ private function formatValue($value) { - if ('' === $value) { + if ($value === '') { return ''; } - if (null === $value) { + if ($value === null) { return 'Null'; } @@ -228,7 +243,7 @@ private function formatValue($value) return (string) $value; } - throw new \InvalidArgumentException(sprintf('Do not know how to format value "%s"', print_r($value, true))); + throw new InvalidArgumentException(sprintf('Do not know how to format value "%s"', print_r($value, true))); } /** @@ -241,9 +256,9 @@ private function formatValue($value) * * @psalm-return array{0: string, 1: string} */ - private function formatField($label, $value) : array + private function formatField($label, $value): array { - if (null === $value) { + if ($value === null) { $value = 'None'; } @@ -259,7 +274,7 @@ private function formatField($label, $value) : array * * @psalm-return list */ - private function formatMappings(array $propertyMappings) : array + private function formatMappings(array $propertyMappings): array { $output = []; @@ -283,7 +298,7 @@ private function formatMappings(array $propertyMappings) : array * * @psalm-return array{0: string, 1: string} */ - private function formatEntityListeners(array $entityListeners) : array + private function formatEntityListeners(array $entityListeners): array { return $this->formatField('Entity listeners', array_map('get_class', $entityListeners)); } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/RunDqlCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/RunDqlCommand.php index ae34c7fe215..86c7d496b3d 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/RunDqlCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/RunDqlCommand.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class RunDqlCommand extends Command { @@ -62,24 +68,24 @@ protected function execute(InputInterface $input, OutputInterface $output) { $ui = new SymfonyStyle($input, $output); - /* @var $em \Doctrine\ORM\EntityManagerInterface */ $em = $this->getHelper('em')->getEntityManager(); + assert($em instanceof EntityManagerInterface); if (($dql = $input->getArgument('dql')) === null) { - throw new \RuntimeException("Argument 'dql' is required in order to execute this command correctly."); + throw new RuntimeException("Argument 'dql' is required in order to execute this command correctly."); } $depth = $input->getOption('depth'); - if ( ! is_numeric($depth)) { - throw new \LogicException("Option 'depth' must contain an integer value"); + if (! is_numeric($depth)) { + throw new LogicException("Option 'depth' must contain an integer value"); } $hydrationModeName = $input->getOption('hydrate'); - $hydrationMode = 'Doctrine\ORM\Query::HYDRATE_' . strtoupper(str_replace('-', '_', $hydrationModeName)); + $hydrationMode = 'Doctrine\ORM\Query::HYDRATE_' . strtoupper(str_replace('-', '_', $hydrationModeName)); - if ( ! defined($hydrationMode)) { - throw new \RuntimeException( + if (! defined($hydrationMode)) { + throw new RuntimeException( "Hydration mode '$hydrationModeName' does not exist. It should be either: object. array, scalar or single-scalar." ); } @@ -87,16 +93,16 @@ protected function execute(InputInterface $input, OutputInterface $output) $query = $em->createQuery($dql); if (($firstResult = $input->getOption('first-result')) !== null) { - if ( ! is_numeric($firstResult)) { - throw new \LogicException("Option 'first-result' must contain an integer value"); + if (! is_numeric($firstResult)) { + throw new LogicException("Option 'first-result' must contain an integer value"); } $query->setFirstResult((int) $firstResult); } if (($maxResult = $input->getOption('max-result')) !== null) { - if ( ! is_numeric($maxResult)) { - throw new \LogicException("Option 'max-result' must contain an integer value"); + if (! is_numeric($maxResult)) { + throw new LogicException("Option 'max-result' must contain an integer value"); } $query->setMaxResults((int) $maxResult); @@ -104,6 +110,7 @@ protected function execute(InputInterface $input, OutputInterface $output) if ($input->getOption('show-sql')) { $ui->text($query->getSQL()); + return 0; } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/AbstractCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/AbstractCommand.php index 21907d094a1..5e8c0f19c1e 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/AbstractCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/AbstractCommand.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ abstract class AbstractCommand extends Command { /** - * @param InputInterface $input - * @param OutputInterface $output - * @param SchemaTool $schemaTool - * @param array $metadatas + * @param array $metadatas * - * @return null|int Null or 0 if everything went fine, or an error code. + * @return int|null Null or 0 if everything went fine, or an error code. */ abstract protected function executeSchemaCommand(InputInterface $input, OutputInterface $output, SchemaTool $schemaTool, array $metadatas, SymfonyStyle $ui); @@ -56,8 +52,8 @@ protected function execute(InputInterface $input, OutputInterface $output) $emHelper = $this->getHelper('em'); - /* @var $em \Doctrine\ORM\EntityManager */ $em = $emHelper->getEntityManager(); + assert($em instanceof EntityManager); $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 0c2137417b3..d10adcab595 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/CreateCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/CreateCommand.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class CreateCommand extends AbstractCommand { @@ -62,7 +60,7 @@ protected function configure() */ protected function executeSchemaCommand(InputInterface $input, OutputInterface $output, SchemaTool $schemaTool, array $metadatas, SymfonyStyle $ui) { - $dumpSql = true === $input->getOption('dump-sql'); + $dumpSql = $input->getOption('dump-sql') === true; if ($dumpSql) { $sqls = $schemaTool->getCreateSchemaSql($metadatas); diff --git a/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/DropCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/DropCommand.php index 3d77fc8fd84..0841889e49e 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/DropCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/DropCommand.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class DropCommand extends AbstractCommand { @@ -66,8 +65,8 @@ protected function configure() protected function executeSchemaCommand(InputInterface $input, OutputInterface $output, SchemaTool $schemaTool, array $metadatas, SymfonyStyle $ui) { $isFullDatabaseDrop = $input->getOption('full-database'); - $dumpSql = true === $input->getOption('dump-sql'); - $force = true === $input->getOption('force'); + $dumpSql = $input->getOption('dump-sql') === true; + $force = $input->getOption('force') === true; if ($dumpSql) { if ($isFullDatabaseDrop) { @@ -75,6 +74,7 @@ protected function executeSchemaCommand(InputInterface $input, OutputInterface $ } else { $sqls = $schemaTool->getDropSchemaSQL($metadatas); } + $ui->text('The following SQL statements will be executed:'); $ui->newLine(); diff --git a/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/UpdateCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/UpdateCommand.php index c9059775b1e..8bae0784213 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/UpdateCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/UpdateCommand.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - * @author Ryan Weaver */ class UpdateCommand extends AbstractCommand { - /** - * @var string - */ + /** @var string */ protected $name = 'orm:schema-tool:update'; /** @@ -103,8 +99,8 @@ protected function executeSchemaCommand(InputInterface $input, OutputInterface $ return 0; } - $dumpSql = true === $input->getOption('dump-sql'); - $force = true === $input->getOption('force'); + $dumpSql = $input->getOption('dump-sql') === true; + $force = $input->getOption('force') === true; if ($dumpSql) { $ui->text('The following SQL statements will be executed:'); @@ -119,12 +115,13 @@ protected function executeSchemaCommand(InputInterface $input, OutputInterface $ if ($dumpSql) { $ui->newLine(); } + $ui->text('Updating database schema...'); $ui->newLine(); $schemaTool->updateSchema($metadatas, $saveMode); - $pluralization = (1 === count($sqls)) ? 'query was' : 'queries were'; + $pluralization = count($sqls) === 1 ? 'query was' : 'queries were'; $ui->text(sprintf(' %s %s executed', count($sqls), $pluralization)); $ui->success('Database schema updated successfully!'); diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ValidateSchemaCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ValidateSchemaCommand.php index 343d3b53db9..294c573641d 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ValidateSchemaCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ValidateSchemaCommand.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class ValidateSchemaCommand extends Command { @@ -58,9 +55,9 @@ protected function execute(InputInterface $input, OutputInterface $output) { $ui = new SymfonyStyle($input, $output); - $em = $this->getHelper('em')->getEntityManager(); + $em = $this->getHelper('em')->getEntityManager(); $validator = new SchemaValidator($em); - $exit = 0; + $exit = 0; $ui->section('Mapping'); @@ -88,7 +85,7 @@ protected function execute(InputInterface $input, OutputInterface $output) if ($input->getOption('skip-sync')) { $ui->text('[SKIPPED] The database was not checked for synchronicity.'); - } elseif ( ! $validator->schemaInSyncWithMetadata()) { + } elseif (! $validator->schemaInSyncWithMetadata()) { $ui->error('The database schema is not in sync with the current mapping file.'); $exit += 2; } else { diff --git a/lib/Doctrine/ORM/Tools/Console/ConsoleRunner.php b/lib/Doctrine/ORM/Tools/Console/ConsoleRunner.php index a84db75f416..b7696710adb 100644 --- a/lib/Doctrine/ORM/Tools/Console/ConsoleRunner.php +++ b/lib/Doctrine/ORM/Tools/Console/ConsoleRunner.php @@ -1,4 +1,5 @@ run(); @@ -67,13 +62,11 @@ public static function run(HelperSet $helperSet, array $commands = []) : void * Creates a console application with the given helperset and * optional commands. * - * @param \Symfony\Component\Console\Helper\HelperSet $helperSet - * @param array $commands + * @param array $commands * - * @return \Symfony\Component\Console\Application * @throws OutOfBoundsException */ - public static function createApplication(HelperSet $helperSet, array $commands = []) : Application + public static function createApplication(HelperSet $helperSet, array $commands = []): Application { $cli = new Application('Doctrine Command Line Interface', Versions::getVersion('doctrine/orm')); $cli->setCatchExceptions(true); @@ -84,12 +77,7 @@ public static function createApplication(HelperSet $helperSet, array $commands = return $cli; } - /** - * @param Application $cli - * - * @return void - */ - public static function addCommands(Application $cli) : void + public static function addCommands(Application $cli): void { $cli->addCommands( [ @@ -122,7 +110,7 @@ public static function addCommands(Application $cli) : void ); } - public static function printCliConfigTemplate() : void + public static function printCliConfigTemplate(): void { echo <<<'HELP' You are missing a "cli-config.php" or "config/cli-config.php" file in your diff --git a/lib/Doctrine/ORM/Tools/Console/Helper/EntityManagerHelper.php b/lib/Doctrine/ORM/Tools/Console/Helper/EntityManagerHelper.php index 267304b984c..b312b453930 100644 --- a/lib/Doctrine/ORM/Tools/Console/Helper/EntityManagerHelper.php +++ b/lib/Doctrine/ORM/Tools/Console/Helper/EntityManagerHelper.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class EntityManagerHelper extends Helper { @@ -41,11 +37,6 @@ class EntityManagerHelper extends Helper */ protected $_em; - /** - * Constructor. - * - * @param EntityManagerInterface $em - */ public function __construct(EntityManagerInterface $em) { $this->_em = $em; diff --git a/lib/Doctrine/ORM/Tools/Console/MetadataFilter.php b/lib/Doctrine/ORM/Tools/Console/MetadataFilter.php index b03f599162f..78c41e6f60e 100644 --- a/lib/Doctrine/ORM/Tools/Console/MetadataFilter.php +++ b/lib/Doctrine/ORM/Tools/Console/MetadataFilter.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ -class MetadataFilter extends \FilterIterator implements \Countable +class MetadataFilter extends FilterIterator implements Countable { - /** - * @var array - */ + /** @var array */ private $filter = []; /** @@ -47,18 +49,17 @@ class MetadataFilter extends \FilterIterator implements \Countable * * @return ClassMetadata[] */ - static public function filter(array $metadatas, $filter) + public static function filter(array $metadatas, $filter) { - $metadatas = new MetadataFilter(new \ArrayIterator($metadatas), $filter); + $metadatas = new MetadataFilter(new ArrayIterator($metadatas), $filter); return iterator_to_array($metadatas); } /** - * @param \ArrayIterator $metadata - * @param array|string $filter + * @param array|string $filter */ - public function __construct(\ArrayIterator $metadata, $filter) + public function __construct(ArrayIterator $metadata, $filter) { $this->filter = (array) $filter; @@ -70,18 +71,18 @@ public function __construct(\ArrayIterator $metadata, $filter) */ public function accept() { - if (count($this->filter) == 0) { + if (count($this->filter) === 0) { return true; } - $it = $this->getInnerIterator(); + $it = $this->getInnerIterator(); $metadata = $it->current(); foreach ($this->filter as $filter) { $pregResult = preg_match("/$filter/", $metadata->name); if ($pregResult === false) { - throw new \RuntimeException( + throw new RuntimeException( sprintf("Error while evaluating regex '/%s/'.", $filter) ); } diff --git a/lib/Doctrine/ORM/Tools/ConvertDoctrine1Schema.php b/lib/Doctrine/ORM/Tools/ConvertDoctrine1Schema.php index c64c24d1e84..f48e9bbaab5 100644 --- a/lib/Doctrine/ORM/Tools/ConvertDoctrine1Schema.php +++ b/lib/Doctrine/ORM/Tools/ConvertDoctrine1Schema.php @@ -1,4 +1,5 @@ - * @author Jonathan Wage - * @author Roman Borschel */ class ConvertDoctrine1Schema { - /** - * @var array - */ + /** @var array */ private $from; - /** - * @var array - */ + /** @var array */ private $legacyTypeMap = [ // TODO: This list may need to be updated 'clob' => 'text', 'timestamp' => 'datetime', - 'enum' => 'string' + 'enum' => 'string', ]; /** @@ -56,8 +60,6 @@ class ConvertDoctrine1Schema * to convert the Doctrine 1 schema files from. * * @param array $from - * - * @author Jonathan Wage */ public function __construct($from) { @@ -98,7 +100,7 @@ public function getMetadata() * @param string $className * @param array $mappingInformation * - * @return \Doctrine\ORM\Mapping\ClassMetadataInfo + * @return ClassMetadataInfo */ private function convertToClassMetadataInfo($className, $mappingInformation) { @@ -113,9 +115,8 @@ private function convertToClassMetadataInfo($className, $mappingInformation) } /** - * @param string $className - * @param array $model - * @param ClassMetadataInfo $metadata + * @param string $className + * @param array $model * * @return void */ @@ -126,7 +127,7 @@ private function convertTableName($className, array $model, ClassMetadataInfo $m if (count($e) > 1) { $metadata->table['schema'] = $e[0]; - $metadata->table['name'] = $e[1]; + $metadata->table['name'] = $e[1]; } else { $metadata->table['name'] = $e[0]; } @@ -134,9 +135,8 @@ private function convertTableName($className, array $model, ClassMetadataInfo $m } /** - * @param string $className - * @param array $model - * @param ClassMetadataInfo $metadata + * @param string $className + * @param array $model * * @return void */ @@ -154,12 +154,12 @@ private function convertColumns($className, array $model, ClassMetadataInfo $met } } - if ( ! $id) { + if (! $id) { $fieldMapping = [ 'fieldName' => 'id', 'columnName' => 'id', 'type' => 'integer', - 'id' => true + 'id' => true, ]; $metadata->mapField($fieldMapping); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); @@ -167,10 +167,9 @@ private function convertColumns($className, array $model, ClassMetadataInfo $met } /** - * @param string $className - * @param string $name - * @param string|array $column - * @param ClassMetadataInfo $metadata + * @param string $className + * @param string $name + * @param string|array $column * * @return mixed[] * @@ -179,24 +178,24 @@ private function convertColumns($className, array $model, ClassMetadataInfo $met private function convertColumn($className, $name, $column, ClassMetadataInfo $metadata) { if (is_string($column)) { - $string = $column; - $column = []; + $string = $column; + $column = []; $column['type'] = $string; } - if ( ! isset($column['name'])) { + 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; + 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]; + if (preg_match('/([a-zA-Z]+)\(([0-9]+)\)/', $column['type'], $matches)) { + $column['type'] = $matches[1]; $column['length'] = $matches[2]; } @@ -206,7 +205,7 @@ private function convertColumn($className, $name, $column, ClassMetadataInfo $me $column['type'] = $this->legacyTypeMap[$column['type']]; } - if ( ! Type::hasType($column['type'])) { + if (! Type::hasType($column['type'])) { throw ToolsException::couldNotMapDoctrine1Type($column['type']); } @@ -216,9 +215,9 @@ private function convertColumn($className, $name, $column, ClassMetadataInfo $me $fieldMapping['id'] = true; } - $fieldMapping['fieldName'] = $column['alias'] ?? $name; + $fieldMapping['fieldName'] = $column['alias'] ?? $name; $fieldMapping['columnName'] = $column['name']; - $fieldMapping['type'] = $column['type']; + $fieldMapping['type'] = $column['type']; if (isset($column['length'])) { $fieldMapping['length'] = $column['length']; @@ -240,7 +239,7 @@ private function convertColumn($className, $name, $column, ClassMetadataInfo $me $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_SEQUENCE); $definition = [ - 'sequenceName' => is_array($column['sequence']) ? $column['sequence']['name']:$column['sequence'] + 'sequenceName' => is_array($column['sequence']) ? $column['sequence']['name'] : $column['sequence'], ]; if (isset($column['sequence']['size'])) { @@ -258,9 +257,8 @@ private function convertColumn($className, $name, $column, ClassMetadataInfo $me } /** - * @param string $className - * @param array $model - * @param ClassMetadataInfo $metadata + * @param string $className + * @param array $model * * @return void */ @@ -271,19 +269,18 @@ private function convertIndexes($className, array $model, ClassMetadataInfo $met } foreach ($model['indexes'] as $name => $index) { - $type = (isset($index['type']) && $index['type'] == 'unique') + $type = isset($index['type']) && $index['type'] === 'unique' ? 'uniqueConstraints' : 'indexes'; $metadata->table[$type][$name] = [ - 'columns' => $index['fields'] + 'columns' => $index['fields'], ]; } } /** - * @param string $className - * @param array $model - * @param ClassMetadataInfo $metadata + * @param string $className + * @param array $model * * @return void */ @@ -296,51 +293,55 @@ private function convertRelations($className, array $model, ClassMetadataInfo $m $inflector = InflectorFactory::create()->build(); foreach ($model['relations'] as $name => $relation) { - if ( ! isset($relation['alias'])) { + if (! isset($relation['alias'])) { $relation['alias'] = $name; } - if ( ! isset($relation['class'])) { + + if (! isset($relation['class'])) { $relation['class'] = $name; } - if ( ! isset($relation['local'])) { + + if (! isset($relation['local'])) { $relation['local'] = $inflector->tableize($relation['class']); } - if ( ! isset($relation['foreign'])) { + + if (! isset($relation['foreign'])) { $relation['foreign'] = 'id'; } - if ( ! isset($relation['foreignAlias'])) { + + if (! isset($relation['foreignAlias'])) { $relation['foreignAlias'] = $className; } if (isset($relation['refClass'])) { - $type = 'many'; + $type = 'many'; $foreignType = 'many'; $joinColumns = []; } else { - $type = $relation['type'] ?? 'one'; + $type = $relation['type'] ?? 'one'; $foreignType = $relation['foreignType'] ?? 'many'; $joinColumns = [ [ 'name' => $relation['local'], 'referencedColumnName' => $relation['foreign'], 'onDelete' => $relation['onDelete'] ?? null, - ] + ], ]; } - if ($type == 'one' && $foreignType == 'one') { + if ($type === 'one' && $foreignType === 'one') { $method = 'mapOneToOne'; - } elseif ($type == 'many' && $foreignType == 'many') { + } elseif ($type === 'many' && $foreignType === 'many') { $method = 'mapManyToMany'; } else { $method = 'mapOneToMany'; } - $associationMapping = []; - $associationMapping['fieldName'] = $relation['alias']; + $associationMapping = []; + $associationMapping['fieldName'] = $relation['alias']; $associationMapping['targetEntity'] = $relation['class']; - $associationMapping['mappedBy'] = $relation['foreignAlias']; - $associationMapping['joinColumns'] = $joinColumns; + $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 94a239f38e9..f9a9b046aba 100644 --- a/lib/Doctrine/ORM/Tools/DebugUnitOfWorkListener.php +++ b/lib/Doctrine/ORM/Tools/DebugUnitOfWorkListener.php @@ -1,4 +1,5 @@ file = $file; + $this->file = $file; $this->context = $context; } /** - * @param \Doctrine\ORM\Event\OnFlushEventArgs $args - * * @return void */ public function onFlush(OnFlushEventArgs $args) @@ -69,60 +73,58 @@ public function onFlush(OnFlushEventArgs $args) /** * Dumps the contents of the identity map into a stream. * - * @param EntityManagerInterface $em - * * @return void */ public function dumpIdentityMap(EntityManagerInterface $em) { - $uow = $em->getUnitOfWork(); + $uow = $em->getUnitOfWork(); $identityMap = $uow->getIdentityMap(); $fh = fopen($this->file, 'xb+'); - if (count($identityMap) == 0) { - fwrite($fh, "Flush Operation [".$this->context."] - Empty identity map.\n"); + 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"); + fwrite($fh, 'Flush Operation [' . $this->context . "] - Dumping identity map:\n"); foreach ($identityMap as $className => $map) { - fwrite($fh, "Class: ". $className . "\n"); + fwrite($fh, 'Class: ' . $className . "\n"); foreach ($map as $entity) { - fwrite($fh, " Entity: " . $this->getIdString($entity, $uow) . " " . spl_object_hash($entity)."\n"); + fwrite($fh, ' Entity: ' . $this->getIdString($entity, $uow) . ' ' . spl_object_hash($entity) . "\n"); fwrite($fh, " Associations:\n"); $cm = $em->getClassMetadata($className); foreach ($cm->associationMappings as $field => $assoc) { - fwrite($fh, " " . $field . " "); + 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] "); + if ($value instanceof Proxy && ! $value->__isInitialized()) { + fwrite($fh, '[PROXY] '); } - fwrite($fh, $this->getIdString($value, $uow) . " " . spl_object_hash($value) . "\n"); + fwrite($fh, $this->getIdString($value, $uow) . ' ' . spl_object_hash($value) . "\n"); } } else { - $initialized = !($value instanceof PersistentCollection) || $value->isInitialized(); + $initialized = ! ($value instanceof PersistentCollection) || $value->isInitialized(); if ($value === null) { fwrite($fh, " NULL\n"); } elseif ($initialized) { - fwrite($fh, "[INITIALIZED] " . $this->getType($value). " " . count($value) . " elements\n"); + fwrite($fh, '[INITIALIZED] ' . $this->getType($value) . ' ' . count($value) . " elements\n"); foreach ($value as $obj) { - fwrite($fh, " " . $this->getIdString($obj, $uow) . " " . spl_object_hash($obj)."\n"); + fwrite($fh, ' ' . $this->getIdString($obj, $uow) . ' ' . spl_object_hash($obj) . "\n"); } } else { - fwrite($fh, "[PROXY] " . $this->getType($value) . " unknown element size\n"); + 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"); + fwrite($fh, ' ' . $this->getIdString($obj, $uow) . ' ' . spl_object_hash($obj) . "\n"); } } } @@ -141,7 +143,7 @@ public function dumpIdentityMap(EntityManagerInterface $em) private function getType($var) { if (is_object($var)) { - $refl = new \ReflectionObject($var); + $refl = new ReflectionObject($var); return $refl->getShortName(); } @@ -150,34 +152,33 @@ private function getType($var) } /** - * @param object $entity - * @param UnitOfWork $uow + * @param object $entity * * @return string */ private function getIdString($entity, UnitOfWork $uow) { if ($uow->isInIdentityMap($entity)) { - $ids = $uow->getEntityIdentifier($entity); - $idstring = ""; + $ids = $uow->getEntityIdentifier($entity); + $idstring = ''; foreach ($ids as $k => $v) { - $idstring .= $k."=".$v; + $idstring .= $k . '=' . $v; } } else { - $idstring = "NEWOBJECT "; + $idstring = 'NEWOBJECT '; } $state = $uow->getEntityState($entity); - if ($state == UnitOfWork::STATE_NEW) { - $idstring .= " [NEW]"; - } elseif ($state == UnitOfWork::STATE_REMOVED) { - $idstring .= " [REMOVED]"; - } elseif ($state == UnitOfWork::STATE_MANAGED) { - $idstring .= " [MANAGED]"; - } elseif ($state == UnitOfWork::STATE_DETACHED) { - $idstring .= " [DETACHED]"; + if ($state === UnitOfWork::STATE_NEW) { + $idstring .= ' [NEW]'; + } elseif ($state === UnitOfWork::STATE_REMOVED) { + $idstring .= ' [REMOVED]'; + } elseif ($state === UnitOfWork::STATE_MANAGED) { + $idstring .= ' [MANAGED]'; + } elseif ($state === UnitOfWork::STATE_DETACHED) { + $idstring .= ' [DETACHED]'; } return $idstring; diff --git a/lib/Doctrine/ORM/Tools/DisconnectedClassMetadataFactory.php b/lib/Doctrine/ORM/Tools/DisconnectedClassMetadataFactory.php index 67af4e2ac07..6c76446d2f4 100644 --- a/lib/Doctrine/ORM/Tools/DisconnectedClassMetadataFactory.php +++ b/lib/Doctrine/ORM/Tools/DisconnectedClassMetadataFactory.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class DisconnectedClassMetadataFactory extends ClassMetadataFactory { diff --git a/lib/Doctrine/ORM/Tools/EntityGenerator.php b/lib/Doctrine/ORM/Tools/EntityGenerator.php index ff3820a55e1..3e1dce35f82 100644 --- a/lib/Doctrine/ORM/Tools/EntityGenerator.php +++ b/lib/Doctrine/ORM/Tools/EntityGenerator.php @@ -1,4 +1,5 @@ setUpdateEntityIfExists(true); * $generator->generate($classes, '/path/to/generate/entities'); * + * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement * * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - * - * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement */ class EntityGenerator { /** * Specifies class fields should be protected. */ - const FIELD_VISIBLE_PROTECTED = 'protected'; + public const FIELD_VISIBLE_PROTECTED = 'protected'; /** * Specifies class fields should be private. */ - const FIELD_VISIBLE_PRIVATE = 'private'; + public const FIELD_VISIBLE_PRIVATE = 'private'; - /** - * @var bool - */ + /** @var bool */ protected $backupExisting = true; /** @@ -81,13 +130,11 @@ class EntityGenerator /** * Whether or not the current ClassMetadataInfo instance is new or old. * - * @var boolean + * @var bool */ protected $isNew = true; - /** - * @var array - */ + /** @var array */ protected $staticReflection = []; /** @@ -112,33 +159,31 @@ class EntityGenerator /** * Whether or not to generation annotations. * - * @var boolean + * @var bool */ protected $generateAnnotations = false; - /** - * @var string - */ + /** @var string */ protected $annotationsPrefix = ''; /** * Whether or not to generate sub methods. * - * @var boolean + * @var bool */ protected $generateEntityStubMethods = false; /** * Whether or not to update the entity class if it exists already. * - * @var boolean + * @var bool */ protected $updateEntityIfExists = false; /** * Whether or not to re-generate entity class if it exists already. * - * @var boolean + * @var bool */ protected $regenerateEntityIfExists = false; @@ -191,7 +236,7 @@ class EntityGenerator ClassMetadataInfo::GENERATOR_TYPE_IDENTITY => 'IDENTITY', ClassMetadataInfo::GENERATOR_TYPE_NONE => 'NONE', ClassMetadataInfo::GENERATOR_TYPE_UUID => 'UUID', - ClassMetadataInfo::GENERATOR_TYPE_CUSTOM => 'CUSTOM' + ClassMetadataInfo::GENERATOR_TYPE_CUSTOM => 'CUSTOM', ]; /** @@ -217,11 +262,9 @@ class EntityGenerator ClassMetadataInfo::INHERITANCE_TYPE_TABLE_PER_CLASS => 'TABLE_PER_CLASS', ]; - /** - * @var string - */ + /** @var string */ protected static $classTemplate = -' @@ -232,11 +275,9 @@ class EntityGenerator } '; - /** - * @var string - */ + /** @var string */ protected static $getMethodTemplate = -'/** + '/** * * * @return @@ -246,11 +287,9 @@ public function () return $this->; }'; - /** - * @var string - */ + /** @var string */ protected static $setMethodTemplate = -'/** + '/** * * * @param $ @@ -264,11 +303,9 @@ public function ($) return $this; }'; - /** - * @var string - */ + /** @var string */ protected static $addMethodTemplate = -'/** + '/** * * * @param $ @@ -282,11 +319,9 @@ public function ($) return $this; }'; - /** - * @var string - */ + /** @var string */ protected static $removeMethodTemplate = -'/** + '/** * * * @param $ @@ -298,11 +333,9 @@ public function ($) return $this->->removeElement($); }'; - /** - * @var string - */ + /** @var string */ protected static $lifecycleCallbackMethodTemplate = -'/** + '/** * @ */ public function () @@ -310,11 +343,9 @@ public function () // Add your code here }'; - /** - * @var string - */ + /** @var string */ protected static $constructorMethodTemplate = -'/** + '/** * Constructor */ public function __construct() @@ -323,11 +354,9 @@ public function __construct() } '; - /** - * @var string - */ + /** @var string */ protected static $embeddableConstructorMethodTemplate = -'/** + '/** * Constructor * * @@ -341,9 +370,6 @@ public function __construct() /** @var Inflector */ protected $inflector; - /** - * Constructor. - */ public function __construct() { @trigger_error(self::class . ' is deprecated and will be removed in Doctrine ORM 3.0', E_USER_DEPRECATED); @@ -370,34 +396,33 @@ public function generate(array $metadatas, $outputDirectory) /** * Generates and writes entity class to disk for the given ClassMetadataInfo instance. * - * @param ClassMetadataInfo $metadata - * @param string $outputDirectory + * @param string $outputDirectory * * @return void * - * @throws \RuntimeException + * @throws RuntimeException */ public function writeEntityClass(ClassMetadataInfo $metadata, $outputDirectory) { $path = $outputDirectory . '/' . str_replace('\\', DIRECTORY_SEPARATOR, $metadata->name) . $this->extension; - $dir = dirname($path); + $dir = dirname($path); - if ( ! is_dir($dir)) { + if (! is_dir($dir)) { mkdir($dir, 0775, true); } $this->isNew = ! file_exists($path) || $this->regenerateEntityIfExists; - if ( ! $this->isNew) { + if (! $this->isNew) { $this->parseTokensInEntityFile(file_get_contents($path)); } else { $this->staticReflection[$metadata->name] = ['properties' => [], 'methods' => []]; } if ($this->backupExisting && file_exists($path)) { - $backupPath = dirname($path) . DIRECTORY_SEPARATOR . basename($path) . "~"; - if (!copy($path, $backupPath)) { - throw new \RuntimeException("Attempt to backup overwritten entity file but copy operation failed."); + $backupPath = dirname($path) . DIRECTORY_SEPARATOR . basename($path) . '~'; + if (! copy($path, $backupPath)) { + throw new RuntimeException('Attempt to backup overwritten entity file but copy operation failed.'); } } @@ -408,14 +433,13 @@ public function writeEntityClass(ClassMetadataInfo $metadata, $outputDirectory) } elseif ($this->updateEntityIfExists) { file_put_contents($path, $this->generateUpdatedEntityClass($metadata, $path)); } + chmod($path, 0664); } /** * Generates a PHP5 Doctrine 2 entity class from the given ClassMetadataInfo instance. * - * @param ClassMetadataInfo $metadata - * * @return string */ public function generateEntityClass(ClassMetadataInfo $metadata) @@ -425,7 +449,7 @@ public function generateEntityClass(ClassMetadataInfo $metadata) '', '', '', - '' + '', ]; $replacements = [ @@ -433,7 +457,7 @@ public function generateEntityClass(ClassMetadataInfo $metadata) $this->generateEntityUse(), $this->generateEntityDocBlock($metadata), $this->generateEntityClassName($metadata), - $this->generateEntityBody($metadata) + $this->generateEntityBody($metadata), ]; $code = str_replace($placeHolders, $replacements, static::$classTemplate); @@ -444,8 +468,7 @@ public function generateEntityClass(ClassMetadataInfo $metadata) /** * Generates the updated code for the given ClassMetadataInfo and entity at path. * - * @param ClassMetadataInfo $metadata - * @param string $path + * @param string $path * * @return string */ @@ -463,13 +486,13 @@ public function generateUpdatedEntityClass(ClassMetadataInfo $metadata, $path) /** * Sets the number of spaces the exported class should have. * - * @param integer $numSpaces + * @param int $numSpaces * * @return void */ public function setNumSpaces($numSpaces) { - $this->spaces = str_repeat(' ', $numSpaces); + $this->spaces = str_repeat(' ', $numSpaces); $this->numSpaces = $numSpaces; } @@ -516,14 +539,14 @@ public function setGenerateAnnotations($bool) * * @return void * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException * * @psalm-param self::FIELD_VISIBLE_* */ public function setFieldVisibility($visibility) { - if ($visibility !== static::FIELD_VISIBLE_PRIVATE && $visibility !== static::FIELD_VISIBLE_PROTECTED) { - throw new \InvalidArgumentException('Invalid provided visibility (only private and protected are allowed): ' . $visibility); + if ($visibility !== self::FIELD_VISIBLE_PRIVATE && $visibility !== self::FIELD_VISIBLE_PROTECTED) { + throw new InvalidArgumentException('Invalid provided visibility (only private and protected are allowed): ' . $visibility); } $this->fieldVisibility = $visibility; @@ -532,11 +555,11 @@ public function setFieldVisibility($visibility) /** * Sets whether or not to generate immutable embeddables. * - * @param boolean $embeddablesImmutable + * @param bool $embeddablesImmutable */ public function setEmbeddablesImmutable($embeddablesImmutable) { - $this->embeddablesImmutable = (boolean) $embeddablesImmutable; + $this->embeddablesImmutable = (bool) $embeddablesImmutable; } /** @@ -599,7 +622,7 @@ public function setBackupExisting($bool) $this->backupExisting = $bool; } - public function setInflector(Inflector $inflector) : void + public function setInflector(Inflector $inflector): void { $this->inflector = $inflector; } @@ -619,8 +642,6 @@ protected function getType($type) } /** - * @param ClassMetadataInfo $metadata - * * @return string */ protected function generateEntityNamespace(ClassMetadataInfo $metadata) @@ -629,7 +650,7 @@ protected function generateEntityNamespace(ClassMetadataInfo $metadata) return ''; } - return 'namespace ' . $this->getNamespace($metadata) .';'; + return 'namespace ' . $this->getNamespace($metadata) . ';'; } /** @@ -641,12 +662,10 @@ protected function generateEntityUse() return ''; } - return "\n".'use Doctrine\ORM\Mapping as ORM;'."\n"; + return "\n" . 'use Doctrine\ORM\Mapping as ORM;' . "\n"; } /** - * @param ClassMetadataInfo $metadata - * * @return string */ protected function generateEntityClassName(ClassMetadataInfo $metadata) @@ -656,17 +675,15 @@ protected function generateEntityClassName(ClassMetadataInfo $metadata) } /** - * @param ClassMetadataInfo $metadata - * * @return string */ protected function generateEntityBody(ClassMetadataInfo $metadata) { - $fieldMappingProperties = $this->generateEntityFieldMappingProperties($metadata); - $embeddedProperties = $this->generateEntityEmbeddedProperties($metadata); + $fieldMappingProperties = $this->generateEntityFieldMappingProperties($metadata); + $embeddedProperties = $this->generateEntityEmbeddedProperties($metadata); $associationMappingProperties = $this->generateEntityAssociationMappingProperties($metadata); - $stubMethods = $this->generateEntityStubMethods ? $this->generateEntityStubMethods($metadata) : null; - $lifecycleCallbackMethods = $this->generateEntityLifecycleCallbackMethods($metadata); + $stubMethods = $this->generateEntityStubMethods ? $this->generateEntityStubMethods($metadata) : null; + $lifecycleCallbackMethods = $this->generateEntityLifecycleCallbackMethods($metadata); $code = []; @@ -696,8 +713,6 @@ protected function generateEntityBody(ClassMetadataInfo $metadata) } /** - * @param ClassMetadataInfo $metadata - * * @return string */ protected function generateEntityConstructor(ClassMetadataInfo $metadata) @@ -714,28 +729,26 @@ protected function generateEntityConstructor(ClassMetadataInfo $metadata) foreach ($metadata->associationMappings as $mapping) { if ($mapping['type'] & ClassMetadataInfo::TO_MANY) { - $collections[] = '$this->'.$mapping['fieldName'].' = new \Doctrine\Common\Collections\ArrayCollection();'; + $collections[] = '$this->' . $mapping['fieldName'] . ' = new \Doctrine\Common\Collections\ArrayCollection();'; } } if ($collections) { - return $this->prefixCodeWithSpaces(str_replace("", implode("\n".$this->spaces, $collections), static::$constructorMethodTemplate)); + return $this->prefixCodeWithSpaces(str_replace('', implode("\n" . $this->spaces, $collections), static::$constructorMethodTemplate)); } return ''; } /** - * @param ClassMetadataInfo $metadata - * * @return string */ private function generateEmbeddableConstructor(ClassMetadataInfo $metadata) { - $paramTypes = []; + $paramTypes = []; $paramVariables = []; - $params = []; - $fields = []; + $params = []; + $fields = []; // Resort fields to put optional fields at the end of the method signature. $requiredFields = []; @@ -754,13 +767,13 @@ private function generateEmbeddableConstructor(ClassMetadataInfo $metadata) $fieldMappings = array_merge($requiredFields, $optionalFields); foreach ($metadata->embeddedClasses as $fieldName => $embeddedClass) { - $paramType = '\\' . ltrim($embeddedClass['class'], '\\'); + $paramType = '\\' . ltrim($embeddedClass['class'], '\\'); $paramVariable = '$' . $fieldName; - $paramTypes[] = $paramType; + $paramTypes[] = $paramType; $paramVariables[] = $paramVariable; - $params[] = $paramType . ' ' . $paramVariable; - $fields[] = '$this->' . $fieldName . ' = ' . $paramVariable . ';'; + $params[] = $paramType . ' ' . $paramVariable; + $fields[] = '$this->' . $fieldName . ' = ' . $paramVariable . ';'; } foreach ($fieldMappings as $fieldMapping) { @@ -768,15 +781,15 @@ private function generateEmbeddableConstructor(ClassMetadataInfo $metadata) continue; } - $paramTypes[] = $this->getType($fieldMapping['type']) . (!empty($fieldMapping['nullable']) ? '|null' : ''); - $param = '$' . $fieldMapping['fieldName']; + $paramTypes[] = $this->getType($fieldMapping['type']) . (! empty($fieldMapping['nullable']) ? '|null' : ''); + $param = '$' . $fieldMapping['fieldName']; $paramVariables[] = $param; if ($fieldMapping['type'] === 'datetime') { $param = $this->getType($fieldMapping['type']) . ' ' . $param; } - if (!empty($fieldMapping['nullable'])) { + if (! empty($fieldMapping['nullable'])) { $param .= ' = null'; } @@ -786,8 +799,8 @@ private function generateEmbeddableConstructor(ClassMetadataInfo $metadata) } $maxParamTypeLength = max(array_map('strlen', $paramTypes)); - $paramTags = array_map( - function ($type, $variable) use ($maxParamTypeLength) { + $paramTags = array_map( + static function ($type, $variable) use ($maxParamTypeLength) { return '@param ' . $type . str_repeat(' ', $maxParamTypeLength - strlen($type) + 1) . $variable; }, $paramTypes, @@ -797,7 +810,7 @@ function ($type, $variable) use ($maxParamTypeLength) { // Generate multi line constructor if the signature exceeds 120 characters. if (array_sum(array_map('strlen', $params)) + count($params) * 2 + 29 > 120) { $delimiter = "\n" . $this->spaces; - $params = $delimiter . implode(',' . $delimiter, $params) . "\n"; + $params = $delimiter . implode(',' . $delimiter, $params) . "\n"; } else { $params = implode(', ', $params); } @@ -818,23 +831,22 @@ function ($type, $variable) use ($maxParamTypeLength) { } /** - * @todo this won't work if there is a namespace in brackets and a class outside of it. - * - * @psalm-suppress UndefinedConstant - * * @param string $src * * @return void + * + * @todo this won't work if there is a namespace in brackets and a class outside of it. + * @psalm-suppress UndefinedConstant */ protected function parseTokensInEntityFile($src) { - $tokens = token_get_all($src); - $tokensCount = count($tokens); + $tokens = token_get_all($src); + $tokensCount = count($tokens); $lastSeenNamespace = ''; - $lastSeenClass = false; + $lastSeenClass = false; $inNamespace = false; - $inClass = false; + $inClass = false; for ($i = 0; $i < $tokensCount; $i++) { $token = $tokens[$i]; @@ -853,40 +865,39 @@ protected function parseTokensInEntityFile($src) } if ($inClass) { - $inClass = false; - $lastSeenClass = $lastSeenNamespace . ($lastSeenNamespace ? '\\' : '') . $token[1]; + $inClass = false; + $lastSeenClass = $lastSeenNamespace . ($lastSeenNamespace ? '\\' : '') . $token[1]; $this->staticReflection[$lastSeenClass]['properties'] = []; - $this->staticReflection[$lastSeenClass]['methods'] = []; + $this->staticReflection[$lastSeenClass]['methods'] = []; } - if (T_NAMESPACE === $token[0]) { + if ($token[0] === T_NAMESPACE) { $lastSeenNamespace = ''; - $inNamespace = true; - } elseif (T_CLASS === $token[0] && T_DOUBLE_COLON !== $tokens[$i-1][0]) { + $inNamespace = true; + } elseif ($token[0] === T_CLASS && $tokens[$i - 1][0] !== T_DOUBLE_COLON) { $inClass = true; - } elseif (T_FUNCTION === $token[0]) { - if (T_STRING === $tokens[$i+2][0]) { - $this->staticReflection[$lastSeenClass]['methods'][] = strtolower($tokens[$i+2][1]); - } elseif ($tokens[$i+2] == '&' && T_STRING === $tokens[$i+3][0]) { - $this->staticReflection[$lastSeenClass]['methods'][] = strtolower($tokens[$i+3][1]); + } elseif ($token[0] === T_FUNCTION) { + if ($tokens[$i + 2][0] === T_STRING) { + $this->staticReflection[$lastSeenClass]['methods'][] = strtolower($tokens[$i + 2][1]); + } elseif ($tokens[$i + 2] === '&' && $tokens[$i + 3][0] === T_STRING) { + $this->staticReflection[$lastSeenClass]['methods'][] = strtolower($tokens[$i + 3][1]); } - } elseif (in_array($token[0], [T_VAR, T_PUBLIC, T_PRIVATE, T_PROTECTED], true) && T_FUNCTION !== $tokens[$i+2][0]) { - $this->staticReflection[$lastSeenClass]['properties'][] = substr($tokens[$i+2][1], 1); + } elseif (in_array($token[0], [T_VAR, T_PUBLIC, T_PRIVATE, T_PROTECTED], true) && $tokens[$i + 2][0] !== T_FUNCTION) { + $this->staticReflection[$lastSeenClass]['properties'][] = substr($tokens[$i + 2][1], 1); } } } /** - * @param string $property - * @param ClassMetadataInfo $metadata + * @param string $property * * @return bool */ protected function hasProperty($property, ClassMetadataInfo $metadata) { - if ($this->extendsClass() || (!$this->isNew && class_exists($metadata->name))) { + if ($this->extendsClass() || (! $this->isNew && class_exists($metadata->name))) { // don't generate property if its already on the base class. - $reflClass = new \ReflectionClass($this->getClassToExtend() ?: $metadata->name); + $reflClass = new ReflectionClass($this->getClassToExtend() ?: $metadata->name); if ($reflClass->hasProperty($property)) { return true; } @@ -899,23 +910,20 @@ protected function hasProperty($property, ClassMetadataInfo $metadata) } } - return ( - isset($this->staticReflection[$metadata->name]) && - in_array($property, $this->staticReflection[$metadata->name]['properties'], true) - ); + return isset($this->staticReflection[$metadata->name]) && + in_array($property, $this->staticReflection[$metadata->name]['properties'], true); } /** - * @param string $method - * @param ClassMetadataInfo $metadata + * @param string $method * * @return bool */ protected function hasMethod($method, ClassMetadataInfo $metadata) { - if ($this->extendsClass() || (!$this->isNew && class_exists($metadata->name))) { + if ($this->extendsClass() || (! $this->isNew && class_exists($metadata->name))) { // don't generate method if its already on the base class. - $reflClass = new \ReflectionClass($this->getClassToExtend() ?: $metadata->name); + $reflClass = new ReflectionClass($this->getClassToExtend() ?: $metadata->name); if ($reflClass->hasMethod($method)) { return true; @@ -929,18 +937,14 @@ protected function hasMethod($method, ClassMetadataInfo $metadata) } } - return ( - isset($this->staticReflection[$metadata->name]) && - in_array(strtolower($method), $this->staticReflection[$metadata->name]['methods'], true) - ); + return isset($this->staticReflection[$metadata->name]) && + in_array(strtolower($method), $this->staticReflection[$metadata->name]['methods'], true); } /** - * @param ClassMetadataInfo $metadata - * * @return ReflectionClass[] * - * @throws \ReflectionException + * @throws ReflectionException * * @psalm-return array */ @@ -950,7 +954,7 @@ protected function getTraits(ClassMetadataInfo $metadata) return []; } - $reflClass = $metadata->reflClass ?? new \ReflectionClass($metadata->name); + $reflClass = $metadata->reflClass ?? new ReflectionClass($metadata->name); $traits = []; @@ -964,8 +968,6 @@ protected function getTraits(ClassMetadataInfo $metadata) } /** - * @param ClassMetadataInfo $metadata - * * @return bool */ protected function hasNamespace(ClassMetadataInfo $metadata) @@ -994,14 +996,12 @@ protected function getClassToExtend() */ protected function getClassToExtendName() { - $refl = new \ReflectionClass($this->getClassToExtend()); + $refl = new ReflectionClass($this->getClassToExtend()); return '\\' . $refl->getName(); } /** - * @param ClassMetadataInfo $metadata - * * @return string */ protected function getClassName(ClassMetadataInfo $metadata) @@ -1011,8 +1011,6 @@ protected function getClassName(ClassMetadataInfo $metadata) } /** - * @param ClassMetadataInfo $metadata - * * @return string */ protected function getNamespace(ClassMetadataInfo $metadata) @@ -1021,13 +1019,11 @@ protected function getNamespace(ClassMetadataInfo $metadata) } /** - * @param ClassMetadataInfo $metadata - * * @return string */ protected function generateEntityDocBlock(ClassMetadataInfo $metadata) { - $lines = []; + $lines = []; $lines[] = '/**'; $lines[] = ' * ' . $this->getClassName($metadata); @@ -1060,8 +1056,6 @@ protected function generateEntityDocBlock(ClassMetadataInfo $metadata) } /** - * @param ClassMetadataInfo $metadata - * * @return string */ protected function generateEntityAnnotation(ClassMetadataInfo $metadata) @@ -1080,8 +1074,6 @@ protected function generateEntityAnnotation(ClassMetadataInfo $metadata) } /** - * @param ClassMetadataInfo $metadata - * * @return string */ protected function generateTableAnnotation(ClassMetadataInfo $metadata) @@ -1106,12 +1098,12 @@ protected function generateTableAnnotation(ClassMetadataInfo $metadata) if (isset($metadata->table['uniqueConstraints']) && $metadata->table['uniqueConstraints']) { $constraints = $this->generateTableConstraints('UniqueConstraint', $metadata->table['uniqueConstraints']); - $table[] = 'uniqueConstraints={' . $constraints . '}'; + $table[] = 'uniqueConstraints={' . $constraints . '}'; } if (isset($metadata->table['indexes']) && $metadata->table['indexes']) { $constraints = $this->generateTableConstraints('Index', $metadata->table['indexes']); - $table[] = 'indexes={' . $constraints . '}'; + $table[] = 'indexes={' . $constraints . '}'; } return '@' . $this->annotationsPrefix . 'Table(' . implode(', ', $table) . ')'; @@ -1131,6 +1123,7 @@ protected function generateTableConstraints($constraintName, array $constraints) foreach ($constraint['columns'] as $column) { $columns[] = '"' . $column . '"'; } + $annotations[] = '@' . $this->annotationsPrefix . $constraintName . '(name="' . $name . '", columns={' . implode(', ', $columns) . '})'; } @@ -1138,8 +1131,6 @@ protected function generateTableConstraints($constraintName, array $constraints) } /** - * @param ClassMetadataInfo $metadata - * * @return string */ protected function generateInheritanceAnnotation(ClassMetadataInfo $metadata) @@ -1148,12 +1139,10 @@ protected function generateInheritanceAnnotation(ClassMetadataInfo $metadata) return ''; } - return '@' . $this->annotationsPrefix . 'InheritanceType("'.$this->getInheritanceTypeString($metadata->inheritanceType).'")'; + return '@' . $this->annotationsPrefix . 'InheritanceType("' . $this->getInheritanceTypeString($metadata->inheritanceType) . '")'; } /** - * @param ClassMetadataInfo $metadata - * * @return string */ protected function generateDiscriminatorColumnAnnotation(ClassMetadataInfo $metadata) @@ -1162,7 +1151,7 @@ protected function generateDiscriminatorColumnAnnotation(ClassMetadataInfo $meta return ''; } - $discrColumn = $metadata->discriminatorColumn; + $discrColumn = $metadata->discriminatorColumn; $columnDefinition = 'name="' . $discrColumn['name'] . '", type="' . $discrColumn['type'] . '", length=' . $discrColumn['length']; @@ -1171,8 +1160,6 @@ protected function generateDiscriminatorColumnAnnotation(ClassMetadataInfo $meta } /** - * @param ClassMetadataInfo $metadata - * * @return string|null */ protected function generateDiscriminatorMapAnnotation(ClassMetadataInfo $metadata) @@ -1191,8 +1178,6 @@ protected function generateDiscriminatorMapAnnotation(ClassMetadataInfo $metadat } /** - * @param ClassMetadataInfo $metadata - * * @return string */ protected function generateEntityStubMethods(ClassMetadataInfo $metadata) @@ -1206,8 +1191,9 @@ protected function generateEntityStubMethods(ClassMetadataInfo $metadata) $nullableField = $this->nullableFieldExpression($fieldMapping); - if ((!$metadata->isEmbeddedClass || !$this->embeddablesImmutable) - && (!isset($fieldMapping['id']) || ! $fieldMapping['id'] || $metadata->generatorType === ClassMetadataInfo::GENERATOR_TYPE_NONE) + if ( + (! $metadata->isEmbeddedClass || ! $this->embeddablesImmutable) + && (! isset($fieldMapping['id']) || ! $fieldMapping['id'] || $metadata->generatorType === ClassMetadataInfo::GENERATOR_TYPE_NONE) && $code = $this->generateEntityStubMethod($metadata, 'set', $fieldMapping['fieldName'], $fieldMapping['type'], $nullableField) ) { $methods[] = $code; @@ -1223,7 +1209,7 @@ protected function generateEntityStubMethods(ClassMetadataInfo $metadata) continue; } - if ( ! $metadata->isEmbeddedClass || ! $this->embeddablesImmutable) { + if (! $metadata->isEmbeddedClass || ! $this->embeddablesImmutable) { if ($code = $this->generateEntityStubMethod($metadata, 'set', $fieldName, $embeddedClass['class'])) { $methods[] = $code; } @@ -1240,6 +1226,7 @@ protected function generateEntityStubMethods(ClassMetadataInfo $metadata) if ($code = $this->generateEntityStubMethod($metadata, 'set', $associationMapping['fieldName'], $associationMapping['targetEntity'], $nullable)) { $methods[] = $code; } + if ($code = $this->generateEntityStubMethod($metadata, 'get', $associationMapping['fieldName'], $associationMapping['targetEntity'], $nullable)) { $methods[] = $code; } @@ -1247,9 +1234,11 @@ protected function generateEntityStubMethods(ClassMetadataInfo $metadata) if ($code = $this->generateEntityStubMethod($metadata, 'add', $associationMapping['fieldName'], $associationMapping['targetEntity'])) { $methods[] = $code; } + if ($code = $this->generateEntityStubMethod($metadata, 'remove', $associationMapping['fieldName'], $associationMapping['targetEntity'])) { $methods[] = $code; } + if ($code = $this->generateEntityStubMethod($metadata, 'get', $associationMapping['fieldName'], Collection::class)) { $methods[] = $code; } @@ -1278,7 +1267,7 @@ protected function isAssociationIsNullable(array $associationMapping) } foreach ($joinColumns as $joinColumn) { - if (isset($joinColumn['nullable']) && !$joinColumn['nullable']) { + if (isset($joinColumn['nullable']) && ! $joinColumn['nullable']) { return false; } } @@ -1287,8 +1276,6 @@ protected function isAssociationIsNullable(array $associationMapping) } /** - * @param ClassMetadataInfo $metadata - * * @return string */ protected function generateEntityLifecycleCallbackMethods(ClassMetadataInfo $metadata) @@ -1309,8 +1296,6 @@ protected function generateEntityLifecycleCallbackMethods(ClassMetadataInfo $met } /** - * @param ClassMetadataInfo $metadata - * * @return string */ protected function generateEntityAssociationMappingProperties(ClassMetadataInfo $metadata) @@ -1324,15 +1309,13 @@ protected function generateEntityAssociationMappingProperties(ClassMetadataInfo $lines[] = $this->generateAssociationMappingPropertyDocBlock($associationMapping, $metadata); $lines[] = $this->spaces . $this->fieldVisibility . ' $' . $associationMapping['fieldName'] - . ($associationMapping['type'] == 'manyToMany' ? ' = array()' : null) . ";\n"; + . ($associationMapping['type'] === 'manyToMany' ? ' = array()' : null) . ";\n"; } return implode("\n", $lines); } /** - * @param ClassMetadataInfo $metadata - * * @return string */ protected function generateEntityFieldMappingProperties(ClassMetadataInfo $metadata) @@ -1340,7 +1323,8 @@ protected function generateEntityFieldMappingProperties(ClassMetadataInfo $metad $lines = []; foreach ($metadata->fieldMappings as $fieldMapping) { - if (isset($fieldMapping['declaredField'], $metadata->embeddedClasses[$fieldMapping['declaredField']]) || + if ( + isset($fieldMapping['declaredField'], $metadata->embeddedClasses[$fieldMapping['declaredField']]) || $this->hasProperty($fieldMapping['fieldName'], $metadata) || $metadata->isInheritedField($fieldMapping['fieldName']) ) { @@ -1364,8 +1348,6 @@ protected function generateEntityFieldMappingProperties(ClassMetadataInfo $metad } /** - * @param ClassMetadataInfo $metadata - * * @return string */ protected function generateEntityEmbeddedProperties(ClassMetadataInfo $metadata) @@ -1385,11 +1367,10 @@ protected function generateEntityEmbeddedProperties(ClassMetadataInfo $metadata) } /** - * @param ClassMetadataInfo $metadata - * @param string $type - * @param string $fieldName - * @param string|null $typeHint - * @param string|null $defaultValue + * @param string $type + * @param string $fieldName + * @param string|null $typeHint + * @param string|null $defaultValue * * @return string */ @@ -1398,7 +1379,7 @@ protected function generateEntityStubMethod(ClassMetadataInfo $metadata, $type, $methodName = $type . $this->inflector->classify($fieldName); $variableName = $this->inflector->camelize($fieldName); - if (in_array($type, ["add", "remove"])) { + if (in_array($type, ['add', 'remove'])) { $methodName = $this->inflector->singularize($methodName); $variableName = $this->inflector->singularize($variableName); } @@ -1406,9 +1387,10 @@ protected function generateEntityStubMethod(ClassMetadataInfo $metadata, $type, if ($this->hasMethod($methodName, $metadata)) { return ''; } + $this->staticReflection[$metadata->name]['methods'][] = strtolower($methodName); - $var = sprintf('%sMethodTemplate', $type); + $var = sprintf('%sMethodTemplate', $type); $template = static::$$var; $methodTypeHint = null; @@ -1421,14 +1403,14 @@ protected function generateEntityStubMethod(ClassMetadataInfo $metadata, $type, } $replacements = [ - '' => ucfirst($type) . ' ' . $variableName . '.', - '' => $methodTypeHint, - '' => $variableType . (null !== $defaultValue ? ('|' . $defaultValue) : ''), - '' => $variableName, - '' => $methodName, - '' => $fieldName, - '' => ($defaultValue !== null ) ? (' = ' . $defaultValue) : '', - '' => $this->getClassName($metadata) + '' => ucfirst($type) . ' ' . $variableName . '.', + '' => $methodTypeHint, + '' => $variableType . ($defaultValue !== null ? '|' . $defaultValue : ''), + '' => $variableName, + '' => $methodName, + '' => $fieldName, + '' => $defaultValue !== null ? ' = ' . $defaultValue : '', + '' => $this->getClassName($metadata), ]; $method = str_replace( @@ -1441,9 +1423,8 @@ protected function generateEntityStubMethod(ClassMetadataInfo $metadata, $type, } /** - * @param string $name - * @param string $methodName - * @param ClassMetadataInfo $metadata + * @param string $name + * @param string $methodName * * @return string */ @@ -1495,7 +1476,7 @@ protected function generateJoinColumnAnnotation(array $joinColumn) } if (isset($joinColumn['onDelete'])) { - $joinColumnAnnot[] = 'onDelete="' . ($joinColumn['onDelete'] . '"'); + $joinColumnAnnot[] = 'onDelete="' . $joinColumn['onDelete'] . '"'; } if (isset($joinColumn['columnDefinition'])) { @@ -1506,14 +1487,13 @@ protected function generateJoinColumnAnnotation(array $joinColumn) } /** - * @param array $associationMapping - * @param ClassMetadataInfo $metadata + * @param array $associationMapping * * @return string */ protected function generateAssociationMappingPropertyDocBlock(array $associationMapping, ClassMetadataInfo $metadata) { - $lines = []; + $lines = []; $lines[] = $this->spaces . '/**'; if ($associationMapping['type'] & ClassMetadataInfo::TO_MANY) { @@ -1548,6 +1528,7 @@ protected function generateAssociationMappingPropertyDocBlock(array $association $type = 'ManyToMany'; break; } + $typeOptions = []; if (isset($associationMapping['targetEntity'])) { @@ -1565,11 +1546,25 @@ protected function generateAssociationMappingPropertyDocBlock(array $association if ($associationMapping['cascade']) { $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"'; + 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"'; + } if (count($cascades) === 5) { $cascades = ['"all"']; @@ -1609,7 +1604,7 @@ protected function generateAssociationMappingPropertyDocBlock(array $association } if (isset($associationMapping['joinTable']) && $associationMapping['joinTable']) { - $joinTable = []; + $joinTable = []; $joinTable[] = 'name="' . $associationMapping['joinTable']['name'] . '"'; if (isset($associationMapping['joinTable']['schema'])) { @@ -1625,7 +1620,7 @@ protected function generateAssociationMappingPropertyDocBlock(array $association $joinColumnsLines[] = $this->spaces . ' * ' . $this->generateJoinColumnAnnotation($joinColumn); } - $lines[] = implode(",". PHP_EOL, $joinColumnsLines); + $lines[] = implode(',' . PHP_EOL, $joinColumnsLines); $lines[] = $this->spaces . ' * },'; $lines[] = $this->spaces . ' * inverseJoinColumns={'; @@ -1635,7 +1630,7 @@ protected function generateAssociationMappingPropertyDocBlock(array $association $inverseJoinColumnsLines[] = $this->spaces . ' * ' . $this->generateJoinColumnAnnotation($joinColumn); } - $lines[] = implode(",". PHP_EOL, $inverseJoinColumnsLines); + $lines[] = implode(',' . PHP_EOL, $inverseJoinColumnsLines); $lines[] = $this->spaces . ' * }'; $lines[] = $this->spaces . ' * )'; } @@ -1648,7 +1643,7 @@ protected function generateAssociationMappingPropertyDocBlock(array $association } $lines[count($lines) - 1] = substr($lines[count($lines) - 1], 0, strlen($lines[count($lines) - 1]) - 1); - $lines[] = $this->spaces . ' * })'; + $lines[] = $this->spaces . ' * })'; } } @@ -1658,14 +1653,13 @@ protected function generateAssociationMappingPropertyDocBlock(array $association } /** - * @param array $fieldMapping - * @param ClassMetadataInfo $metadata + * @param array $fieldMapping * * @return string */ protected function generateFieldMappingPropertyDocBlock(array $fieldMapping, ClassMetadataInfo $metadata) { - $lines = []; + $lines = []; $lines[] = $this->spaces . '/**'; $lines[] = $this->spaces . ' * @var ' . $this->getType($fieldMapping['type']) @@ -1688,7 +1682,7 @@ protected function generateFieldMappingPropertyDocBlock(array $fieldMapping, Cla } if (isset($fieldMapping['precision'])) { - $column[] = 'precision=' . $fieldMapping['precision']; + $column[] = 'precision=' . $fieldMapping['precision']; } if (isset($fieldMapping['scale'])) { @@ -1696,13 +1690,13 @@ protected function generateFieldMappingPropertyDocBlock(array $fieldMapping, Cla } if (isset($fieldMapping['nullable'])) { - $column[] = 'nullable=' . var_export($fieldMapping['nullable'], true); + $column[] = 'nullable=' . var_export($fieldMapping['nullable'], true); } $options = []; if (isset($fieldMapping['options']['default']) && $fieldMapping['options']['default']) { - $options[] = '"default"="' . $fieldMapping['options']['default'] .'"'; + $options[] = '"default"="' . $fieldMapping['options']['default'] . '"'; } if (isset($fieldMapping['options']['unsigned']) && $fieldMapping['options']['unsigned']) { @@ -1718,15 +1712,15 @@ protected function generateFieldMappingPropertyDocBlock(array $fieldMapping, Cla } if (isset($fieldMapping['options']['collation']) && $fieldMapping['options']['collation']) { - $options[] = '"collation"="' . $fieldMapping['options']['collation'] .'"'; + $options[] = '"collation"="' . $fieldMapping['options']['collation'] . '"'; } if (isset($fieldMapping['options']['check']) && $fieldMapping['options']['check']) { - $options[] = '"check"="' . $fieldMapping['options']['check'] .'"'; + $options[] = '"check"="' . $fieldMapping['options']['check'] . '"'; } if ($options) { - $column[] = 'options={'.implode(',', $options).'}'; + $column[] = 'options={' . implode(',', $options) . '}'; } if (isset($fieldMapping['columnDefinition'])) { @@ -1743,7 +1737,7 @@ protected function generateFieldMappingPropertyDocBlock(array $fieldMapping, Cla $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'Id'; if ($generatorType = $this->getIdGeneratorTypeString($metadata->generatorType)) { - $lines[] = $this->spaces.' * @' . $this->annotationsPrefix . 'GeneratedValue(strategy="' . $generatorType . '")'; + $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'GeneratedValue(strategy="' . $generatorType . '")'; } if ($metadata->sequenceGeneratorDefinition) { @@ -1782,7 +1776,7 @@ protected function generateFieldMappingPropertyDocBlock(array $fieldMapping, Cla */ protected function generateEmbeddedPropertyDocBlock(array $embeddedClass) { - $lines = []; + $lines = []; $lines[] = $this->spaces . '/**'; $lines[] = $this->spaces . ' * @var \\' . ltrim($embeddedClass['class'], '\\'); @@ -1810,7 +1804,7 @@ protected function generateEmbeddedPropertyDocBlock(array $embeddedClass) private function generateEntityListenerAnnotation(ClassMetadataInfo $metadata): string { - if (0 === \count($metadata->entityListeners)) { + if (count($metadata->entityListeners) === 0) { return ''; } @@ -1821,11 +1815,11 @@ private function generateEntityListenerAnnotation(ClassMetadataInfo $metadata): } } - return \sprintf( + return sprintf( '%s%s({%s})', '@' . $this->annotationsPrefix, 'EntityListeners', - \implode(',', \array_unique($processedClasses)) + implode(',', array_unique($processedClasses)) ); } @@ -1840,7 +1834,7 @@ protected function prefixCodeWithSpaces($code, $num = 1) $lines = explode("\n", $code); foreach ($lines as $key => $value) { - if ( ! empty($value)) { + if (! empty($value)) { $lines[$key] = str_repeat($this->spaces, $num) . $lines[$key]; } } @@ -1849,48 +1843,48 @@ protected function prefixCodeWithSpaces($code, $num = 1) } /** - * @param integer $type The inheritance type used by the class and its subclasses. + * @param int $type The inheritance type used by the class and its subclasses. * * @return string The literal string for the inheritance type. * - * @throws \InvalidArgumentException When the inheritance type does not exist. + * @throws InvalidArgumentException When the inheritance type does not exist. */ protected function getInheritanceTypeString($type) { - if ( ! isset(static::$inheritanceTypeMap[$type])) { - throw new \InvalidArgumentException(sprintf('Invalid provided InheritanceType: %s', $type)); + if (! isset(static::$inheritanceTypeMap[$type])) { + throw new InvalidArgumentException(sprintf('Invalid provided InheritanceType: %s', $type)); } return static::$inheritanceTypeMap[$type]; } /** - * @param integer $type The policy used for change-tracking for the mapped class. + * @param int $type The policy used for change-tracking for the mapped class. * * @return string The literal string for the change-tracking type. * - * @throws \InvalidArgumentException When the change-tracking type does not exist. + * @throws InvalidArgumentException When the change-tracking type does not exist. */ protected function getChangeTrackingPolicyString($type) { - if ( ! isset(static::$changeTrackingPolicyMap[$type])) { - throw new \InvalidArgumentException(sprintf('Invalid provided ChangeTrackingPolicy: %s', $type)); + if (! isset(static::$changeTrackingPolicyMap[$type])) { + throw new InvalidArgumentException(sprintf('Invalid provided ChangeTrackingPolicy: %s', $type)); } return static::$changeTrackingPolicyMap[$type]; } /** - * @param integer $type The generator to use for the mapped class. + * @param int $type The generator to use for the mapped class. * * @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])) { - throw new \InvalidArgumentException(sprintf('Invalid provided IdGeneratorType: %s', $type)); + if (! isset(static::$generatorStrategyMap[$type])) { + throw new InvalidArgumentException(sprintf('Invalid provided IdGeneratorType: %s', $type)); } return static::$generatorStrategyMap[$type]; @@ -1903,7 +1897,7 @@ protected function getIdGeneratorTypeString($type) */ private function nullableFieldExpression(array $fieldMapping) { - if (isset($fieldMapping['nullable']) && true === $fieldMapping['nullable']) { + if (isset($fieldMapping['nullable']) && $fieldMapping['nullable'] === true) { return 'null'; } diff --git a/lib/Doctrine/ORM/Tools/EntityRepositoryGenerator.php b/lib/Doctrine/ORM/Tools/EntityRepositoryGenerator.php index 753ca550c19..afb00975dac 100644 --- a/lib/Doctrine/ORM/Tools/EntityRepositoryGenerator.php +++ b/lib/Doctrine/ORM/Tools/EntityRepositoryGenerator.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - * - * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement */ class EntityRepositoryGenerator { private $repositoryName; protected static $_template = -' @@ -71,7 +81,7 @@ public function generateEntityRepositoryClass($fullClassName) $variables = [ '' => $this->generateEntityRepositoryNamespace($fullClassName), '' => $this->generateEntityRepositoryName($fullClassName), - '' => $this->generateClassName($fullClassName) + '' => $this->generateClassName($fullClassName), ]; return str_replace(array_keys($variables), array_values($variables), self::$_template); @@ -86,9 +96,7 @@ public function generateEntityRepositoryClass($fullClassName) */ private function getClassNamespace($fullClassName) { - $namespace = substr($fullClassName, 0, strrpos($fullClassName, '\\')); - - return $namespace; + return substr($fullClassName, 0, strrpos($fullClassName, '\\')); } /** @@ -154,14 +162,14 @@ public function writeEntityRepositoryClass($fullClassName, $outputDirectory) $code = $this->generateEntityRepositoryClass($fullClassName); $path = $outputDirectory . DIRECTORY_SEPARATOR - . str_replace('\\', \DIRECTORY_SEPARATOR, $fullClassName) . '.php'; - $dir = dirname($path); + . str_replace('\\', DIRECTORY_SEPARATOR, $fullClassName) . '.php'; + $dir = dirname($path); - if ( ! is_dir($dir)) { + if (! is_dir($dir)) { mkdir($dir, 0775, true); } - if ( ! file_exists($path)) { + if (! file_exists($path)) { file_put_contents($path, $code); chmod($path, 0664); } @@ -178,5 +186,4 @@ public function setDefaultRepositoryName($repositoryName) return $this; } - } diff --git a/lib/Doctrine/ORM/Tools/Event/GenerateSchemaEventArgs.php b/lib/Doctrine/ORM/Tools/Event/GenerateSchemaEventArgs.php index ed03e32d9dc..16be9c9e6e7 100644 --- a/lib/Doctrine/ORM/Tools/Event/GenerateSchemaEventArgs.php +++ b/lib/Doctrine/ORM/Tools/Event/GenerateSchemaEventArgs.php @@ -1,4 +1,5 @@ */ class GenerateSchemaEventArgs extends EventArgs { - /** - * @var \Doctrine\ORM\EntityManagerInterface - */ + /** @var EntityManagerInterface */ private $em; - /** - * @var \Doctrine\DBAL\Schema\Schema - */ + /** @var Schema */ private $schema; - /** - * @param EntityManagerInterface $em - * @param Schema $schema - */ public function __construct(EntityManagerInterface $em, Schema $schema) { - $this->em = $em; + $this->em = $em; $this->schema = $schema; } diff --git a/lib/Doctrine/ORM/Tools/Event/GenerateSchemaTableEventArgs.php b/lib/Doctrine/ORM/Tools/Event/GenerateSchemaTableEventArgs.php index e2c38f9c592..9c468326edf 100644 --- a/lib/Doctrine/ORM/Tools/Event/GenerateSchemaTableEventArgs.php +++ b/lib/Doctrine/ORM/Tools/Event/GenerateSchemaTableEventArgs.php @@ -1,4 +1,5 @@ . */ + namespace Doctrine\ORM\Tools\Event; use Doctrine\Common\EventArgs; -use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\Table; +use Doctrine\ORM\Mapping\ClassMetadata; /** * Event Args used for the Events::postGenerateSchemaTable event. * - * @license http://www.opensource.org/licenses/mit-license.php MIT * @link www.doctrine-project.com - * @since 1.0 - * @author Benjamin Eberlei */ class GenerateSchemaTableEventArgs extends EventArgs { - /** - * @var \Doctrine\ORM\Mapping\ClassMetadata - */ + /** @var ClassMetadata */ private $classMetadata; - /** - * @var \Doctrine\DBAL\Schema\Schema - */ + /** @var Schema */ private $schema; - /** - * @var \Doctrine\DBAL\Schema\Table - */ + /** @var Table */ private $classTable; - /** - * @param ClassMetadata $classMetadata - * @param Schema $schema - * @param Table $classTable - */ public function __construct(ClassMetadata $classMetadata, Schema $schema, Table $classTable) { $this->classMetadata = $classMetadata; - $this->schema = $schema; - $this->classTable = $classTable; + $this->schema = $schema; + $this->classTable = $classTable; } /** diff --git a/lib/Doctrine/ORM/Tools/Export/ClassMetadataExporter.php b/lib/Doctrine/ORM/Tools/Export/ClassMetadataExporter.php index 15c03b5c5af..dae2d2e07bc 100644 --- a/lib/Doctrine/ORM/Tools/Export/ClassMetadataExporter.php +++ b/lib/Doctrine/ORM/Tools/Export/ClassMetadataExporter.php @@ -1,4 +1,5 @@ - * * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement + * + * @link www.doctrine-project.org */ class ClassMetadataExporter { - /** - * @var array - */ + /** @var array */ private static $_exporterDrivers = [ 'xml' => Driver\XmlExporter::class, 'yaml' => Driver\YamlExporter::class, 'yml' => Driver\YamlExporter::class, 'php' => Driver\PhpExporter::class, - 'annotation' => Driver\AnnotationExporter::class + 'annotation' => Driver\AnnotationExporter::class, ]; public function __construct() @@ -75,7 +73,7 @@ public static function registerExportDriver($name, $class) */ public function getExporter($type, $dest = null) { - if ( ! isset(self::$_exporterDrivers[$type])) { + if (! isset(self::$_exporterDrivers[$type])) { throw ExportException::invalidExporterDriverType($type); } diff --git a/lib/Doctrine/ORM/Tools/Export/Driver/AbstractExporter.php b/lib/Doctrine/ORM/Tools/Export/Driver/AbstractExporter.php index 5ed79f6e769..d83673b4b2e 100644 --- a/lib/Doctrine/ORM/Tools/Export/Driver/AbstractExporter.php +++ b/lib/Doctrine/ORM/Tools/Export/Driver/AbstractExporter.php @@ -1,4 +1,5 @@ - * * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement + * + * @link www.doctrine-project.org */ abstract class AbstractExporter { - /** - * @var array - */ + /** @var array */ protected $_metadata = []; - /** - * @var string|null - */ + /** @var string|null */ protected $_outputDir; - /** - * @var string|null - */ + /** @var string|null */ protected $_extension; - /** - * @var bool - */ + /** @var bool */ protected $_overwriteExistingFiles = false; /** @@ -80,8 +80,6 @@ public function setOverwriteExistingFiles($overwrite) * Converts a single ClassMetadata instance to the exported format * and returns it. * - * @param ClassMetadataInfo $metadata - * * @return string */ abstract public function exportClassMetadata(ClassMetadataInfo $metadata); @@ -131,11 +129,11 @@ public function setOutputDir($dir) * * @return void * - * @throws \Doctrine\ORM\Tools\Export\ExportException + * @throws ExportException */ public function export() { - if ( ! is_dir($this->_outputDir)) { + if (! is_dir($this->_outputDir)) { mkdir($this->_outputDir, 0775, true); } @@ -143,13 +141,15 @@ public function export() // In case output is returned, write it to a file, skip otherwise if ($output = $this->exportClassMetadata($metadata)) { $path = $this->_generateOutputPath($metadata); - $dir = dirname($path); - if ( ! is_dir($dir)) { + $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); chmod($path, 0664); } @@ -159,8 +159,6 @@ public function export() /** * Generates the path to write the class for the given ClassMetadataInfo instance. * - * @param ClassMetadataInfo $metadata - * * @return string */ protected function _generateOutputPath(ClassMetadataInfo $metadata) diff --git a/lib/Doctrine/ORM/Tools/Export/Driver/AnnotationExporter.php b/lib/Doctrine/ORM/Tools/Export/Driver/AnnotationExporter.php index 29cb8df3633..77d13eb9702 100644 --- a/lib/Doctrine/ORM/Tools/Export/Driver/AnnotationExporter.php +++ b/lib/Doctrine/ORM/Tools/Export/Driver/AnnotationExporter.php @@ -1,4 +1,5 @@ - * * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement + * + * @link www.doctrine-project.org */ class AnnotationExporter extends AbstractExporter { - /** - * @var string - */ + /** @var string */ protected $_extension = '.php'; - /** - * @var EntityGenerator|null - */ + /** @var EntityGenerator|null */ private $_entityGenerator; /** @@ -48,8 +46,8 @@ class AnnotationExporter extends AbstractExporter */ public function exportClassMetadata(ClassMetadataInfo $metadata) { - if ( ! $this->_entityGenerator) { - throw new \RuntimeException('For the AnnotationExporter you must set an EntityGenerator instance with the setEntityGenerator() method.'); + if (! $this->_entityGenerator) { + throw new RuntimeException('For the AnnotationExporter you must set an EntityGenerator instance with the setEntityGenerator() method.'); } $this->_entityGenerator->setGenerateAnnotations(true); @@ -61,8 +59,6 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) } /** - * @param ClassMetadataInfo $metadata - * * @return string */ protected function _generateOutputPath(ClassMetadataInfo $metadata) @@ -71,8 +67,6 @@ protected function _generateOutputPath(ClassMetadataInfo $metadata) } /** - * @param EntityGenerator $entityGenerator - * * @return void */ public function setEntityGenerator(EntityGenerator $entityGenerator) diff --git a/lib/Doctrine/ORM/Tools/Export/Driver/PhpExporter.php b/lib/Doctrine/ORM/Tools/Export/Driver/PhpExporter.php index 90c75dc9696..f1d19dd54e0 100644 --- a/lib/Doctrine/ORM/Tools/Export/Driver/PhpExporter.php +++ b/lib/Doctrine/ORM/Tools/Export/Driver/PhpExporter.php @@ -1,4 +1,5 @@ - * * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement + * + * @link www.doctrine-project.org */ class PhpExporter extends AbstractExporter { - /** - * @var string - */ + /** @var string */ protected $_extension = '.php'; /** @@ -42,7 +50,7 @@ class PhpExporter extends AbstractExporter */ public function exportClassMetadata(ClassMetadataInfo $metadata) { - $lines = []; + $lines = []; $lines[] = 'mapField(' . $this->_varExport($fieldMapping) . ');'; } - if ( ! $metadata->isIdentifierComposite && $generatorType = $this->_getIdGeneratorTypeString($metadata->generatorType)) { + if (! $metadata->isIdentifierComposite && $generatorType = $this->_getIdGeneratorTypeString($metadata->generatorType)) { $lines[] = '$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_' . $generatorType . ');'; } foreach ($metadata->associationMappings as $associationMapping) { $cascade = ['remove', 'persist', 'refresh', 'merge', 'detach']; foreach ($cascade as $key => $value) { - if ( ! $associationMapping['isCascade'.ucfirst($value)]) { + if (! $associationMapping['isCascade' . ucfirst($value)]) { unset($cascade[$key]); } } @@ -106,7 +114,7 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) $cascade = ['all']; } - $method = null; + $method = null; $associationMappingArray = [ 'fieldName' => $associationMapping['fieldName'], 'targetEntity' => $associationMapping['targetEntity'], @@ -118,7 +126,7 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) } if ($associationMapping['type'] & ClassMetadataInfo::TO_ONE) { - $method = 'mapOneToOne'; + $method = 'mapOneToOne'; $oneToOneMappingArray = [ 'mappedBy' => $associationMapping['mappedBy'], 'inversedBy' => $associationMapping['inversedBy'], @@ -127,33 +135,35 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) ]; $associationMappingArray = array_merge($associationMappingArray, $oneToOneMappingArray); - } elseif ($associationMapping['type'] == ClassMetadataInfo::ONE_TO_MANY) { - $method = 'mapOneToMany'; + } elseif ($associationMapping['type'] === ClassMetadataInfo::ONE_TO_MANY) { + $method = 'mapOneToMany'; $potentialAssociationMappingIndexes = [ 'mappedBy', 'orphanRemoval', 'orderBy', ]; - $oneToManyMappingArray = []; + $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'; + } elseif ($associationMapping['type'] === ClassMetadataInfo::MANY_TO_MANY) { + $method = 'mapManyToMany'; $potentialAssociationMappingIndexes = [ 'mappedBy', 'joinTable', 'orderBy', ]; - $manyToManyMappingArray = []; + $manyToManyMappingArray = []; foreach ($potentialAssociationMappingIndexes as $index) { if (isset($associationMapping[$index])) { $manyToManyMappingArray[$index] = $associationMapping[$index]; } } + $associationMappingArray = array_merge($associationMappingArray, $manyToManyMappingArray); } @@ -187,17 +197,17 @@ protected function _varExport($var) * * @psalm-return list */ - private function processEntityListeners(ClassMetadataInfo $metadata) : array + private function processEntityListeners(ClassMetadataInfo $metadata): array { $lines = []; foreach ($metadata->entityListeners as $event => $entityListenerConfig) { foreach ($entityListenerConfig as $entityListener) { - $lines[] = \sprintf( + $lines[] = sprintf( '$metadata->addEntityListener(%s, %s, %s);', - \var_export($event, true), - \var_export($entityListener['class'], true), - \var_export($entityListener['method'], true) + var_export($event, true), + var_export($entityListener['class'], true), + var_export($entityListener['method'], true) ); } } diff --git a/lib/Doctrine/ORM/Tools/Export/Driver/XmlExporter.php b/lib/Doctrine/ORM/Tools/Export/Driver/XmlExporter.php index ec0f7ef9fdd..3585d8e0e27 100644 --- a/lib/Doctrine/ORM/Tools/Export/Driver/XmlExporter.php +++ b/lib/Doctrine/ORM/Tools/Export/Driver/XmlExporter.php @@ -1,4 +1,5 @@ - * * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement + * + * @link www.doctrine-project.org */ class XmlExporter extends AbstractExporter { - /** - * @var string - */ + /** @var string */ protected $_extension = '.dcm.xml'; /** @@ -100,7 +105,7 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) $trackingPolicy = $this->_getChangeTrackingPolicyString($metadata->changeTrackingPolicy); - if ( $trackingPolicy != 'DEFERRED_IMPLICIT') { + if ($trackingPolicy !== 'DEFERRED_IMPLICIT') { $root->addChild('change-tracking-policy', $trackingPolicy); } @@ -141,12 +146,12 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) if (isset($assoc['id']) && $assoc['id']) { $id[$name] = [ 'fieldName' => $name, - 'associationKey' => true + 'associationKey' => true, ]; } } - if ( ! $metadata->isIdentifierComposite && $idGeneratorType = $this->_getIdGeneratorTypeString($metadata->generatorType)) { + if (! $metadata->isIdentifierComposite && $idGeneratorType = $this->_getIdGeneratorTypeString($metadata->generatorType)) { $id[$metadata->getSingleIdentifierFieldName()]['generator']['strategy'] = $idGeneratorType; } @@ -235,7 +240,7 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) ClassMetadataInfo::MANY_TO_MANY, ]; - uasort($metadata->associationMappings, function($m1, $m2) use (&$orderMap){ + uasort($metadata->associationMappings, static function ($m1, $m2) use (&$orderMap) { $a1 = array_search($m1['type'], $orderMap); $a2 = array_search($m2['type'], $orderMap); @@ -244,13 +249,13 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) foreach ($metadata->associationMappings as $associationMapping) { $associationMappingXml = null; - if ($associationMapping['type'] == ClassMetadataInfo::ONE_TO_ONE) { + if ($associationMapping['type'] === ClassMetadataInfo::ONE_TO_ONE) { $associationMappingXml = $root->addChild('one-to-one'); - } elseif ($associationMapping['type'] == ClassMetadataInfo::MANY_TO_ONE) { + } elseif ($associationMapping['type'] === ClassMetadataInfo::MANY_TO_ONE) { $associationMappingXml = $root->addChild('many-to-one'); - } elseif ($associationMapping['type'] == ClassMetadataInfo::ONE_TO_MANY) { + } elseif ($associationMapping['type'] === ClassMetadataInfo::ONE_TO_MANY) { $associationMappingXml = $root->addChild('one-to-many'); - } elseif ($associationMapping['type'] == ClassMetadataInfo::MANY_TO_MANY) { + } elseif ($associationMapping['type'] === ClassMetadataInfo::MANY_TO_MANY) { $associationMappingXml = $root->addChild('many-to-many'); } @@ -299,7 +304,7 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) } if (count($cascade) === 5) { - $cascade = ['cascade-all']; + $cascade = ['cascade-all']; } if ($cascade) { @@ -349,6 +354,7 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) } } } + if (isset($associationMapping['joinColumns'])) { $joinColumnsXml = $associationMappingXml->addChild('join-columns'); @@ -370,6 +376,7 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) } } } + if (isset($associationMapping['orderBy'])) { $orderByXml = $associationMappingXml->addChild('order-by'); @@ -381,7 +388,7 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) } } - if (isset($metadata->lifecycleCallbacks) && count($metadata->lifecycleCallbacks)>0) { + if (isset($metadata->lifecycleCallbacks) && count($metadata->lifecycleCallbacks) > 0) { $lifecycleCallbacksXml = $root->addChild('lifecycle-callbacks'); foreach ($metadata->lifecycleCallbacks as $name => $methods) { @@ -401,10 +408,9 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) /** * Exports (nested) option elements. * - * @param SimpleXMLElement $parentXml - * @param array $options + * @param array $options */ - private function exportTableOptions(SimpleXMLElement $parentXml, array $options) : void + private function exportTableOptions(SimpleXMLElement $parentXml, array $options): void { foreach ($options as $name => $option) { $isArray = is_array($option); @@ -422,13 +428,8 @@ 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 - * - * @return void */ - private function exportSequenceInformation(SimpleXMLElement $identifierXmlNode, ClassMetadataInfo $metadata) : void + private function exportSequenceInformation(SimpleXMLElement $identifierXmlNode, ClassMetadataInfo $metadata): void { $sequenceDefinition = $metadata->sequenceGeneratorDefinition; @@ -443,9 +444,9 @@ private function exportSequenceInformation(SimpleXMLElement $identifierXmlNode, $sequenceGeneratorXml->addAttribute('initial-value', $sequenceDefinition['initialValue']); } - private function _asXml(SimpleXMLElement $simpleXml) : string + private function _asXml(SimpleXMLElement $simpleXml): string { - $dom = new \DOMDocument('1.0', 'UTF-8'); + $dom = new DOMDocument('1.0', 'UTF-8'); $dom->loadXML($simpleXml->asXML()); $dom->formatOutput = true; @@ -454,11 +455,11 @@ private function _asXml(SimpleXMLElement $simpleXml) : string private function processEntityListeners(ClassMetadataInfo $metadata, SimpleXMLElement $root): void { - if (0 === \count($metadata->entityListeners)) { + if (count($metadata->entityListeners) === 0) { return; } - $entityListenersXml = $root->addChild('entity-listeners'); + $entityListenersXml = $root->addChild('entity-listeners'); $entityListenersXmlMap = []; $this->generateEntityListenerXml($metadata, $entityListenersXmlMap, $entityListenersXml); diff --git a/lib/Doctrine/ORM/Tools/Export/Driver/YamlExporter.php b/lib/Doctrine/ORM/Tools/Export/Driver/YamlExporter.php index 1d2b5828037..13babe6a841 100644 --- a/lib/Doctrine/ORM/Tools/Export/Driver/YamlExporter.php +++ b/lib/Doctrine/ORM/Tools/Export/Driver/YamlExporter.php @@ -1,4 +1,5 @@ - * * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement + * + * @link www.doctrine-project.org */ class YamlExporter extends AbstractExporter { - /** - * @var string - */ + /** @var string */ protected $_extension = '.dcm.yml'; /** @@ -50,6 +50,7 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) } else { $array['type'] = 'entity'; } + $metadataTable = $metadata->table ?? ['name' => null]; $array['table'] = $metadataTable['name']; @@ -100,7 +101,7 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) unset($fieldMapping['columnName'], $fieldMapping['fieldName']); - if ($fieldMapping['column'] == $name) { + if ($fieldMapping['column'] === $name) { unset($fieldMapping['column']); } @@ -113,7 +114,7 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) $fieldMappings[$name] = $fieldMapping; } - if ( ! $metadata->isIdentifierComposite && $idGeneratorType = $this->_getIdGeneratorTypeString($metadata->generatorType)) { + if (! $metadata->isIdentifierComposite && $idGeneratorType = $this->_getIdGeneratorTypeString($metadata->generatorType)) { $ids[$metadata->getSingleIdentifierFieldName()]['generator']['strategy'] = $idGeneratorType; } @@ -145,6 +146,7 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) if ($associationMapping['isCascadeDetach']) { $cascade[] = 'detach'; } + if (count($cascade) === 5) { $cascade = ['all']; } @@ -163,7 +165,7 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) } if ($associationMapping['type'] & ClassMetadataInfo::TO_ONE) { - $joinColumns = $associationMapping['isOwningSide'] ? $associationMapping['joinColumns'] : []; + $joinColumns = $associationMapping['isOwningSide'] ? $associationMapping['joinColumns'] : []; $newJoinColumns = []; foreach ($joinColumns as $joinColumn) { @@ -188,28 +190,29 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) } else { $array['manyToOne'][$name] = $associationMappingArray; } - } elseif ($associationMapping['type'] == ClassMetadataInfo::ONE_TO_MANY) { + } elseif ($associationMapping['type'] === ClassMetadataInfo::ONE_TO_MANY) { $oneToManyMappingArray = [ 'mappedBy' => $associationMapping['mappedBy'], 'inversedBy' => $associationMapping['inversedBy'], 'orphanRemoval' => $associationMapping['orphanRemoval'], - 'orderBy' => $associationMapping['orderBy'] ?? null + 'orderBy' => $associationMapping['orderBy'] ?? null, ]; - $associationMappingArray = array_merge($associationMappingArray, $oneToManyMappingArray); + $associationMappingArray = array_merge($associationMappingArray, $oneToManyMappingArray); $array['oneToMany'][$name] = $associationMappingArray; - } elseif ($associationMapping['type'] == ClassMetadataInfo::MANY_TO_MANY) { + } elseif ($associationMapping['type'] === ClassMetadataInfo::MANY_TO_MANY) { $manyToManyMappingArray = [ 'mappedBy' => $associationMapping['mappedBy'], 'inversedBy' => $associationMapping['inversedBy'], 'joinTable' => $associationMapping['joinTable'] ?? null, - 'orderBy' => $associationMapping['orderBy'] ?? null + 'orderBy' => $associationMapping['orderBy'] ?? null, ]; - $associationMappingArray = array_merge($associationMappingArray, $manyToManyMappingArray); + $associationMappingArray = array_merge($associationMappingArray, $manyToManyMappingArray); $array['manyToMany'][$name] = $associationMappingArray; } } + if (isset($metadata->lifecycleCallbacks)) { $array['lifecycleCallbacks'] = $metadata->lifecycleCallbacks; } @@ -225,8 +228,8 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) * 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 + * @param array $array PHP array + * @param int $inline [optional] The level where you switch to inline YAML * * @return string A YAML string representing the original PHP array */ @@ -235,9 +238,9 @@ protected function yamlDump($array, $inline = 2) return Yaml::dump($array, $inline); } - private function processEntityListeners(ClassMetadataInfo $metadata, array $array) : array + private function processEntityListeners(ClassMetadataInfo $metadata, array $array): array { - if (0 === \count($metadata->entityListeners)) { + if (count($metadata->entityListeners) === 0) { return $array; } @@ -250,7 +253,7 @@ private function processEntityListeners(ClassMetadataInfo $metadata, array $arra return $array; } - private function processEntityListenerConfig(array $array, array $entityListenerConfig, string $event) : array + private function processEntityListenerConfig(array $array, array $entityListenerConfig, string $event): array { foreach ($entityListenerConfig as $entityListener) { if (! isset($array['entityListeners'][$entityListener['class']])) { diff --git a/lib/Doctrine/ORM/Tools/Export/ExportException.php b/lib/Doctrine/ORM/Tools/Export/ExportException.php index 725ea2137c8..47e0582e193 100644 --- a/lib/Doctrine/ORM/Tools/Export/ExportException.php +++ b/lib/Doctrine/ORM/Tools/Export/ExportException.php @@ -1,4 +1,5 @@ */ class CountOutputWalker extends SqlWalker { - /** - * @var \Doctrine\DBAL\Platforms\AbstractPlatform - */ + /** @var AbstractPlatform */ private $platform; - /** - * @var \Doctrine\ORM\Query\ResultSetMapping - */ + /** @var ResultSetMapping */ private $rsm; - /** - * @var array - */ + /** @var array */ private $queryComponents; /** - * Constructor. - * * Stores various parameters that are otherwise unavailable * because Doctrine\ORM\Query\SqlWalker keeps everything private without * accessors. * - * @param \Doctrine\ORM\Query $query - * @param \Doctrine\ORM\Query\ParserResult $parserResult - * @param array $queryComponents + * @param Query $query + * @param ParserResult $parserResult + * @param array $queryComponents */ 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; parent::__construct($query, $parserResult, $queryComponents); @@ -77,15 +80,13 @@ public function __construct($query, $parserResult, array $queryComponents) * are able to cache subqueries. By keeping the ORDER BY clause intact, the limitSubQuery * that will most likely be executed next can be read from the native SQL cache. * - * @param SelectStatement $AST - * * @return string * - * @throws \RuntimeException + * @throws RuntimeException */ public function walkSelectStatement(SelectStatement $AST) { - if ($this->platform->getName() === "mssql") { + if ($this->platform->getName() === 'mssql') { $AST->orderByClause = null; } @@ -107,7 +108,7 @@ public function walkSelectStatement(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"); + throw new RuntimeException('Cannot count query which selects two FROM components, cannot make distinction'); } $fromRoot = reset($from); @@ -120,7 +121,7 @@ public function walkSelectStatement(SelectStatement $AST) foreach ($rootIdentifier as $property) { if (isset($rootClass->fieldMappings[$property])) { foreach (array_keys($this->rsm->fieldMappings, $property) as $alias) { - if ($this->rsm->columnOwnerMap[$alias] == $rootAlias) { + if ($this->rsm->columnOwnerMap[$alias] === $rootAlias) { $sqlIdentifier[$property] = $alias; } } @@ -130,22 +131,23 @@ public function walkSelectStatement(SelectStatement $AST) $joinColumn = $rootClass->associationMappings[$property]['joinColumns'][0]['name']; foreach (array_keys($this->rsm->metaMappings, $joinColumn) as $alias) { - if ($this->rsm->columnOwnerMap[$alias] == $rootAlias) { + if ($this->rsm->columnOwnerMap[$alias] === $rootAlias) { $sqlIdentifier[$property] = $alias; } } } } - if (count($rootIdentifier) != count($sqlIdentifier)) { - throw new \RuntimeException(sprintf( + if (count($rootIdentifier) !== count($sqlIdentifier)) { + throw new RuntimeException(sprintf( 'Not all identifier properties can be found in the ResultSetMapping: %s', implode(', ', array_diff($rootIdentifier, array_keys($sqlIdentifier))) )); } // Build the counter query - return sprintf('SELECT %s AS dctrn_count FROM (SELECT DISTINCT %s FROM (%s) dctrn_result) dctrn_table', + return sprintf( + 'SELECT %s AS dctrn_count FROM (SELECT DISTINCT %s FROM (%s) dctrn_result) dctrn_table', $this->platform->getCountExpression('*'), implode(', ', $sqlIdentifier), $sql diff --git a/lib/Doctrine/ORM/Tools/Pagination/CountWalker.php b/lib/Doctrine/ORM/Tools/Pagination/CountWalker.php index a8f26001aba..2fb473a2581 100644 --- a/lib/Doctrine/ORM/Tools/Pagination/CountWalker.php +++ b/lib/Doctrine/ORM/Tools/Pagination/CountWalker.php @@ -1,4 +1,5 @@ - * @copyright Copyright (c) 2010 David Abdemoulaie (http://hobodave.com/) - * @license http://hobodave.com/license.txt New BSD License */ class CountWalker extends TreeWalkerAdapter { /** * Distinct mode hint name. */ - const HINT_DISTINCT = 'doctrine_paginator.distinct'; + public const HINT_DISTINCT = 'doctrine_paginator.distinct'; /** * Walks down a SelectStatement AST node, modifying it to retrieve a COUNT. * - * @param SelectStatement $AST - * * @return void * - * @throws \RuntimeException + * @throws RuntimeException */ public function walkSelectStatement(SelectStatement $AST) { if ($AST->havingClause) { - throw new \RuntimeException('Cannot count query that uses a HAVING clause. Use the output walkers for pagination'); + throw new RuntimeException('Cannot count query that uses a HAVING clause. Use the output walkers for pagination'); } $queryComponents = $this->_getQueryComponents(); @@ -61,7 +58,7 @@ public function walkSelectStatement(SelectStatement $AST) $from = $AST->fromClause->identificationVariableDeclarations; if (count($from) > 1) { - throw new \RuntimeException("Cannot count query which selects two FROM components, cannot make distinction"); + throw new RuntimeException('Cannot count query which selects two FROM components, cannot make distinction'); } $fromRoot = reset($from); @@ -74,21 +71,22 @@ public function walkSelectStatement(SelectStatement $AST) $pathType = PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION; } - $pathExpression = new PathExpression( - PathExpression::TYPE_STATE_FIELD | PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION, $rootAlias, + $pathExpression = new PathExpression( + PathExpression::TYPE_STATE_FIELD | PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION, + $rootAlias, $identifierFieldName ); $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 - ) + new AggregateExpression('count', $pathExpression, $distinct), + null + ), ]; // ORDER BY is not needed, only increases query execution through unnecessary sorting. $AST->orderByClause = null; } } - diff --git a/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryOutputWalker.php b/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryOutputWalker.php index 5f00fdce88d..3605bfb7b69 100644 --- a/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryOutputWalker.php +++ b/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryOutputWalker.php @@ -1,4 +1,5 @@ */ class LimitSubqueryOutputWalker extends SqlWalker { private const ORDER_BY_PATH_EXPRESSION = '/(?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(); + $this->maxResults = $query->getMaxResults(); $query->setFirstResult(null)->setMaxResults(null); - $this->em = $query->getEntityManager(); - $this->quoteStrategy = $this->em->getConfiguration()->getQuoteStrategy(); + $this->em = $query->getEntityManager(); + $this->quoteStrategy = $this->em->getConfiguration()->getQuoteStrategy(); parent::__construct($query, $parserResult, $queryComponents); } @@ -140,12 +145,10 @@ private function platformSupportsRowNumber() /** * Rebuilds a select statement's order by clause for use in a * ROW_NUMBER() OVER() expression. - * - * @param SelectStatement $AST */ private function rebuildOrderByForRowNumber(SelectStatement $AST) { - $orderByClause = $AST->orderByClause; + $orderByClause = $AST->orderByClause; $selectAliasToExpressionMap = []; // Get any aliases that are available for select expressions. foreach ($AST->selectClause->selectExpressions as $selectExpression) { @@ -158,8 +161,9 @@ private function rebuildOrderByForRowNumber(SelectStatement $AST) $orderByItem->expression = $selectAliasToExpressionMap[$orderByItem->expression]; } } - $func = new RowNumberOverFunction('dctrn_rownum'); - $func->orderByClause = $AST->orderByClause; + + $func = new RowNumberOverFunction('dctrn_rownum'); + $func->orderByClause = $AST->orderByClause; $AST->selectClause->selectExpressions[] = new SelectExpression($func, 'dctrn_rownum', true); // No need for an order by clause, we'll order by rownum in the outer query. @@ -169,17 +173,16 @@ private function rebuildOrderByForRowNumber(SelectStatement $AST) /** * Walks down a SelectStatement AST node, wrapping it in a SELECT DISTINCT. * - * @param SelectStatement $AST - * * @return string * - * @throws \RuntimeException + * @throws RuntimeException */ public function walkSelectStatement(SelectStatement $AST) { if ($this->platformSupportsRowNumber()) { return $this->walkSelectStatementWithRowNumber($AST); } + return $this->walkSelectStatementWithoutRowNumber($AST); } @@ -187,15 +190,13 @@ public function walkSelectStatement(SelectStatement $AST) * Walks down a SelectStatement AST node, wrapping it in a SELECT DISTINCT. * This method is for use with platforms which support ROW_NUMBER. * - * @param SelectStatement $AST - * * @return string * - * @throws \RuntimeException + * @throws RuntimeException */ public function walkSelectStatementWithRowNumber(SelectStatement $AST) { - $hasOrderBy = false; + $hasOrderBy = false; $outerOrderBy = ' ORDER BY dctrn_minrownum ASC'; $orderGroupBy = ''; if ($AST->orderByClause instanceof OrderByClause) { @@ -208,7 +209,7 @@ public function walkSelectStatementWithRowNumber(SelectStatement $AST) $sqlIdentifier = $this->getSQLIdentifier($AST); if ($hasOrderBy) { - $orderGroupBy = ' GROUP BY ' . implode(', ', $sqlIdentifier); + $orderGroupBy = ' GROUP BY ' . implode(', ', $sqlIdentifier); $sqlIdentifier[] = 'MIN(' . $this->walkResultVariable('dctrn_rownum') . ') AS dctrn_minrownum'; } @@ -245,12 +246,11 @@ public function walkSelectStatementWithRowNumber(SelectStatement $AST) * Walks down a SelectStatement AST node, wrapping it in a SELECT DISTINCT. * This method is for platforms which DO NOT support ROW_NUMBER. * - * @param SelectStatement $AST * @param bool $addMissingItemsFromOrderByToSelect * * @return string * - * @throws \RuntimeException + * @throws RuntimeException */ public function walkSelectStatementWithoutRowNumber(SelectStatement $AST, $addMissingItemsFromOrderByToSelect = true) { @@ -264,7 +264,7 @@ public function walkSelectStatementWithoutRowNumber(SelectStatement $AST, $addMi // Remove order by clause from the inner query // It will be re-appended in the outer select generated by this method - $orderByClause = $AST->orderByClause; + $orderByClause = $AST->orderByClause; $AST->orderByClause = null; $innerSql = $this->getInnerSQL($AST); @@ -272,15 +272,20 @@ public function walkSelectStatementWithoutRowNumber(SelectStatement $AST, $addMi $sqlIdentifier = $this->getSQLIdentifier($AST); // 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(', ', $sqlIdentifier), + $innerSql + ); // http://www.doctrine-project.org/jira/browse/DDC-1958 $sql = $this->preserveSqlOrdering($sqlIdentifier, $innerSql, $sql, $orderByClause); // Apply the limit and offset. $sql = $this->platform->modifyLimitQuery( - $sql, $this->maxResults, $this->firstResult + $sql, + $this->maxResults, + $this->firstResult ); // Add the columns to the ResultSetMapping. It's not really nice but @@ -300,8 +305,6 @@ public function walkSelectStatementWithoutRowNumber(SelectStatement $AST, $addMi /** * Finds all PathExpressions in an AST's OrderByClause, and ensures that * the referenced fields are present in the SelectClause of the passed AST. - * - * @param SelectStatement $AST */ private function addMissingItemsFromOrderByToSelect(SelectStatement $AST) { @@ -323,9 +326,10 @@ private function addMissingItemsFromOrderByToSelect(SelectStatement $AST) 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,9 +338,10 @@ 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. @@ -356,28 +361,23 @@ private function addMissingItemsFromOrderByToSelect(SelectStatement $AST) /** * Generates new SQL for statements with an order by clause * - * @param array $sqlIdentifier - * @param string $innerSql - * @param string $sql - * @param OrderByClause|null $orderByClause - * - * @return string + * @param array $sqlIdentifier */ private function preserveSqlOrdering( array $sqlIdentifier, string $innerSql, string $sql, ?OrderByClause $orderByClause - ) : string { + ): string { // If the sql statement has an order by clause, we need to wrap it in a new select distinct statement if (! $orderByClause) { return $sql; } // now only select distinct identifier - return \sprintf( + return sprintf( 'SELECT DISTINCT %s FROM (%s) dctrn_result', - \implode(', ', $sqlIdentifier), + implode(', ', $sqlIdentifier), $this->recreateInnerSql($orderByClause, $sqlIdentifier, $innerSql) ); } @@ -385,17 +385,13 @@ private function preserveSqlOrdering( /** * Generates a new SQL statement for the inner query to keep the correct sorting * - * @param OrderByClause $orderByClause - * @param array $identifiers - * @param string $innerSql - * - * @return string + * @param array $identifiers */ private function recreateInnerSql( OrderByClause $orderByClause, array $identifiers, string $innerSql - ) : string { + ): string { [$searchPatterns, $replacements] = $this->generateSqlAliasReplacements(); $orderByItems = []; @@ -403,45 +399,45 @@ private function recreateInnerSql( foreach ($orderByClause->orderByItems as $orderByItem) { // Walk order by item to get string representation of it and // replace path expressions in the order by clause with their column alias - $orderByItemString = \preg_replace( + $orderByItemString = preg_replace( $searchPatterns, $replacements, $this->walkOrderByItem($orderByItem) ); $orderByItems[] = $orderByItemString; - $identifier = \substr($orderByItemString, 0, \strrpos($orderByItemString, ' ')); + $identifier = substr($orderByItemString, 0, strrpos($orderByItemString, ' ')); - if (! \in_array($identifier, $identifiers, true)) { + if (! in_array($identifier, $identifiers, true)) { $identifiers[] = $identifier; } } - return $sql = \sprintf( + return $sql = sprintf( 'SELECT DISTINCT %s FROM (%s) dctrn_result_inner ORDER BY %s', - \implode(', ', $identifiers), + implode(', ', $identifiers), $innerSql, - \implode(', ', $orderByItems) + implode(', ', $orderByItems) ); } /** * @return string[][] */ - private function generateSqlAliasReplacements() : array + private function generateSqlAliasReplacements(): array { $aliasMap = $searchPatterns = $replacements = $metadataList = []; // Generate DQL alias -> SQL table alias mapping - foreach (\array_keys($this->rsm->aliasMap) as $dqlAlias) { + foreach (array_keys($this->rsm->aliasMap) as $dqlAlias) { $metadataList[$dqlAlias] = $class = $this->queryComponents[$dqlAlias]['metadata']; - $aliasMap[$dqlAlias] = $this->getSQLTableAlias($class->getTableName(), $dqlAlias); + $aliasMap[$dqlAlias] = $this->getSQLTableAlias($class->getTableName(), $dqlAlias); } // 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 = $metadataList[$dqlAliasForFieldAlias]; // If the field is from a joined child table, we won't be ordering on it. if (! isset($class->fieldMappings[$fieldName])) { @@ -471,7 +467,7 @@ private function generateSqlAliasReplacements() : array } // Compose search and replace patterns - $searchPatterns[] = \sprintf(self::ORDER_BY_PATH_EXPRESSION, $sqlTableAliasForFieldAlias, $columnName); + $searchPatterns[] = sprintf(self::ORDER_BY_PATH_EXPRESSION, $sqlTableAliasForFieldAlias, $columnName); $replacements[] = $fieldAlias; } @@ -489,12 +485,10 @@ public function getOrderByPathExpressions() } /** - * @param SelectStatement $AST - * * @return string * - * @throws \Doctrine\ORM\OptimisticLockException - * @throws \Doctrine\ORM\Query\QueryException + * @throws OptimisticLockException + * @throws QueryException */ private function getInnerSQL(SelectStatement $AST) { @@ -504,7 +498,7 @@ private function getInnerSQL(SelectStatement $AST) $hiddens = []; foreach ($AST->selectClause->selectExpressions as $idx => $expr) { - $hiddens[$idx] = $expr->hiddenAliasResultVariable; + $hiddens[$idx] = $expr->hiddenAliasResultVariable; $expr->hiddenAliasResultVariable = false; } @@ -519,8 +513,6 @@ private function getInnerSQL(SelectStatement $AST) } /** - * @param SelectStatement $AST - * * @return array-key[] * * @psalm-return array @@ -535,7 +527,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'); + throw new RuntimeException('Cannot count query which selects two FROM components, cannot make distinction'); } $fromRoot = reset($from); @@ -548,7 +540,7 @@ private function getSQLIdentifier(SelectStatement $AST) foreach ($rootIdentifier as $property) { if (isset($rootClass->fieldMappings[$property])) { foreach (array_keys($this->rsm->fieldMappings, $property) as $alias) { - if ($this->rsm->columnOwnerMap[$alias] == $rootAlias) { + if ($this->rsm->columnOwnerMap[$alias] === $rootAlias) { $sqlIdentifier[$property] = $alias; } } @@ -558,7 +550,7 @@ private function getSQLIdentifier(SelectStatement $AST) $joinColumn = $rootClass->associationMappings[$property]['joinColumns'][0]['name']; foreach (array_keys($this->rsm->metaMappings, $joinColumn) as $alias) { - if ($this->rsm->columnOwnerMap[$alias] == $rootAlias) { + if ($this->rsm->columnOwnerMap[$alias] === $rootAlias) { $sqlIdentifier[$property] = $alias; } } @@ -566,11 +558,11 @@ private function getSQLIdentifier(SelectStatement $AST) } if (count($sqlIdentifier) === 0) { - throw new \RuntimeException('The Paginator does not support Queries which only yield ScalarResults.'); + throw new RuntimeException('The Paginator does not support Queries which only yield ScalarResults.'); } - if (count($rootIdentifier) != count($sqlIdentifier)) { - throw new \RuntimeException(sprintf( + if (count($rootIdentifier) !== count($sqlIdentifier)) { + throw new RuntimeException(sprintf( 'Not all identifier properties can be found in the ResultSetMapping: %s', implode(', ', array_diff($rootIdentifier, array_keys($sqlIdentifier))) )); @@ -584,7 +576,7 @@ private function getSQLIdentifier(SelectStatement $AST) */ public function walkPathExpression($pathExpr) { - if (!$this->inSubSelect && !$this->platformSupportsRowNumber() && !in_array($pathExpr, $this->orderByPathExpressions)) { + if (! $this->inSubSelect && ! $this->platformSupportsRowNumber() && ! in_array($pathExpr, $this->orderByPathExpressions)) { $this->orderByPathExpressions[] = $pathExpr; } diff --git a/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryWalker.php b/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryWalker.php index 2f76e8565e1..a40f0545481 100644 --- a/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryWalker.php +++ b/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryWalker.php @@ -1,4 +1,5 @@ - * @copyright Copyright (c) 2010 David Abdemoulaie (http://hobodave.com/) - * @license http://hobodave.com/license.txt New BSD License */ class LimitSubqueryWalker extends TreeWalkerAdapter { @@ -54,11 +54,9 @@ class LimitSubqueryWalker extends TreeWalkerAdapter * Walks down a SelectStatement AST node, modifying it to retrieve DISTINCT ids * of the root Entity. * - * @param SelectStatement $AST - * * @return void * - * @throws \RuntimeException + * @throws RuntimeException */ public function walkSelectStatement(SelectStatement $AST) { @@ -73,7 +71,7 @@ public function walkSelectStatement(SelectStatement $AST) $identifier = $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."); + 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( @@ -94,14 +92,15 @@ public function walkSelectStatement(SelectStatement $AST) $AST->selectClause->selectExpressions = [new SelectExpression($pathExpression, '_dctrn_id')]; $AST->selectClause->isDistinct = true; - if ( ! isset($AST->orderByClause)) { + if (! isset($AST->orderByClause)) { return; } foreach ($AST->orderByClause->orderByItems as $item) { if ($item->expression instanceof PathExpression) { $AST->selectClause->selectExpressions[] = new SelectExpression( - $this->createSelectExpressionItem($item->expression), '_dctrn_ord' . $this->_aliasCounter++ + $this->createSelectExpressionItem($item->expression), + '_dctrn_ord' . $this->_aliasCounter++ ); continue; @@ -122,8 +121,6 @@ public function walkSelectStatement(SelectStatement $AST) /** * Validate the AST to ensure that this walker is able to properly manipulate it. - * - * @param SelectStatement $AST */ private function validate(SelectStatement $AST) { @@ -135,20 +132,26 @@ private function validate(SelectStatement $AST) $from = $AST->fromClause->identificationVariableDeclarations; $fromRoot = reset($from); - if ($query instanceof Query - && null !== $query->getMaxResults() + if ( + $query instanceof Query + && $query->getMaxResults() !== null && $AST->orderByClause - && count($fromRoot->joins)) { + && 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 ( + $orderByItem->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']['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.'); } } } diff --git a/lib/Doctrine/ORM/Tools/Pagination/Paginator.php b/lib/Doctrine/ORM/Tools/Pagination/Paginator.php index d6c50e23107..5ee8fe0aaa9 100644 --- a/lib/Doctrine/ORM/Tools/Pagination/Paginator.php +++ b/lib/Doctrine/ORM/Tools/Pagination/Paginator.php @@ -1,4 +1,5 @@ - * @author Benjamin Eberlei - * @license New BSD - * * @template T */ -class Paginator implements \Countable, \IteratorAggregate +class Paginator implements Countable, IteratorAggregate { - /** - * @var Query - */ + /** @var Query */ private $query; - /** - * @var bool - */ + /** @var bool */ private $fetchJoinCollection; - /** - * @var bool|null - */ + /** @var bool|null */ private $useOutputWalkers; - /** - * @var int - */ + /** @var int */ private $count; /** - * Constructor. - * * @param Query|QueryBuilder $query A Doctrine ORM query or query builder. - * @param boolean $fetchJoinCollection Whether the query joins a collection (true by default). + * @param bool $fetchJoinCollection Whether the query joins a collection (true by default). */ public function __construct($query, $fetchJoinCollection = true) { @@ -71,7 +65,7 @@ public function __construct($query, $fetchJoinCollection = true) $query = $query->getQuery(); } - $this->query = $query; + $this->query = $query; $this->fetchJoinCollection = (bool) $fetchJoinCollection; } @@ -88,7 +82,7 @@ public function getQuery() /** * Returns whether the query joins a collection. * - * @return boolean Whether the query joins a collection. + * @return bool Whether the query joins a collection. */ public function getFetchJoinCollection() { @@ -180,8 +174,7 @@ public function getIterator() ->setMaxResults($length) ->setFirstResult($offset) ->setCacheable($this->query->isCacheable()) - ->getResult($this->query->getHydrationMode()) - ; + ->getResult($this->query->getHydrationMode()); } return new ArrayIterator($result); @@ -227,7 +220,6 @@ private function useOutputWalker(Query $query) /** * Appends a custom tree walker to the tree walkers hint. * - * @param Query $query * @param string $walkerClass */ private function appendTreeWalker(Query $query, $walkerClass) @@ -251,7 +243,7 @@ private function getCountQuery() { $countQuery = $this->cloneQuery($this->query); - if ( ! $countQuery->hasHint(CountWalker::HINT_DISTINCT)) { + if (! $countQuery->hasHint(CountWalker::HINT_DISTINCT)) { $countQuery->setHint(CountWalker::HINT_DISTINCT, true); } @@ -277,13 +269,13 @@ private function unbindUnusedQueryParams(Query $query): void { $parser = new Parser($query); $parameterMappings = $parser->parse()->getParameterMappings(); - /* @var $parameters \Doctrine\Common\Collections\Collection|\Doctrine\ORM\Query\Parameter[] */ - $parameters = $query->getParameters(); + /** @var Collection|Parameter[] $parameters */ + $parameters = $query->getParameters(); foreach ($parameters as $key => $parameter) { $parameterName = $parameter->getName(); - if ( ! (isset($parameterMappings[$parameterName]) || array_key_exists($parameterName, $parameterMappings))) { + if (! (isset($parameterMappings[$parameterName]) || array_key_exists($parameterName, $parameterMappings))) { unset($parameters[$key]); } } diff --git a/lib/Doctrine/ORM/Tools/Pagination/RowNumberOverFunction.php b/lib/Doctrine/ORM/Tools/Pagination/RowNumberOverFunction.php index a9d3e5d686e..9d680b7a0c2 100644 --- a/lib/Doctrine/ORM/Tools/Pagination/RowNumberOverFunction.php +++ b/lib/Doctrine/ORM/Tools/Pagination/RowNumberOverFunction.php @@ -22,27 +22,27 @@ use Doctrine\ORM\ORMException; use Doctrine\ORM\Query\AST\Functions\FunctionNode; +use Doctrine\ORM\Query\AST\OrderByClause; +use Doctrine\ORM\Query\Parser; +use Doctrine\ORM\Query\SqlWalker; + +use function trim; /** * RowNumberOverFunction * * Provides ROW_NUMBER() OVER(ORDER BY...) construct for use in LimitSubqueryOutputWalker - * - * @since 2.5 - * @author Bill Schaller */ class RowNumberOverFunction extends FunctionNode { - /** - * @var \Doctrine\ORM\Query\AST\OrderByClause - */ + /** @var OrderByClause */ public $orderByClause; /** * @override * @inheritdoc */ - public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) + public function getSql(SqlWalker $sqlWalker) { return 'ROW_NUMBER() OVER(' . trim($sqlWalker->walkOrderByClause( $this->orderByClause @@ -50,13 +50,13 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) } /** + * @throws ORMException + * * @override * @inheritdoc - * - * @throws ORMException */ - public function parse(\Doctrine\ORM\Query\Parser $parser) + public function parse(Parser $parser) { - throw new ORMException("The RowNumberOverFunction is not intended for, nor is it enabled for use in DQL."); + throw new ORMException('The RowNumberOverFunction is not intended for, nor is it enabled for use in DQL.'); } } diff --git a/lib/Doctrine/ORM/Tools/Pagination/WhereInWalker.php b/lib/Doctrine/ORM/Tools/Pagination/WhereInWalker.php index de66f64d7ec..1403fe97781 100644 --- a/lib/Doctrine/ORM/Tools/Pagination/WhereInWalker.php +++ b/lib/Doctrine/ORM/Tools/Pagination/WhereInWalker.php @@ -1,4 +1,5 @@ - * @copyright Copyright (c) 2010 David Abdemoulaie (http://hobodave.com/) - * @license http://hobodave.com/license.txt New BSD License */ class WhereInWalker extends TreeWalkerAdapter { /** * ID Count hint name. */ - const HINT_PAGINATOR_ID_COUNT = 'doctrine.id.count'; + public const HINT_PAGINATOR_ID_COUNT = 'doctrine.id.count'; /** * Primary key alias for query. */ - const PAGINATOR_ID_ALIAS = 'dpid'; + public const PAGINATOR_ID_ALIAS = 'dpid'; /** * Replaces the whereClause in the AST. @@ -70,11 +69,9 @@ class WhereInWalker extends TreeWalkerAdapter * The total number of parameters is retrieved from * the HINT_PAGINATOR_ID_COUNT query hint. * - * @param SelectStatement $AST - * * @return void * - * @throws \RuntimeException + * @throws RuntimeException */ public function walkSelectStatement(SelectStatement $AST) { @@ -83,13 +80,13 @@ public function walkSelectStatement(SelectStatement $AST) $from = $AST->fromClause->identificationVariableDeclarations; if (count($from) > 1) { - throw new \RuntimeException("Cannot count query which selects two FROM components, cannot make distinction"); + throw new RuntimeException('Cannot count query which selects two FROM components, cannot make distinction'); } - $fromRoot = reset($from); - $rootAlias = $fromRoot->rangeVariableDeclaration->aliasIdentificationVariable; - /** @var ClassMetadata $rootClass */ - $rootClass = $queryComponents[$rootAlias]['metadata']; + $fromRoot = reset($from); + $rootAlias = $fromRoot->rangeVariableDeclaration->aliasIdentificationVariable; + $rootClass = $queryComponents[$rootAlias]['metadata']; + assert($rootClass instanceof ClassMetadata); $identifierFieldName = $rootClass->getSingleIdentifierFieldName(); $pathType = PathExpression::TYPE_STATE_FIELD; @@ -103,12 +100,12 @@ public function walkSelectStatement(SelectStatement $AST) $count = $this->_getQuery()->getHint(self::HINT_PAGINATOR_ID_COUNT); if ($count > 0) { - $arithmeticExpression = new ArithmeticExpression(); + $arithmeticExpression = new ArithmeticExpression(); $arithmeticExpression->simpleArithmeticExpression = new SimpleArithmeticExpression( [$pathExpression] ); - $expression = new InExpression($arithmeticExpression); - $expression->literals[] = new InputParameter(":" . self::PAGINATOR_ID_ALIAS); + $expression = new InExpression($arithmeticExpression); + $expression->literals[] = new InputParameter(':' . self::PAGINATOR_ID_ALIAS); $this->convertWhereInIdentifiersToDatabaseValue( PersisterHelper::getTypeOfField( @@ -119,11 +116,11 @@ public function walkSelectStatement(SelectStatement $AST) )[0] ); } else { - $expression = new NullComparisonExpression($pathExpression); + $expression = new NullComparisonExpression($pathExpression); $expression->not = false; } - $conditionalPrimary = new ConditionalPrimary; + $conditionalPrimary = new ConditionalPrimary(); $conditionalPrimary->simpleConditionalExpression = $expression; if ($AST->whereClause) { if ($AST->whereClause->conditionalExpression instanceof ConditionalTerm) { @@ -134,35 +131,34 @@ public function walkSelectStatement(SelectStatement $AST) new ConditionalTerm( [ $AST->whereClause->conditionalExpression, - $conditionalPrimary + $conditionalPrimary, ] - ) + ), ] ); - } elseif ($AST->whereClause->conditionalExpression instanceof ConditionalExpression + } elseif ( + $AST->whereClause->conditionalExpression instanceof ConditionalExpression || $AST->whereClause->conditionalExpression instanceof ConditionalFactor ) { - $tmpPrimary = new ConditionalPrimary; - $tmpPrimary->conditionalExpression = $AST->whereClause->conditionalExpression; + $tmpPrimary = new ConditionalPrimary(); + $tmpPrimary->conditionalExpression = $AST->whereClause->conditionalExpression; $AST->whereClause->conditionalExpression = new ConditionalTerm( [ $tmpPrimary, - $conditionalPrimary + $conditionalPrimary, ] ); } } else { $AST->whereClause = new WhereClause( new ConditionalExpression( - [ - new ConditionalTerm([$conditionalPrimary]) - ] + [new ConditionalTerm([$conditionalPrimary])] ) ); } } - private function convertWhereInIdentifiersToDatabaseValue(string $type) : void + private function convertWhereInIdentifiersToDatabaseValue(string $type): void { $query = $this->_getQuery(); $identifiersParameter = $query->getParameter(self::PAGINATOR_ID_ALIAS); diff --git a/lib/Doctrine/ORM/Tools/ResolveTargetEntityListener.php b/lib/Doctrine/ORM/Tools/ResolveTargetEntityListener.php index 73b8fa7ceec..29c6a3b3dcc 100644 --- a/lib/Doctrine/ORM/Tools/ResolveTargetEntityListener.php +++ b/lib/Doctrine/ORM/Tools/ResolveTargetEntityListener.php @@ -1,4 +1,5 @@ - * @since 2.2 */ class ResolveTargetEntityListener implements EventSubscriber { - /** - * @var array[] indexed by original entity name - */ + /** @var array[] indexed by original entity name */ private $resolveTargetEntities = []; /** @@ -48,7 +49,7 @@ public function getSubscribedEvents() { return [ Events::loadClassMetadata, - Events::onClassMetadataNotFound + Events::onClassMetadataNotFound, ]; } @@ -63,13 +64,11 @@ public function getSubscribedEvents() */ public function addResolveTargetEntity($originalEntity, $newEntity, array $mapping) { - $mapping['targetEntity'] = ltrim($newEntity, "\\"); - $this->resolveTargetEntities[ltrim($originalEntity, "\\")] = $mapping; + $mapping['targetEntity'] = ltrim($newEntity, '\\'); + $this->resolveTargetEntities[ltrim($originalEntity, '\\')] = $mapping; } /** - * @param OnClassMetadataNotFoundEventArgs $args - * * @internal this is an event callback, and should not be called directly * * @return void @@ -88,11 +87,9 @@ public function onClassMetadataNotFound(OnClassMetadataNotFoundEventArgs $args) /** * Processes event and resolves new target entity names. * - * @param LoadClassMetadataEventArgs $args + * @internal this is an event callback, and should not be called directly * * @return void - * - * @internal this is an event callback, and should not be called directly */ public function loadClassMetadata(LoadClassMetadataEventArgs $args) { @@ -105,22 +102,22 @@ public function loadClassMetadata(LoadClassMetadataEventArgs $args) } foreach ($this->resolveTargetEntities as $interface => $data) { - if ($data['targetEntity'] == $cm->getName()) { + if ($data['targetEntity'] === $cm->getName()) { $args->getEntityManager()->getMetadataFactory()->setMetadataFor($interface, $cm); } } } /** - * @param \Doctrine\ORM\Mapping\ClassMetadataInfo $classMetadata - * @param array $mapping + * @param ClassMetadataInfo $classMetadata + * @param array $mapping * * @return void */ private function remapAssociation($classMetadata, $mapping) { - $newMapping = $this->resolveTargetEntities[$mapping['targetEntity']]; - $newMapping = array_replace_recursive($mapping, $newMapping); + $newMapping = $this->resolveTargetEntities[$mapping['targetEntity']]; + $newMapping = array_replace_recursive($mapping, $newMapping); $newMapping['fieldName'] = $mapping['fieldName']; unset($classMetadata->associationMappings[$mapping['fieldName']]); diff --git a/lib/Doctrine/ORM/Tools/SchemaTool.php b/lib/Doctrine/ORM/Tools/SchemaTool.php index 6d718bceea7..c565276de09 100644 --- a/lib/Doctrine/ORM/Tools/SchemaTool.php +++ b/lib/Doctrine/ORM/Tools/SchemaTool.php @@ -1,4 +1,5 @@ ClassMetadata class descriptors. * * @link www.doctrine-project.org - * @since 2.0 - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - * @author Benjamin Eberlei - * @author Stefano Rodriguez */ class SchemaTool { private const KNOWN_COLUMN_OPTIONS = ['comment', 'unsigned', 'fixed', 'default']; - /** - * @var \Doctrine\ORM\EntityManagerInterface - */ + /** @var EntityManagerInterface */ private $em; - /** - * @var \Doctrine\DBAL\Platforms\AbstractPlatform - */ + /** @var AbstractPlatform */ private $platform; /** * The quote strategy. * - * @var \Doctrine\ORM\Mapping\QuoteStrategy + * @var QuoteStrategy */ private $quoteStrategy; /** * Initializes a new SchemaTool instance that uses the connection of the * provided EntityManager. - * - * @param \Doctrine\ORM\EntityManagerInterface $em */ 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(); + $this->quoteStrategy = $em->getConfiguration()->getQuoteStrategy(); } /** @@ -90,12 +96,12 @@ public function __construct(EntityManagerInterface $em) public function createSchema(array $classes) { $createSchemaSql = $this->getCreateSchemaSql($classes); - $conn = $this->em->getConnection(); + $conn = $this->em->getConnection(); foreach ($createSchemaSql as $sql) { try { $conn->executeQuery($sql); - } catch (\Throwable $e) { + } catch (Throwable $e) { throw ToolsException::schemaToolFailure($sql, $e); } } @@ -126,12 +132,10 @@ public function getCreateSchemaSql(array $classes) */ private function processingNotRequired($class, array $processedClasses) { - return ( - isset($processedClasses[$class->name]) || + return isset($processedClasses[$class->name]) || $class->isMappedSuperclass || $class->isEmbeddedClass || - ($class->isInheritanceTypeSingleTable() && $class->name != $class->rootEntityName) - ); + ($class->isInheritanceTypeSingleTable() && $class->name !== $class->rootEntityName); } /** @@ -141,24 +145,24 @@ private function processingNotRequired($class, array $processedClasses) * * @return Schema * - * @throws \Doctrine\ORM\ORMException + * @throws ORMException */ public function getSchemaFromMetadata(array $classes) { // Reminder for processed classes, used for hierarchies - $processedClasses = []; - $eventManager = $this->em->getEventManager(); - $schemaManager = $this->em->getConnection()->getSchemaManager(); - $metadataSchemaConfig = $schemaManager->createSchemaConfig(); + $processedClasses = []; + $eventManager = $this->em->getEventManager(); + $schemaManager = $this->em->getConnection()->getSchemaManager(); + $metadataSchemaConfig = $schemaManager->createSchemaConfig(); $metadataSchemaConfig->setExplicitForeignKeyIndexes(false); $schema = new Schema([], [], $metadataSchemaConfig); - $addedFks = []; + $addedFks = []; $blacklistedFks = []; foreach ($classes as $class) { - /** @var \Doctrine\ORM\Mapping\ClassMetadata $class */ + assert($class instanceof ClassMetadata); if ($this->processingNotRequired($class, $processedClasses)) { continue; } @@ -187,7 +191,7 @@ public function getSchemaFromMetadata(array $classes) } elseif ($class->isInheritanceTypeJoined()) { // Add all non-inherited fields as columns foreach ($class->fieldMappings as $fieldName => $mapping) { - if ( ! isset($mapping['inherited'])) { + if (! isset($mapping['inherited'])) { $this->gatherColumn($class, $mapping, $table); } } @@ -195,7 +199,7 @@ public function getSchemaFromMetadata(array $classes) $this->gatherRelationsSql($class, $table, $schema, $addedFks, $blacklistedFks); // Add the discriminator column only to the root table - if ($class->name == $class->rootEntityName) { + if ($class->name === $class->rootEntityName) { $this->addDiscriminatorColumnDefinition($class, $table); } else { // Add an ID FK column to child tables @@ -214,7 +218,7 @@ public function getSchemaFromMetadata(array $classes) // TODO: This seems rather hackish, can we optimize it? $table->getColumn($columnName)->setAutoincrement(false); - $pkColumns[] = $columnName; + $pkColumns[] = $columnName; $inheritedKeyColumns[] = $columnName; continue; @@ -226,7 +230,7 @@ public function getSchemaFromMetadata(array $classes) $targetEntity = current( array_filter( $classes, - function (ClassMetadata $class) use ($idMapping) : bool { + static function (ClassMetadata $class) use ($idMapping): bool { return $class->name === $idMapping['targetEntity']; } ) @@ -247,7 +251,7 @@ function (ClassMetadata $class) use ($idMapping) : bool { } } - if ( ! empty($inheritedKeyColumns)) { + if (! empty($inheritedKeyColumns)) { // Add a FK constraint on the ID column $table->addForeignKeyConstraint( $this->quoteStrategy->getTableName( @@ -260,7 +264,7 @@ function (ClassMetadata $class) use ($idMapping) : bool { ); } - if ( ! empty($pkColumns)) { + if (! empty($pkColumns)) { $table->setPrimaryKey($pkColumns); } } @@ -277,8 +281,8 @@ function (ClassMetadata $class) use ($idMapping) : bool { 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]; + assert($assoc instanceof OneToOne); foreach ($assoc['joinColumns'] as $joinColumn) { $pkColumns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform); @@ -286,7 +290,7 @@ function (ClassMetadata $class) use ($idMapping) : bool { } } - if ( ! $table->hasIndex('primary')) { + if (! $table->hasIndex('primary')) { $table->setPrimaryKey($pkColumns); } @@ -303,7 +307,7 @@ function (ClassMetadata $class) use ($idMapping) : bool { if (isset($class->table['indexes'])) { foreach ($class->table['indexes'] as $indexName => $indexData) { - if ( ! isset($indexData['flags'])) { + if (! isset($indexData['flags'])) { $indexData['flags'] = []; } @@ -334,10 +338,10 @@ function (ClassMetadata $class) use ($idMapping) : bool { $processedClasses[$class->name] = true; - if ($class->isIdGeneratorSequence() && $class->name == $class->rootEntityName) { + if ($class->isIdGeneratorSequence() && $class->name === $class->rootEntityName) { $seqDef = $class->sequenceGeneratorDefinition; $quotedName = $this->quoteStrategy->getSequenceName($seqDef, $class, $this->platform); - if ( ! $schema->hasSequence($quotedName)) { + if (! $schema->hasSequence($quotedName)) { $schema->createSequence( $quotedName, $seqDef['allocationSize'], @@ -354,7 +358,7 @@ function (ClassMetadata $class) use ($idMapping) : bool { } } - if ( ! $this->platform->supportsSchemas() && ! $this->platform->canEmulateSchemas()) { + if (! $this->platform->supportsSchemas() && ! $this->platform->canEmulateSchemas()) { $schema->visit(new RemoveNamespacedAssets()); } @@ -373,7 +377,6 @@ function (ClassMetadata $class) use ($idMapping) : bool { * column of a class. * * @param ClassMetadata $class - * @param Table $table * * @return void */ @@ -381,16 +384,17 @@ private function addDiscriminatorColumnDefinition($class, Table $table) { $discrColumn = $class->discriminatorColumn; - if ( ! isset($discrColumn['type']) || - (strtolower($discrColumn['type']) == 'string' && ! isset($discrColumn['length'])) + if ( + ! isset($discrColumn['type']) || + (strtolower($discrColumn['type']) === 'string' && ! isset($discrColumn['length'])) ) { - $discrColumn['type'] = 'string'; + $discrColumn['type'] = 'string'; $discrColumn['length'] = 255; } $options = [ 'length' => $discrColumn['length'] ?? null, - 'notnull' => true + 'notnull' => true, ]; if (isset($discrColumn['columnDefinition'])) { @@ -405,7 +409,6 @@ private function addDiscriminatorColumnDefinition($class, Table $table) * found in the given class. * * @param ClassMetadata $class - * @param Table $table * * @return void */ @@ -431,7 +434,6 @@ private function gatherColumns($class, Table $table) * * @param ClassMetadata $class The class that owns the field mapping. * @param array $mapping The field mapping. - * @param Table $table * * @return void */ @@ -440,17 +442,17 @@ private function gatherColumn($class, array $mapping, Table $table) $columnName = $this->quoteStrategy->getColumnName($mapping['fieldName'], $class, $this->platform); $columnType = $mapping['type']; - $options = []; - $options['length'] = $mapping['length'] ?? null; + $options = []; + $options['length'] = $mapping['length'] ?? null; $options['notnull'] = isset($mapping['nullable']) ? ! $mapping['nullable'] : true; if ($class->isInheritanceTypeSingleTable() && $class->parentClasses) { $options['notnull'] = false; } - $options['platformOptions'] = []; + $options['platformOptions'] = []; $options['platformOptions']['version'] = $class->isVersioned && $class->versionField === $mapping['fieldName']; - if (strtolower($columnType) === 'string' && null === $options['length']) { + if (strtolower($columnType) === 'string' && $options['length'] === null) { $options['length'] = 255; } @@ -473,9 +475,10 @@ private function gatherColumn($class, array $mapping, Table $table) // the 'default' option can be overwritten here $options = $this->gatherColumnOptions($mapping) + $options; - if ($class->isIdGeneratorIdentity() && $class->getIdentifierFieldNames() == [$mapping['fieldName']]) { + if ($class->isIdGeneratorIdentity() && $class->getIdentifierFieldNames() === [$mapping['fieldName']]) { $options['autoincrement'] = true; } + if ($class->isInheritanceTypeJoined() && $class->name !== $class->rootEntityName) { $options['autoincrement'] = false; } @@ -505,12 +508,12 @@ private function gatherColumn($class, array $mapping, Table $table) * * @return void * - * @throws \Doctrine\ORM\ORMException + * @throws ORMException */ private function gatherRelationsSql($class, $table, $schema, &$addedFks, &$blacklistedFks) { foreach ($class->associationMappings as $id => $mapping) { - if (isset($mapping['inherited']) && ! \in_array($id, $class->identifier, true)) { + if (isset($mapping['inherited']) && ! in_array($id, $class->identifier, true)) { continue; } @@ -528,10 +531,10 @@ private function gatherRelationsSql($class, $table, $schema, &$addedFks, &$black $addedFks, $blacklistedFks ); - } elseif ($mapping['type'] == ClassMetadata::ONE_TO_MANY && $mapping['isOwningSide']) { + } 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']) { + } elseif ($mapping['type'] === ClassMetadata::MANY_TO_MANY && $mapping['isOwningSide']) { // create join table $joinTable = $mapping['joinTable']; @@ -593,8 +596,10 @@ private function getDefiningClass($class, $referencedColumnName) 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) { + if ( + $class->hasAssociation($fieldName) + && $class->getSingleAssociationJoinColumnName($fieldName) === $referencedColumnName + ) { return $this->getDefiningClass( $this->em->getClassMetadata($class->associationMappings[$fieldName]['targetEntity']), $class->getSingleAssociationReferencedJoinColumnName($fieldName) @@ -619,7 +624,7 @@ private function getDefiningClass($class, $referencedColumnName) * * @return void * - * @throws \Doctrine\ORM\ORMException + * @throws ORMException */ private function gatherRelationJoinColumns( $joinColumns, @@ -629,23 +634,21 @@ private function gatherRelationJoinColumns( &$primaryKeyColumns, &$addedFks, &$blacklistedFks - ) - { - $localColumns = []; - $foreignColumns = []; - $fkOptions = []; - $foreignTableName = $this->quoteStrategy->getTableName($class, $this->platform); - $uniqueConstraints = []; + ) { + $localColumns = []; + $foreignColumns = []; + $fkOptions = []; + $foreignTableName = $this->quoteStrategy->getTableName($class, $this->platform); + $uniqueConstraints = []; foreach ($joinColumns as $joinColumn) { - [$definingClass, $referencedFieldName] = $this->getDefiningClass( $class, $joinColumn['referencedColumnName'] ); - if ( ! $definingClass) { - throw new \Doctrine\ORM\ORMException( + if (! $definingClass) { + throw new ORMException( 'Column name `' . $joinColumn['referencedColumnName'] . '` referenced for relation from ' . $mapping['sourceEntity'] . ' towards ' . $mapping['targetEntity'] . ' does not exist.' ); @@ -662,7 +665,7 @@ private function gatherRelationJoinColumns( $localColumns[] = $quotedColumnName; $foreignColumns[] = $quotedRefColumnName; - if ( ! $theJoinTable->hasColumn($quotedColumnName)) { + 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. @@ -682,19 +685,19 @@ private function gatherRelationJoinColumns( $columnOptions['notnull'] = ! $joinColumn['nullable']; } - $columnOptions = $columnOptions + $this->gatherColumnOptions($fieldMapping); + $columnOptions += $this->gatherColumnOptions($fieldMapping); - if ($fieldMapping['type'] == "string" && isset($fieldMapping['length'])) { + if ($fieldMapping['type'] === 'string' && isset($fieldMapping['length'])) { $columnOptions['length'] = $fieldMapping['length']; - } elseif ($fieldMapping['type'] == "decimal") { - $columnOptions['scale'] = $fieldMapping['scale']; + } elseif ($fieldMapping['type'] === 'decimal') { + $columnOptions['scale'] = $fieldMapping['scale']; $columnOptions['precision'] = $fieldMapping['precision']; } $theJoinTable->addColumn($quotedColumnName, $fieldMapping['type'], $columnOptions); } - if (isset($joinColumn['unique']) && $joinColumn['unique'] == true) { + if (isset($joinColumn['unique']) && $joinColumn['unique'] === true) { $uniqueConstraints[] = ['columns' => [$quotedColumnName]]; } @@ -709,22 +712,25 @@ private function gatherRelationJoinColumns( $theJoinTable->addUniqueIndex($unique['columns'], is_numeric($indexName) ? null : $indexName); } - $compositeName = $theJoinTable->getName().'.'.implode('', $localColumns); - if (isset($addedFks[$compositeName]) - && ($foreignTableName != $addedFks[$compositeName]['foreignTableName'] + $compositeName = $theJoinTable->getName() . '.' . implode('', $localColumns); + if ( + isset($addedFks[$compositeName]) + && ($foreignTableName !== $addedFks[$compositeName]['foreignTableName'] || 0 < count(array_diff($foreignColumns, $addedFks[$compositeName]['foreignColumns']))) ) { foreach ($theJoinTable->getForeignKeys() as $fkName => $key) { - if (0 === count(array_diff($key->getLocalColumns(), $localColumns)) - && (($key->getForeignTableName() != $foreignTableName) + if ( + count(array_diff($key->getLocalColumns(), $localColumns)) === 0 + && (($key->getForeignTableName() !== $foreignTableName) || 0 < count(array_diff($key->getForeignColumns(), $foreignColumns))) ) { $theJoinTable->removeForeignKey($fkName); break; } } + $blacklistedFks[$compositeName] = true; - } elseif ( ! isset($blacklistedFks[$compositeName])) { + } elseif (! isset($blacklistedFks[$compositeName])) { $addedFks[$compositeName] = ['foreignTableName' => $foreignTableName, 'foreignColumns' => $foreignColumns]; $theJoinTable->addUnnamedForeignKeyConstraint( $foreignTableName, @@ -740,13 +746,13 @@ private function gatherRelationJoinColumns( * * @return mixed[] */ - private function gatherColumnOptions(array $mapping) : array + private function gatherColumnOptions(array $mapping): array { if (! isset($mapping['options'])) { return []; } - $options = array_intersect_key($mapping['options'], array_flip(self::KNOWN_COLUMN_OPTIONS)); + $options = array_intersect_key($mapping['options'], array_flip(self::KNOWN_COLUMN_OPTIONS)); $options['customSchemaOptions'] = array_diff_key($mapping['options'], $options); return $options; @@ -765,12 +771,12 @@ private function gatherColumnOptions(array $mapping) : array public function dropSchema(array $classes) { $dropSchemaSql = $this->getDropSchemaSQL($classes); - $conn = $this->em->getConnection(); + $conn = $this->em->getConnection(); foreach ($dropSchemaSql as $sql) { try { $conn->executeQuery($sql); - } catch (\Throwable $e) { + } catch (Throwable $e) { // ignored } } @@ -784,7 +790,7 @@ public function dropSchema(array $classes) public function dropDatabase() { $dropSchemaSql = $this->getDropDatabaseSQL(); - $conn = $this->em->getConnection(); + $conn = $this->em->getConnection(); foreach ($dropSchemaSql as $sql) { $conn->executeQuery($sql); @@ -798,7 +804,7 @@ public function dropDatabase() */ public function getDropDatabaseSQL() { - $sm = $this->em->getConnection()->getSchemaManager(); + $sm = $this->em->getConnection()->getSchemaManager(); $schema = $sm->createSchema(); $visitor = new DropSchemaSqlCollector($this->platform); @@ -817,13 +823,13 @@ public function getDropDatabaseSQL() public function getDropSchemaSQL(array $classes) { $visitor = new DropSchemaSqlCollector($this->platform); - $schema = $this->getSchemaFromMetadata($classes); + $schema = $this->getSchemaFromMetadata($classes); - $sm = $this->em->getConnection()->getSchemaManager(); + $sm = $this->em->getConnection()->getSchemaManager(); $fullSchema = $sm->createSchema(); foreach ($fullSchema->getTables() as $table) { - if ( ! $schema->hasTable($table->getName())) { + if (! $schema->hasTable($table->getName())) { foreach ($table->getForeignKeys() as $foreignKey) { if ($schema->hasTable($foreignKey->getForeignTableName())) { $visitor->acceptForeignKey($table, $foreignKey); @@ -843,10 +849,10 @@ public function getDropSchemaSQL(array $classes) } foreach ($schema->getTables() as $table) { - /* @var $sequence Table */ + /** @var Table $sequence */ if ($table->hasPrimaryKey()) { $columns = $table->getPrimaryKey()->getColumns(); - if (count($columns) == 1) { + if (count($columns) === 1) { $checkSequence = $table->getName() . '_' . $columns[0] . '_seq'; if ($fullSchema->hasSequence($checkSequence)) { $visitor->acceptSequence($fullSchema->getSequence($checkSequence)); @@ -863,16 +869,16 @@ public function getDropSchemaSQL(array $classes) * Updates the database schema of the given classes by comparing the ClassMetadata * instances to the current database schema that is inspected. * - * @param array $classes - * @param boolean $saveMode If TRUE, only performs a partial update - * without dropping assets which are scheduled for deletion. + * @param array $classes + * @param bool $saveMode If TRUE, only performs a partial update + * without dropping assets which are scheduled for deletion. * * @return void */ public function updateSchema(array $classes, $saveMode = false) { $updateSchemaSql = $this->getUpdateSchemaSql($classes, $saveMode); - $conn = $this->em->getConnection(); + $conn = $this->em->getConnection(); foreach ($updateSchemaSql as $sql) { $conn->executeQuery($sql); @@ -883,15 +889,15 @@ public function updateSchema(array $classes, $saveMode = false) * Gets the sequence of SQL statements that need to be performed in order * to bring the given class mappings in-synch with the relational schema. * - * @param array $classes The classes to consider. - * @param boolean $saveMode If TRUE, only generates SQL for a partial update - * that does not include SQL for dropping assets which are scheduled for deletion. + * @param array $classes The classes to consider. + * @param bool $saveMode If TRUE, only generates SQL for a partial update + * that does not include SQL for dropping assets which are scheduled for deletion. * * @return string[] The sequence of SQL statements. */ public function getUpdateSchemaSql(array $classes, $saveMode = false) { - $toSchema = $this->getSchemaFromMetadata($classes); + $toSchema = $this->getSchemaFromMetadata($classes); $fromSchema = $this->createSchemaForComparison($toSchema); $comparator = new Comparator(); @@ -907,7 +913,7 @@ public function getUpdateSchemaSql(array $classes, $saveMode = false) /** * Creates the schema from the database, ensuring tables from the target schema are whitelisted for comparison. */ - private function createSchemaForComparison(Schema $toSchema) : Schema + private function createSchemaForComparison(Schema $toSchema): Schema { $connection = $this->em->getConnection(); $schemaManager = $connection->getSchemaManager(); @@ -921,7 +927,7 @@ private function createSchemaForComparison(Schema $toSchema) : Schema } // whitelist assets we already know about in $toSchema, use the existing filter otherwise - $config->setSchemaAssetsFilter(static function ($asset) use ($previousFilter, $toSchema) : bool { + $config->setSchemaAssetsFilter(static function ($asset) use ($previousFilter, $toSchema): bool { $assetName = $asset instanceof AbstractAsset ? $asset->getName() : $asset; return $toSchema->hasTable($assetName) || $toSchema->hasSequence($assetName) || $previousFilter($asset); diff --git a/lib/Doctrine/ORM/Tools/SchemaValidator.php b/lib/Doctrine/ORM/Tools/SchemaValidator.php index ff38d458877..6f17884febd 100644 --- a/lib/Doctrine/ORM/Tools/SchemaValidator.php +++ b/lib/Doctrine/ORM/Tools/SchemaValidator.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class SchemaValidator { - /** - * @var EntityManagerInterface - */ + /** @var EntityManagerInterface */ private $em; - /** - * @param EntityManagerInterface $em - */ public function __construct(EntityManagerInterface $em) { $this->em = $em; @@ -64,8 +62,8 @@ public function __construct(EntityManagerInterface $em) */ public function validateMapping() { - $errors = []; - $cmf = $this->em->getMetadataFactory(); + $errors = []; + $cmf = $this->em->getMetadataFactory(); $classes = $cmf->getAllMetadata(); foreach ($classes as $class) { @@ -80,20 +78,18 @@ public function validateMapping() /** * Validates a single class of the current. * - * @param ClassMetadataInfo $class - * * @return string[] * * @psalm-return list */ public function validateClass(ClassMetadataInfo $class) { - $ce = []; + $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'] . "'."; + if (! Type::hasType($mapping['type'])) { + $ce[] = "The field '" . $class->name . '#' . $fieldName . "' uses a non-existent type '" . $mapping['type'] . "'."; } } @@ -104,86 +100,87 @@ public function validateClass(ClassMetadataInfo $class) } foreach ($class->associationMappings as $fieldName => $assoc) { - if (!class_exists($assoc['targetEntity']) || $cmf->isTransient($assoc['targetEntity'])) { + 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.'; return $ce; } if ($assoc['mappedBy'] && $assoc['inversedBy']) { - $ce[] = "The association " . $class . "#" . $fieldName . " cannot be defined as both inverse and owning."; + $ce[] = 'The association ' . $class . '#' . $fieldName . ' cannot be defined as both inverse and owning.'; } $targetMetadata = $cmf->getMetadataFor($assoc['targetEntity']); 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[] = "Cannot map association '" . $class->name . '#' . $fieldName . ' as identifier, because ' . + "the target entity '" . $targetMetadata->name . "' also maps an association as identifier."; } 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."; + $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 ". + + 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."; + } elseif ($targetMetadata->associationMappings[$assoc['mappedBy']]['inversedBy'] !== $fieldName) { + $ce[] = 'The mappings ' . $class->name . '#' . $fieldName . ' and ' . + $assoc['targetEntity'] . '#' . $assoc['mappedBy'] . ' are ' . + 'inconsistent with each other.'; } } 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."; + $ce[] = 'The association ' . $class->name . '#' . $fieldName . ' refers to the inverse side ' . + 'field ' . $assoc['targetEntity'] . '#' . $assoc['inversedBy'] . ' which is not defined as association.'; } - 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 ". + 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."; + } elseif ($targetMetadata->associationMappings[$assoc['inversedBy']]['mappedBy'] !== $fieldName) { + $ce[] = 'The mappings ' . $class->name . '#' . $fieldName . ' and ' . + $assoc['targetEntity'] . '#' . $assoc['inversedBy'] . ' are ' . + 'inconsistent with each other.'; } // 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."; + 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.'; } } } if ($assoc['isOwningSide']) { - if ($assoc['type'] == ClassMetadataInfo::MANY_TO_MANY) { + if ($assoc['type'] === ClassMetadataInfo::MANY_TO_MANY) { $identifierColumns = $class->getIdentifierColumnNames(); foreach ($assoc['joinTable']['joinColumns'] as $joinColumn) { - if (!in_array($joinColumn['referencedColumnName'], $identifierColumns)) { + 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."'."; + "has to be a primary key column on the target entity class '" . $class->name . "'."; break; } } @@ -192,35 +189,34 @@ public function validateClass(ClassMetadataInfo $class) foreach ($assoc['joinTable']['inverseJoinColumns'] as $inverseJoinColumn) { if (! in_array($inverseJoinColumn['referencedColumnName'], $identifierColumns)) { $ce[] = "The referenced column name '" . $inverseJoinColumn['referencedColumnName'] . "' " . - "has to be a primary key column on the target entity class '" .$targetMetadata->name . "'."; + "has to be a primary key column on the target entity class '" . $targetMetadata->name . "'."; break; } } - if (count($targetMetadata->getIdentifierColumnNames()) != count($assoc['joinTable']['inverseJoinColumns'])) { + 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']))) . + "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($class->getIdentifierColumnNames()) != count($assoc['joinTable']['joinColumns'])) { + 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']))) . + "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."; } - } elseif ($assoc['type'] & ClassMetadataInfo::TO_ONE) { $identifierColumns = $targetMetadata->getIdentifierColumnNames(); foreach ($assoc['joinColumns'] as $joinColumn) { - if (!in_array($joinColumn['referencedColumnName'], $identifierColumns)) { + 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."'."; + "has to be a primary key column on the target entity class '" . $targetMetadata->name . "'."; } } - if (count($identifierColumns) != count($assoc['joinColumns'])) { + if (count($identifierColumns) !== count($assoc['joinColumns'])) { $ids = []; foreach ($assoc['joinColumns'] as $joinColumn) { @@ -228,8 +224,8 @@ public function validateClass(ClassMetadataInfo $class) } $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)) . + "have to match to ALL identifier columns of the target entity '" . $targetMetadata->name . "', " . + "however '" . implode(', ', array_diff($targetMetadata->getIdentifierColumnNames(), $ids)) . "' are missing."; } } @@ -237,19 +233,21 @@ public function validateClass(ClassMetadataInfo $class) 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 . "."; + 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."; + $ce[] = 'The association ' . $class->name . '#' . $fieldName . ' is ordered by a field ' . + $orderField . ' on ' . $targetMetadata->name . ' that is a collection-valued association.'; continue; } + 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."; + $ce[] = 'The association ' . $class->name . '#' . $fieldName . ' is ordered by a field ' . + $orderField . ' on ' . $targetMetadata->name . ' that is the inverse side of an association.'; continue; } } @@ -257,8 +255,8 @@ public function validateClass(ClassMetadataInfo $class) } 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 ". + 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."; } } @@ -277,6 +275,6 @@ public function schemaInSyncWithMetadata() $allMetadata = $this->em->getMetadataFactory()->getAllMetadata(); - return count($schemaTool->getUpdateSchemaSql($allMetadata, true)) == 0; + return count($schemaTool->getUpdateSchemaSql($allMetadata, true)) === 0; } } diff --git a/lib/Doctrine/ORM/Tools/Setup.php b/lib/Doctrine/ORM/Tools/Setup.php index 302db6797b3..1a47c402544 100644 --- a/lib/Doctrine/ORM/Tools/Setup.php +++ b/lib/Doctrine/ORM/Tools/Setup.php @@ -1,4 +1,5 @@ */ class Setup { @@ -44,29 +53,28 @@ class Setup */ public static function registerAutoloadDirectory($directory) { - if (!class_exists('Doctrine\Common\ClassLoader', false)) { - require_once $directory . "/Doctrine/Common/ClassLoader.php"; + if (! class_exists('Doctrine\Common\ClassLoader', false)) { + require_once $directory . '/Doctrine/Common/ClassLoader.php'; } - $loader = new ClassLoader("Doctrine", $directory); + $loader = new ClassLoader('Doctrine', $directory); $loader->register(); - $loader = new ClassLoader("Symfony\Component", $directory . "/Doctrine"); + $loader = new ClassLoader('Symfony\Component', $directory . '/Doctrine'); $loader->register(); } /** * Creates a configuration with an annotation metadata driver. * - * @param array $paths - * @param boolean $isDevMode - * @param string $proxyDir - * @param Cache $cache - * @param bool $useSimpleAnnotationReader + * @param array $paths + * @param bool $isDevMode + * @param string $proxyDir + * @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, $useSimpleAnnotationReader = true) { $config = self::createConfiguration($isDevMode, $proxyDir, $cache); $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver($paths, $useSimpleAnnotationReader)); @@ -77,14 +85,13 @@ public static function createAnnotationMetadataConfiguration(array $paths, $isDe /** * Creates a configuration with a xml metadata driver. * - * @param array $paths - * @param boolean $isDevMode - * @param string $proxyDir - * @param Cache $cache + * @param array $paths + * @param bool $isDevMode + * @param string $proxyDir * * @return Configuration */ - public static function createXMLMetadataConfiguration(array $paths, $isDevMode = false, $proxyDir = null, Cache $cache = null) + public static function createXMLMetadataConfiguration(array $paths, $isDevMode = false, $proxyDir = null, ?Cache $cache = null) { $config = self::createConfiguration($isDevMode, $proxyDir, $cache); $config->setMetadataDriverImpl(new XmlDriver($paths)); @@ -95,14 +102,13 @@ public static function createXMLMetadataConfiguration(array $paths, $isDevMode = /** * Creates a configuration with a yaml metadata driver. * - * @param array $paths - * @param boolean $isDevMode - * @param string $proxyDir - * @param Cache $cache + * @param array $paths + * @param bool $isDevMode + * @param string $proxyDir * * @return Configuration */ - public static function createYAMLMetadataConfiguration(array $paths, $isDevMode = false, $proxyDir = null, Cache $cache = null) + public static function createYAMLMetadataConfiguration(array $paths, $isDevMode = false, $proxyDir = null, ?Cache $cache = null) { $config = self::createConfiguration($isDevMode, $proxyDir, $cache); $config->setMetadataDriverImpl(new YamlDriver($paths)); @@ -115,11 +121,10 @@ public static function createYAMLMetadataConfiguration(array $paths, $isDevMode * * @param bool $isDevMode * @param string $proxyDir - * @param Cache $cache * * @return Configuration */ - public static function createConfiguration($isDevMode = false, $proxyDir = null, Cache $cache = null) + public static function createConfiguration($isDevMode = false, $proxyDir = null, ?Cache $cache = null) { $proxyDir = $proxyDir ?: sys_get_temp_dir(); @@ -136,11 +141,11 @@ public static function createConfiguration($isDevMode = false, $proxyDir = null, return $config; } - private static function createCacheConfiguration(bool $isDevMode, string $proxyDir, ?Cache $cache) : Cache + private static function createCacheConfiguration(bool $isDevMode, string $proxyDir, ?Cache $cache): Cache { $cache = self::createCacheInstance($isDevMode, $cache); - if ( ! $cache instanceof CacheProvider) { + if (! $cache instanceof CacheProvider) { return $cache; } @@ -155,7 +160,7 @@ private static function createCacheConfiguration(bool $isDevMode, string $proxyD return $cache; } - private static function createCacheInstance(bool $isDevMode, ?Cache $cache) : Cache + private static function createCacheInstance(bool $isDevMode, ?Cache $cache): Cache { if ($cache !== null) { return $cache; @@ -166,25 +171,24 @@ private static function createCacheInstance(bool $isDevMode, ?Cache $cache) : Ca } if (extension_loaded('apcu')) { - return new \Doctrine\Common\Cache\ApcuCache(); + return new ApcuCache(); } - if (extension_loaded('memcached')) { - $memcached = new \Memcached(); + $memcached = new Memcached(); $memcached->addServer('127.0.0.1', 11211); - $cache = new \Doctrine\Common\Cache\MemcachedCache(); + $cache = new MemcachedCache(); $cache->setMemcached($memcached); return $cache; } if (extension_loaded('redis')) { - $redis = new \Redis(); + $redis = new Redis(); $redis->connect('127.0.0.1'); - $cache = new \Doctrine\Common\Cache\RedisCache(); + $cache = new RedisCache(); $cache->setRedis($redis); return $cache; diff --git a/lib/Doctrine/ORM/Tools/ToolEvents.php b/lib/Doctrine/ORM/Tools/ToolEvents.php index aebb5d8f37d..cbfd9c0b367 100644 --- a/lib/Doctrine/ORM/Tools/ToolEvents.php +++ b/lib/Doctrine/ORM/Tools/ToolEvents.php @@ -1,4 +1,5 @@ */ class ToolsException extends ORMException { - public static function schemaToolFailure(string $sql, Throwable $e) : self + public static function schemaToolFailure(string $sql, Throwable $e): self { - return new self("Schema-Tool failed with Error '" . $e->getMessage() . "' while executing DDL: " . $sql, "0", $e); + 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..888a4f1a57e 100644 --- a/lib/Doctrine/ORM/TransactionRequiredException.php +++ b/lib/Doctrine/ORM/TransactionRequiredException.php @@ -1,4 +1,5 @@ - * @author Roman Borschel */ class TransactionRequiredException extends ORMException { /** * @return TransactionRequiredException */ - static public function transactionRequired() + public static function transactionRequired() { return new self('An open transaction is required for this operation.'); } diff --git a/lib/Doctrine/ORM/UnexpectedResultException.php b/lib/Doctrine/ORM/UnexpectedResultException.php index 3cd561f0965..6d509c9484e 100644 --- a/lib/Doctrine/ORM/UnexpectedResultException.php +++ b/lib/Doctrine/ORM/UnexpectedResultException.php @@ -1,4 +1,5 @@ - * @since 2.3 */ class UnexpectedResultException extends ORMException { diff --git a/lib/Doctrine/ORM/UnitOfWork.php b/lib/Doctrine/ORM/UnitOfWork.php index 53f5ff37f9b..ed4566f08a0 100644 --- a/lib/Doctrine/ORM/UnitOfWork.php +++ b/lib/Doctrine/ORM/UnitOfWork.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - * @author Rob Caiger */ class UnitOfWork implements PropertyChangedListener { /** * An entity is in MANAGED state when its persistence is managed by an EntityManager. */ - const STATE_MANAGED = 1; + public const STATE_MANAGED = 1; /** * An entity is new if it has just been instantiated (i.e. using the "new" operator) * and is not (yet) managed by an EntityManager. */ - const STATE_NEW = 2; + public const STATE_NEW = 2; /** * A detached entity is an instance with persistent state and identity that is not * (or no longer) associated with an EntityManager (and a UnitOfWork). */ - const STATE_DETACHED = 3; + public const STATE_DETACHED = 3; /** * A removed entity instance is an instance with a persistent identity, * associated with an EntityManager, whose persistent state will be deleted * on commit. */ - const STATE_REMOVED = 4; + public const STATE_REMOVED = 4; /** * Hint used to collect all primary keys of associated entities during hydration * and execute it in a dedicated query afterwards + * * @see https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html#temporarily-change-fetch-mode-in-dql */ - const HINT_DEFEREAGERLOAD = 'deferEagerLoad'; + public const HINT_DEFEREAGERLOAD = 'deferEagerLoad'; /** * The identity map that holds references to all managed entities that have @@ -241,21 +261,21 @@ class UnitOfWork implements PropertyChangedListener /** * The EventManager used for dispatching events. * - * @var \Doctrine\Common\EventManager + * @var EventManager */ private $evm; /** * The ListenersInvoker used for dispatching events. * - * @var \Doctrine\ORM\Event\ListenersInvoker + * @var ListenersInvoker */ private $listenersInvoker; /** * The IdentifierFlattener used for manipulating identifiers * - * @var \Doctrine\ORM\Utility\IdentifierFlattener + * @var IdentifierFlattener */ private $identifierFlattener; @@ -280,9 +300,7 @@ class UnitOfWork implements PropertyChangedListener */ private $eagerLoadingEntities = []; - /** - * @var boolean - */ + /** @var bool */ protected $hasCache = false; /** @@ -292,15 +310,11 @@ class UnitOfWork implements PropertyChangedListener */ private $hydrationCompleteHandler; - /** - * @var ReflectionPropertiesGetter - */ + /** @var ReflectionPropertiesGetter */ private $reflectionPropertiesGetter; /** * Initializes a new UnitOfWork instance, bound to the given EntityManager. - * - * @param EntityManagerInterface $em */ public function __construct(EntityManagerInterface $em) { @@ -326,11 +340,11 @@ public function __construct(EntityManagerInterface $em) * 4) All collection updates * 5) All entity deletions * - * @param null|object|array $entity + * @param object|array|null $entity * * @return void * - * @throws \Exception + * @throws Exception */ public function commit($entity = null) { @@ -340,7 +354,7 @@ public function commit($entity = null) } // Compute changes done since last commit. - if (null === $entity) { + if ($entity === null) { $this->computeChangeSets(); } elseif (is_object($entity)) { $this->computeSingleEntityChangeSet($entity); @@ -350,12 +364,14 @@ public function commit($entity = null) } } - if ( ! ($this->entityInsertions || + if ( + ! ($this->entityInsertions || $this->entityDeletions || $this->entityUpdates || $this->collectionUpdates || $this->collectionDeletions || - $this->orphanRemovals)) { + $this->orphanRemovals) + ) { $this->dispatchOnFlushEvent(); $this->dispatchPostFlushEvent(); @@ -457,27 +473,27 @@ public function commit($entity = null) } /** - * @param null|object|object[] $entity + * @param object|object[]|null $entity */ - private function postCommitCleanup($entity) : void + private function postCommitCleanup($entity): void { - $this->entityInsertions = - $this->entityUpdates = - $this->entityDeletions = - $this->extraUpdates = - $this->collectionUpdates = + $this->entityInsertions = + $this->entityUpdates = + $this->entityDeletions = + $this->extraUpdates = + $this->collectionUpdates = $this->nonCascadedNewDetectedEntities = - $this->collectionDeletions = - $this->visitedCollections = - $this->orphanRemovals = []; + $this->collectionDeletions = + $this->visitedCollections = + $this->orphanRemovals = []; - if (null === $entity) { + if ($entity === null) { $this->entityChangeSets = $this->scheduledForSynchronization = []; return; } - $entities = \is_object($entity) + $entities = is_object($entity) ? [$entity] : $entity; @@ -486,7 +502,7 @@ private function postCommitCleanup($entity) : void $this->clearEntityChangeSet($oid); - unset($this->scheduledForSynchronization[$this->em->getClassMetadata(\get_class($object))->rootEntityName][$oid]); + unset($this->scheduledForSynchronization[$this->em->getClassMetadata(get_class($object))->rootEntityName][$oid]); } } @@ -516,14 +532,14 @@ private function computeScheduleInsertsChangeSets() * * @return void * - * @throws \InvalidArgumentException + * @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)); + 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)); @@ -547,7 +563,7 @@ private function computeSingleEntityChangeSet($entity) // 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])) { + if (! isset($this->entityInsertions[$oid]) && ! isset($this->entityDeletions[$oid]) && isset($this->entityStates[$oid])) { $this->computeChangeSet($class, $entity); } } @@ -579,7 +595,7 @@ public function & getEntityChangeSet($entity) $oid = spl_object_hash($entity); $data = []; - if (!isset($this->entityChangeSets[$oid])) { + if (! isset($this->entityChangeSets[$oid])) { return $data; } @@ -611,14 +627,14 @@ public function & getEntityChangeSet($entity) * If a PersistentCollection has been de-referenced in a fully MANAGED entity, * then this collection is marked for deletion. * - * @ignore - * * @internal Don't call from the outside. * * @param ClassMetadata $class The class descriptor of the entity. * @param object $entity The entity for which to compute the changes. * * @return void + * + * @ignore */ public function computeChangeSet(ClassMetadata $class, $entity) { @@ -628,7 +644,7 @@ public function computeChangeSet(ClassMetadata $class, $entity) return; } - if ( ! $class->isInheritanceTypeNone()) { + if (! $class->isInheritanceTypeNone()) { $class = $this->em->getClassMetadata(get_class($entity)); } @@ -653,7 +669,7 @@ public function computeChangeSet(ClassMetadata $class, $entity) } // If $value is not a Collection then use an ArrayCollection. - if ( ! $value instanceof Collection) { + if (! $value instanceof Collection) { $value = new ArrayCollection($value); } @@ -661,10 +677,12 @@ public function computeChangeSet(ClassMetadata $class, $entity) // Inject PersistentCollection $value = new PersistentCollection( - $this->em, $this->em->getClassMetadata($assoc['targetEntity']), $value + $this->em, + $this->em->getClassMetadata($assoc['targetEntity']), + $value ); $value->setOwner($entity, $assoc); - $value->setDirty( ! $value->isEmpty()); + $value->setDirty(! $value->isEmpty()); $class->reflFields[$name]->setValue($entity, $value); @@ -678,14 +696,14 @@ public function computeChangeSet(ClassMetadata $class, $entity) } } - if ( ! isset($this->originalEntityData[$oid])) { + if (! isset($this->originalEntityData[$oid])) { // Entity is either NEW or MANAGED but not yet fully persisted (only has an id). // These result in an INSERT. $this->originalEntityData[$oid] = $actualData; - $changeSet = []; + $changeSet = []; foreach ($actualData as $propName => $actualValue) { - if ( ! isset($class->associationMappings[$propName])) { + if (! isset($class->associationMappings[$propName])) { $changeSet[$propName] = [null, $actualValue]; continue; @@ -704,13 +722,13 @@ public function computeChangeSet(ClassMetadata $class, $entity) // and we have a copy of the original data $originalData = $this->originalEntityData[$oid]; $isChangeTrackingNotify = $class->isChangeTrackingNotify(); - $changeSet = ($isChangeTrackingNotify && isset($this->entityChangeSets[$oid])) + $changeSet = $isChangeTrackingNotify && isset($this->entityChangeSets[$oid]) ? $this->entityChangeSets[$oid] : []; foreach ($actualData as $propName => $actualValue) { // skip field, its a partially omitted one! - if ( ! (isset($originalData[$propName]) || array_key_exists($propName, $originalData))) { + if (! (isset($originalData[$propName]) || array_key_exists($propName, $originalData))) { continue; } @@ -722,7 +740,7 @@ public function computeChangeSet(ClassMetadata $class, $entity) } // if regular field - if ( ! isset($class->associationMappings[$propName])) { + if (! isset($class->associationMappings[$propName])) { if ($isChangeTrackingNotify) { continue; } @@ -741,10 +759,11 @@ public function computeChangeSet(ClassMetadata $class, $entity) $owner = $actualValue->getOwner(); if ($owner === null) { // cloned $actualValue->setOwner($entity, $assoc); - } else if ($owner !== $entity) { // no clone, we have to fix - if (!$actualValue->isInitialized()) { + } elseif ($owner !== $entity) { // no clone, we have to fix + 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); @@ -760,7 +779,7 @@ public function computeChangeSet(ClassMetadata $class, $entity) } $this->collectionDeletions[$coid] = $orgValue; - $changeSet[$propName] = $orgValue; // Signal changeset, to-many assocs will be ignored. + $changeSet[$propName] = $orgValue; // Signal changeset, to-many assocs will be ignored. continue; } @@ -791,12 +810,13 @@ public function computeChangeSet(ClassMetadata $class, $entity) $this->computeAssociationChanges($assoc, $val); - if ( ! isset($this->entityChangeSets[$oid]) && + if ( + ! isset($this->entityChangeSets[$oid]) && $assoc['isOwningSide'] && - $assoc['type'] == ClassMetadata::MANY_TO_MANY && + $assoc['type'] === ClassMetadata::MANY_TO_MANY && $val instanceof PersistentCollection && - $val->isDirty()) { - + $val->isDirty() + ) { $this->entityChangeSets[$oid] = []; $this->originalEntityData[$oid] = $actualData; $this->entityUpdates[$oid] = $entity; @@ -828,17 +848,16 @@ public function computeChangeSets() // 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->isChangeTrackingDeferredImplicit(): $entitiesToProcess = $entities; break; - case (isset($this->scheduledForSynchronization[$className])): + case isset($this->scheduledForSynchronization[$className]): $entitiesToProcess = $this->scheduledForSynchronization[$className]; break; default: $entitiesToProcess = []; - } foreach ($entitiesToProcess as $entity) { @@ -850,7 +869,7 @@ public function computeChangeSets() // 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])) { + if (! isset($this->entityInsertions[$oid]) && ! isset($this->entityDeletions[$oid]) && isset($this->entityStates[$oid])) { $this->computeChangeSet($class, $entity); } } @@ -863,10 +882,10 @@ public function computeChangeSets() * @param array $assoc The association mapping. * @param mixed $value The value of the association. * + * @return void + * * @throws ORMInvalidArgumentException * @throws ORMException - * - * @return void */ private function computeAssociationChanges($assoc, $value) { @@ -877,14 +896,14 @@ private function computeAssociationChanges($assoc, $value) if ($value instanceof PersistentCollection && $value->isDirty()) { $coid = spl_object_hash($value); - $this->collectionUpdates[$coid] = $value; + $this->collectionUpdates[$coid] = $value; $this->visitedCollections[$coid] = $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(); + $unwrappedValue = $assoc['type'] & ClassMetadata::TO_ONE ? [$value] : $value->unwrap(); $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); foreach ($unwrappedValue as $key => $entry) { @@ -894,13 +913,13 @@ private function computeAssociationChanges($assoc, $value) $state = $this->getEntityState($entry, self::STATE_NEW); - if ( ! ($entry instanceof $assoc['targetEntity'])) { + if (! ($entry instanceof $assoc['targetEntity'])) { throw ORMException::unexpectedAssociationValue($assoc['sourceEntity'], $assoc['fieldName'], get_class($entry), $assoc['targetEntity']); } switch ($state) { case self::STATE_NEW: - if ( ! $assoc['isCascadePersist']) { + if (! $assoc['isCascadePersist']) { /* * For now just record the details, because this may * not be an issue if we later discover another pathway @@ -923,12 +942,14 @@ private function computeAssociationChanges($assoc, $value) if ($assoc['type'] & ClassMetadata::TO_MANY) { unset($value[$key]); } + break; 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); + break; default: @@ -939,8 +960,8 @@ private function computeAssociationChanges($assoc, $value) } /** - * @param \Doctrine\ORM\Mapping\ClassMetadata $class - * @param object $entity + * @param ClassMetadata $class + * @param object $entity * * @return void */ @@ -955,10 +976,10 @@ private function persistNew($class, $entity) $idGen = $class->idGenerator; - if ( ! $idGen->isPostInsertGenerator()) { + if (! $idGen->isPostInsertGenerator()) { $idValue = $idGen->generate($this->em, $entity); - if ( ! $idGen instanceof \Doctrine\ORM\Id\AssignedGenerator) { + if (! $idGen instanceof AssignedGenerator) { $idValue = [$class->getSingleIdentifierFieldName() => $this->convertSingleFieldIdentifierToPHPValue($class, $idValue)]; $class->setIdentifierValues($entity, $idValue); @@ -979,7 +1000,7 @@ private function persistNew($class, $entity) /** * @param mixed[] $idValue */ - private function hasMissingIdsWhichAreForeignKeys(ClassMetadata $class, array $idValue) : bool + private function hasMissingIdsWhichAreForeignKeys(ClassMetadata $class, array $idValue): bool { foreach ($idValue as $idField => $idFieldValue) { if ($idFieldValue === null && isset($class->associationMappings[$idField])) { @@ -999,20 +1020,20 @@ private function hasMissingIdsWhichAreForeignKeys(ClassMetadata $class, array $i * because this method is invoked during a commit cycle then the change sets are added. * whereby changes detected in this method prevail. * - * @ignore - * * @param ClassMetadata $class The class descriptor of the entity. * @param object $entity The entity for which to (re)calculate the change set. * * @return void * * @throws ORMInvalidArgumentException If the passed entity is not MANAGED. + * + * @ignore */ public function recomputeSingleEntityChangeSet(ClassMetadata $class, $entity) { $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); } @@ -1021,26 +1042,28 @@ public function recomputeSingleEntityChangeSet(ClassMetadata $class, $entity) return; } - if ( ! $class->isInheritanceTypeNone()) { + if (! $class->isInheritanceTypeNone()) { $class = $this->em->getClassMetadata(get_class($entity)); } $actualData = []; foreach ($class->reflFields as $name => $refProp) { - if (( ! $class->isIdentifier($name) || ! $class->isIdGeneratorIdentity()) + if ( + ( ! $class->isIdentifier($name) || ! $class->isIdGeneratorIdentity()) && ($name !== $class->versionField) - && ! $class->isCollectionValuedAssociation($name)) { + && ! $class->isCollectionValuedAssociation($name) + ) { $actualData[$name] = $refProp->getValue($entity); } } - if ( ! isset($this->originalEntityData[$oid])) { - throw new \RuntimeException('Cannot call recomputeSingleEntityChangeSet before computeChangeSet on an entity.'); + if (! isset($this->originalEntityData[$oid])) { + throw new RuntimeException('Cannot call recomputeSingleEntityChangeSet before computeChangeSet on an entity.'); } $originalData = $this->originalEntityData[$oid]; - $changeSet = []; + $changeSet = []; foreach ($actualData as $propName => $actualValue) { $orgValue = $originalData[$propName] ?? null; @@ -1053,10 +1076,11 @@ public function recomputeSingleEntityChangeSet(ClassMetadata $class, $entity) if ($changeSet) { if (isset($this->entityChangeSets[$oid])) { $this->entityChangeSets[$oid] = array_merge($this->entityChangeSets[$oid], $changeSet); - } else if ( ! isset($this->entityInsertions[$oid])) { + } elseif (! isset($this->entityInsertions[$oid])) { $this->entityChangeSets[$oid] = $changeSet; $this->entityUpdates[$oid] = $entity; } + $this->originalEntityData[$oid] = $actualData; } } @@ -1064,21 +1088,20 @@ 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) { - $entities = []; - $className = $class->name; - $persister = $this->getEntityPersister($className); - $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postPersist); + $entities = []; + $className = $class->name; + $persister = $this->getEntityPersister($className); + $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postPersist); $insertionsForClass = []; foreach ($this->entityInsertions as $oid => $entity) { - if ($this->em->getClassMetadata(get_class($entity))->name !== $className) { continue; } @@ -1102,13 +1125,13 @@ private function executeInserts($class) $idField = $class->getSingleIdentifierFieldName(); $idValue = $this->convertSingleFieldIdentifierToPHPValue($class, $postInsertId['generatedId']); - $entity = $postInsertId['entity']; - $oid = spl_object_hash($entity); + $entity = $postInsertId['entity']; + $oid = spl_object_hash($entity); $class->reflFields[$idField]->setValue($entity, $idValue); - $this->entityIdentifiers[$oid] = [$idField => $idValue]; - $this->entityStates[$oid] = self::STATE_MANAGED; + $this->entityIdentifiers[$oid] = [$idField => $idValue]; + $this->entityStates[$oid] = self::STATE_MANAGED; $this->originalEntityData[$oid][$idField] = $idValue; $this->addToIdentityMap($entity); @@ -1155,35 +1178,35 @@ private function addToEntityIdentifiersAndEntityMap(ClassMetadata $class, string /** * Executes all entity updates for entities of the specified type. * - * @param \Doctrine\ORM\Mapping\ClassMetadata $class + * @param ClassMetadata $class * * @return void */ private function executeUpdates($class) { - $className = $class->name; - $persister = $this->getEntityPersister($className); - $preUpdateInvoke = $this->listenersInvoker->getSubscribedSystems($class, Events::preUpdate); - $postUpdateInvoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postUpdate); + $className = $class->name; + $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) { continue; } - if ($preUpdateInvoke != ListenersInvoker::INVOKE_NONE) { + if ($preUpdateInvoke !== ListenersInvoker::INVOKE_NONE) { $this->listenersInvoker->invoke($class, Events::preUpdate, $entity, new PreUpdateEventArgs($entity, $this->em, $this->getEntityChangeSet($entity)), $preUpdateInvoke); $this->recomputeSingleEntityChangeSet($class, $entity); } - if ( ! empty($this->entityChangeSets[$oid])) { + if (! empty($this->entityChangeSets[$oid])) { $persister->update($entity); } unset($this->entityUpdates[$oid]); - if ($postUpdateInvoke != ListenersInvoker::INVOKE_NONE) { + if ($postUpdateInvoke !== ListenersInvoker::INVOKE_NONE) { $this->listenersInvoker->invoke($class, Events::postUpdate, $entity, new LifecycleEventArgs($entity, $this->em), $postUpdateInvoke); } } @@ -1192,15 +1215,15 @@ private function executeUpdates($class) /** * Executes all entity deletions for entities of the specified type. * - * @param \Doctrine\ORM\Mapping\ClassMetadata $class + * @param ClassMetadata $class * * @return void */ private function executeDeletions($class) { - $className = $class->name; - $persister = $this->getEntityPersister($className); - $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postRemove); + $className = $class->name; + $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) { @@ -1219,7 +1242,7 @@ 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()) { + if (! $class->isIdentifierNatural()) { $class->reflFields[$class->identifier[0]]->setValue($entity, null); } @@ -1236,7 +1259,7 @@ private function executeDeletions($class) * * @return array */ - private function getCommitOrder(array $entityChangeSet = null) + private function getCommitOrder(?array $entityChangeSet = null) { if ($entityChangeSet === null) { $entityChangeSet = array_merge($this->entityInsertions, $this->entityUpdates, $this->entityDeletions); @@ -1266,13 +1289,13 @@ private function getCommitOrder(array $entityChangeSet = null) // Calculate dependencies for new nodes while ($class = array_pop($newNodes)) { foreach ($class->associationMappings as $assoc) { - if ( ! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE)) { + if (! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE)) { continue; } $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); - if ( ! $calc->hasNode($targetClass->name)) { + if (! $calc->hasNode($targetClass->name)) { $calc->addNode($targetClass->name, $targetClass); $newNodes[] = $targetClass; @@ -1280,17 +1303,17 @@ private function getCommitOrder(array $entityChangeSet = null) $joinColumns = reset($assoc['joinColumns']); - $calc->addDependency($targetClass->name, $class->name, (int)empty($joinColumns['nullable'])); + $calc->addDependency($targetClass->name, $class->name, (int) empty($joinColumns['nullable'])); // If the target class has mapped subclasses, these share the same dependency. - if ( ! $targetClass->subClasses) { + if (! $targetClass->subClasses) { continue; } foreach ($targetClass->subClasses as $subClassName) { $targetSubClass = $this->em->getClassMetadata($subClassName); - if ( ! $calc->hasNode($subClassName)) { + if (! $calc->hasNode($subClassName)) { $calc->addNode($targetSubClass->name, $targetSubClass); $newNodes[] = $targetSubClass; @@ -1313,19 +1336,20 @@ private function getCommitOrder(array $entityChangeSet = null) * @return void * * @throws ORMInvalidArgumentException - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public function scheduleForInsert($entity) { $oid = spl_object_hash($entity); if (isset($this->entityUpdates[$oid])) { - throw new InvalidArgumentException("Dirty entity can not be scheduled for insertion."); + throw new InvalidArgumentException('Dirty entity can not be scheduled for insertion.'); } if (isset($this->entityDeletions[$oid])) { throw ORMInvalidArgumentException::scheduleInsertForRemovedEntity($entity); } + if (isset($this->originalEntityData[$oid]) && ! isset($this->entityInsertions[$oid])) { throw ORMInvalidArgumentException::scheduleInsertForManagedEntity($entity); } @@ -1350,7 +1374,7 @@ public function scheduleForInsert($entity) * * @param object $entity * - * @return boolean + * @return bool */ public function isScheduledForInsert($entity) { @@ -1370,15 +1394,15 @@ public function scheduleForUpdate($entity) { $oid = spl_object_hash($entity); - if ( ! isset($this->entityIdentifiers[$oid])) { - throw ORMInvalidArgumentException::entityHasNoIdentity($entity, "scheduling for update"); + if (! isset($this->entityIdentifiers[$oid])) { + throw ORMInvalidArgumentException::entityHasNoIdentity($entity, 'scheduling for update'); } if (isset($this->entityDeletions[$oid])) { - throw ORMInvalidArgumentException::entityIsRemoved($entity, "schedule for update"); + throw ORMInvalidArgumentException::entityIsRemoved($entity, 'schedule for update'); } - if ( ! isset($this->entityUpdates[$oid]) && ! isset($this->entityInsertions[$oid])) { + if (! isset($this->entityUpdates[$oid]) && ! isset($this->entityInsertions[$oid])) { $this->entityUpdates[$oid] = $entity; } } @@ -1390,12 +1414,12 @@ public function scheduleForUpdate($entity) * * Extra updates for entities are stored as (entity, changeset) tuples. * - * @ignore - * * @param object $entity The entity for which to schedule an extra update. * @param array $changeset The changeset of the entity (what to update). * * @return void + * + * @ignore */ public function scheduleExtraUpdate($entity, array $changeset) { @@ -1418,7 +1442,7 @@ public function scheduleExtraUpdate($entity, array $changeset) * * @param object $entity * - * @return boolean + * @return bool */ public function isScheduledForUpdate($entity) { @@ -1430,7 +1454,7 @@ public function isScheduledForUpdate($entity) * * @param object $entity * - * @return boolean + * @return bool */ public function isScheduledForDirtyCheck($entity) { @@ -1461,7 +1485,7 @@ public function scheduleForDelete($entity) return; // entity has not been persisted yet, so nothing more to do. } - if ( ! $this->isInIdentityMap($entity)) { + if (! $this->isInIdentityMap($entity)) { return; } @@ -1469,7 +1493,7 @@ public function scheduleForDelete($entity) unset($this->entityUpdates[$oid]); - if ( ! isset($this->entityDeletions[$oid])) { + if (! isset($this->entityDeletions[$oid])) { $this->entityDeletions[$oid] = $entity; $this->entityStates[$oid] = self::STATE_REMOVED; } @@ -1481,7 +1505,7 @@ public function scheduleForDelete($entity) * * @param object $entity * - * @return boolean + * @return bool */ public function isScheduledForDelete($entity) { @@ -1493,7 +1517,7 @@ public function isScheduledForDelete($entity) * * @param object $entity * - * @return boolean + * @return bool */ public function isEntityScheduled($entity) { @@ -1510,14 +1534,14 @@ public function isEntityScheduled($entity) * Note that entities in a hierarchy are registered with the class name of * the root entity. * - * @ignore - * * @param object $entity The entity to register. * - * @return boolean TRUE if the registration was successful, FALSE if the identity of - * the entity in question is already managed. + * @return bool TRUE if the registration was successful, FALSE if the identity of + * the entity in question is already managed. * * @throws ORMInvalidArgumentException + * + * @ignore */ public function addToIdentityMap($entity) { @@ -1570,7 +1594,7 @@ public function getEntityState($entity, $assume = null) $class = $this->em->getClassMetadata(get_class($entity)); $id = $class->getIdentifierValues($entity); - if ( ! $id) { + if (! $id) { return self::STATE_NEW; } @@ -1579,10 +1603,10 @@ public function getEntityState($entity, $assume = null) } switch (true) { - case ($class->isIdentifierNatural()): + case $class->isIdentifierNatural(): // Check for a version field, if available, to avoid a db lookup. if ($class->isVersioned) { - return ($class->getFieldValue($entity, $class->versionField)) + return $class->getFieldValue($entity, $class->versionField) ? self::STATE_DETACHED : self::STATE_NEW; } @@ -1599,7 +1623,7 @@ public function getEntityState($entity, $assume = null) return self::STATE_NEW; - case ( ! $class->idGenerator->isPostInsertGenerator()): + 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 @@ -1626,13 +1650,13 @@ public function getEntityState($entity, $assume = null) * Removes an entity from the identity map. This effectively detaches the * entity from the persistence management of Doctrine. * - * @ignore - * * @param object $entity * - * @return boolean + * @return bool * * @throws ORMInvalidArgumentException + * + * @ignore */ public function removeFromIdentityMap($entity) { @@ -1641,7 +1665,7 @@ public function removeFromIdentityMap($entity) $idHash = implode(' ', $this->entityIdentifiers[$oid]); if ($idHash === '') { - throw ORMInvalidArgumentException::entityHasNoIdentity($entity, "remove from identity map"); + throw ORMInvalidArgumentException::entityHasNoIdentity($entity, 'remove from identity map'); } $className = $classMetadata->rootEntityName; @@ -1662,12 +1686,12 @@ public function removeFromIdentityMap($entity) * INTERNAL: * Gets an entity in the identity map by its identifier hash. * - * @ignore - * * @param string $idHash * @param string $rootClassName * * @return object + * + * @ignore */ public function getByIdHash($idHash, $rootClassName) { @@ -1679,20 +1703,18 @@ public function getByIdHash($idHash, $rootClassName) * Tries to get an entity by its identifier hash. If no entity is found for * the given hash, FALSE is returned. * - * @ignore - * * @param mixed $idHash (must be possible to cast it to string) * @param string $rootClassName * * @return object|bool The found entity or FALSE. + * + * @ignore */ public function tryGetByIdHash($idHash, $rootClassName) { $stringIdHash = (string) $idHash; - return isset($this->identityMap[$rootClassName][$stringIdHash]) - ? $this->identityMap[$rootClassName][$stringIdHash] - : false; + return $this->identityMap[$rootClassName][$stringIdHash] ?? false; } /** @@ -1700,7 +1722,7 @@ public function tryGetByIdHash($idHash, $rootClassName) * * @param object $entity * - * @return boolean + * @return bool */ public function isInIdentityMap($entity) { @@ -1720,12 +1742,12 @@ public function isInIdentityMap($entity) * INTERNAL: * Checks whether an identifier hash exists in the identity map. * - * @ignore - * * @param string $idHash * @param string $rootClassName * - * @return boolean + * @return bool + * + * @ignore */ public function containsIdHash($idHash, $rootClassName) { @@ -1784,6 +1806,7 @@ private function doPersist($entity, array &$visited) if ($class->isChangeTrackingDeferredExplicit()) { $this->scheduleForDirtyCheck($entity); } + break; case self::STATE_NEW: @@ -1800,11 +1823,12 @@ private function doPersist($entity, array &$visited) if ($class->isChangeTrackingDeferredExplicit()) { $this->scheduleForDirtyCheck($entity); } + break; case self::STATE_DETACHED: // Can actually not happen right now since we assume STATE_NEW. - throw ORMInvalidArgumentException::detachedEntityCannot($entity, "persisted"); + throw ORMInvalidArgumentException::detachedEntityCannot($entity, 'persisted'); default: throw new UnexpectedValueException("Unexpected entity state: $entityState." . self::objToStr($entity)); @@ -1875,24 +1899,24 @@ private function doRemove($entity, array &$visited) break; case self::STATE_DETACHED: - throw ORMInvalidArgumentException::detachedEntityCannot($entity, "removed"); + throw ORMInvalidArgumentException::detachedEntityCannot($entity, 'removed'); + default: throw new UnexpectedValueException("Unexpected entity state: $entityState." . self::objToStr($entity)); } - } /** * Merges the state of the given detached entity into this UnitOfWork. * + * @deprecated 2.7 This method is being removed from the ORM and won't have any replacement + * * @param object $entity * * @return object The managed copy of the entity. * * @throws OptimisticLockException If the entity uses optimistic locking through a version * attribute and the version check against the managed copy fails. - * - * @deprecated 2.7 This method is being removed from the ORM and won't have any replacement */ public function merge($entity) { @@ -1943,13 +1967,13 @@ private function doMerge($entity, array &$visited, $prevManagedCopy = null, arra $id = $class->getIdentifierValues($entity); // If there is no ID, it is actually NEW. - if ( ! $id) { + if (! $id) { $managedCopy = $this->newInstance($class); $this->mergeEntityStateIntoManagedCopy($entity, $managedCopy); $this->persistNew($class, $managedCopy); } else { - $flatId = ($class->containsForeignIdentifier) + $flatId = $class->containsForeignIdentifier ? $this->identifierFlattener->flattenIdentifier($class, $id) : $id; @@ -1957,8 +1981,8 @@ private function doMerge($entity, array &$visited, $prevManagedCopy = null, arra 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"); + if ($this->getEntityState($managedCopy) === self::STATE_REMOVED) { + throw ORMInvalidArgumentException::entityIsRemoved($managedCopy, 'merge'); } } else { // We need to fetch the managed copy in order to merge. @@ -1968,7 +1992,7 @@ private function doMerge($entity, array &$visited, $prevManagedCopy = null, arra if ($managedCopy === null) { // If the identifier is ASSIGNED, it is NEW, otherwise an error // since the managed entity was not found. - if ( ! $class->isIdentifierNatural()) { + if (! $class->isIdentifierNatural()) { throw EntityNotFoundException::fromClassNameAndIdentifier( $class->getName(), $this->identifierFlattener->flattenIdentifier($class, $id) @@ -2006,9 +2030,8 @@ private function doMerge($entity, array &$visited, $prevManagedCopy = null, arra } /** - * @param ClassMetadata $class - * @param object $entity - * @param object $managedCopy + * @param object $entity + * @param object $managedCopy * * @return void * @@ -2025,7 +2048,7 @@ private function ensureVersionMatch(ClassMetadata $class, $entity, $managedCopy) $entityVersion = $reflField->getValue($entity); // Throw exception if versions don't match. - if ($managedCopyVersion == $entityVersion) { + if ($managedCopyVersion === $entityVersion) { return; } @@ -2041,7 +2064,7 @@ private function ensureVersionMatch(ClassMetadata $class, $entity, $managedCopy) */ private function isLoaded($entity) { - return !($entity instanceof Proxy) || $entity->__isInitialized(); + return ! ($entity instanceof Proxy) || $entity->__isInitialized(); } /** @@ -2068,7 +2091,7 @@ private function updateAssociationWithMergedEntity($entity, array $association, $value = $prevClass->reflFields[$assocField]->getValue($previousManagedCopy); $value[] = $managedCopy; - if ($association['type'] == ClassMetadata::ONE_TO_MANY) { + if ($association['type'] === ClassMetadata::ONE_TO_MANY) { $class = $this->em->getClassMetadata(get_class($entity)); $class->reflFields[$association['mappedBy']]->setValue($managedCopy, $previousManagedCopy); @@ -2079,11 +2102,11 @@ private function updateAssociationWithMergedEntity($entity, array $association, * Detaches an entity from the persistence management. It's persistence will * no longer be managed by Doctrine. * + * @deprecated 2.7 This method is being removed from the ORM and won't have any replacement + * * @param object $entity The entity to detach. * * @return void - * - * @deprecated 2.7 This method is being removed from the ORM and won't have any replacement */ public function detach($entity) { @@ -2095,9 +2118,9 @@ public function detach($entity) /** * Executes a detach operation on the given entity. * - * @param object $entity - * @param array $visited - * @param boolean $noCascade if true, don't cascade detach operation. + * @param object $entity + * @param array $visited + * @param bool $noCascade if true, don't cascade detach operation. * * @return void */ @@ -2131,7 +2154,7 @@ private function doDetach($entity, array &$visited, $noCascade = false) return; } - if ( ! $noCascade) { + if (! $noCascade) { $this->cascadeDetach($entity, $visited); } } @@ -2201,26 +2224,29 @@ private function cascadeRefresh($entity, array &$visited) $associationMappings = array_filter( $class->associationMappings, - function ($assoc) { return $assoc['isCascadeRefresh']; } + static function ($assoc) { + return $assoc['isCascadeRefresh']; + } ); foreach ($associationMappings as $assoc) { $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity); switch (true) { - case ($relatedEntities instanceof PersistentCollection): + 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)): + case $relatedEntities instanceof Collection: + case is_array($relatedEntities): foreach ($relatedEntities as $relatedEntity) { $this->doRefresh($relatedEntity, $visited); } + break; - case ($relatedEntities !== null): + case $relatedEntities !== null: $this->doRefresh($relatedEntities, $visited); break; @@ -2244,26 +2270,29 @@ private function cascadeDetach($entity, array &$visited) $associationMappings = array_filter( $class->associationMappings, - function ($assoc) { return $assoc['isCascadeDetach']; } + static function ($assoc) { + return $assoc['isCascadeDetach']; + } ); foreach ($associationMappings as $assoc) { $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity); switch (true) { - case ($relatedEntities instanceof PersistentCollection): + 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)): + case $relatedEntities instanceof Collection: + case is_array($relatedEntities): foreach ($relatedEntities as $relatedEntity) { $this->doDetach($relatedEntity, $visited); } + break; - case ($relatedEntities !== null): + case $relatedEntities !== null: $this->doDetach($relatedEntities, $visited); break; @@ -2288,7 +2317,9 @@ private function cascadeMerge($entity, $managedCopy, array &$visited) $associationMappings = array_filter( $class->associationMappings, - function ($assoc) { return $assoc['isCascadeMerge']; } + static function ($assoc) { + return $assoc['isCascadeMerge']; + } ); foreach ($associationMappings as $assoc) { @@ -2307,7 +2338,7 @@ function ($assoc) { return $assoc['isCascadeMerge']; } foreach ($relatedEntities as $relatedEntity) { $this->doMerge($relatedEntity, $visited, $managedCopy, $assoc); } - } else if ($relatedEntities !== null) { + } elseif ($relatedEntities !== null) { $this->doMerge($relatedEntities, $visited, $managedCopy, $assoc); } } @@ -2327,20 +2358,22 @@ private function cascadePersist($entity, array &$visited) $associationMappings = array_filter( $class->associationMappings, - function ($assoc) { return $assoc['isCascadePersist']; } + static function ($assoc) { + return $assoc['isCascadePersist']; + } ); foreach ($associationMappings as $assoc) { $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity); switch (true) { - case ($relatedEntities instanceof PersistentCollection): + 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)): + case $relatedEntities instanceof Collection: + case is_array($relatedEntities): if (($assoc['type'] & ClassMetadata::TO_MANY) <= 0) { throw ORMInvalidArgumentException::invalidAssociation( $this->em->getClassMetadata($assoc['targetEntity']), @@ -2355,7 +2388,7 @@ function ($assoc) { return $assoc['isCascadePersist']; } break; - case ($relatedEntities !== null): + case $relatedEntities !== null: if (! $relatedEntities instanceof $assoc['targetEntity']) { throw ORMInvalidArgumentException::invalidAssociation( $this->em->getClassMetadata($assoc['targetEntity']), @@ -2387,28 +2420,31 @@ private function cascadeRemove($entity, array &$visited) $associationMappings = array_filter( $class->associationMappings, - function ($assoc) { return $assoc['isCascadeRemove']; } + static function ($assoc) { + return $assoc['isCascadeRemove']; + } ); $entitiesToCascade = []; 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); switch (true) { - case ($relatedEntities instanceof Collection): - case (is_array($relatedEntities)): + case $relatedEntities instanceof Collection: + case is_array($relatedEntities): // If its a PersistentCollection initialization is intended! No unwrap! foreach ($relatedEntities as $relatedEntity) { $entitiesToCascade[] = $relatedEntity; } + break; - case ($relatedEntities !== null): + case $relatedEntities !== null: $entitiesToCascade[] = $relatedEntities; break; @@ -2438,18 +2474,18 @@ function ($assoc) { return $assoc['isCascadeRemove']; } public function lock($entity, $lockMode, $lockVersion = null) { if ($entity === null) { - throw new \InvalidArgumentException("No entity passed to UnitOfWork#lock()."); + throw new InvalidArgumentException('No entity passed to UnitOfWork#lock().'); } - if ($this->getEntityState($entity, self::STATE_DETACHED) != self::STATE_MANAGED) { + if ($this->getEntityState($entity, self::STATE_DETACHED) !== self::STATE_MANAGED) { throw ORMInvalidArgumentException::entityNotManaged($entity); } $class = $this->em->getClassMetadata(get_class($entity)); switch (true) { - case LockMode::OPTIMISTIC === $lockMode: - if ( ! $class->isVersioned) { + case $lockMode === LockMode::OPTIMISTIC: + if (! $class->isVersioned) { throw OptimisticLockException::notVersioned($class->name); } @@ -2457,22 +2493,22 @@ public function lock($entity, $lockMode, $lockVersion = null) return; } - if ($entity instanceof Proxy && !$entity->__isInitialized__) { + if ($entity instanceof Proxy && ! $entity->__isInitialized__) { $entity->__load(); } $entityVersion = $class->reflFields[$class->versionField]->getValue($entity); - if ($entityVersion != $lockVersion) { + if ($entityVersion !== $lockVersion) { throw OptimisticLockException::lockFailedVersionMismatch($entity, $lockVersion, $entityVersion); } break; - case LockMode::NONE === $lockMode: - case LockMode::PESSIMISTIC_READ === $lockMode: - case LockMode::PESSIMISTIC_WRITE === $lockMode: - if (!$this->em->getConnection()->isTransactionActive()) { + case $lockMode === LockMode::NONE: + case $lockMode === LockMode::PESSIMISTIC_READ: + case $lockMode === LockMode::PESSIMISTIC_WRITE: + if (! $this->em->getConnection()->isTransactionActive()) { throw TransactionRequiredException::transactionRequired(); } @@ -2492,7 +2528,7 @@ public function lock($entity, $lockMode, $lockVersion = null) /** * Gets the CommitOrderCalculator used by the UnitOfWork to order commits. * - * @return \Doctrine\ORM\Internal\CommitOrderCalculator + * @return CommitOrderCalculator */ public function getCommitOrderCalculator() { @@ -2544,11 +2580,11 @@ public function clear($entityName = null) * invoked on that entity at the beginning of the next commit of this * UnitOfWork. * - * @ignore - * * @param object $entity * * @return void + * + * @ignore */ public function scheduleOrphanRemoval($entity) { @@ -2559,11 +2595,11 @@ public function scheduleOrphanRemoval($entity) * INTERNAL: * Cancels a previously scheduled orphan removal. * - * @ignore - * * @param object $entity * * @return void + * + * @ignore */ public function cancelOrphanRemoval($entity) { @@ -2574,8 +2610,6 @@ public function cancelOrphanRemoval($entity) * INTERNAL: * Schedules a complete collection for removal when this UnitOfWork commits. * - * @param PersistentCollection $coll - * * @return void */ public function scheduleCollectionDeletion(PersistentCollection $coll) @@ -2590,8 +2624,6 @@ public function scheduleCollectionDeletion(PersistentCollection $coll) } /** - * @param PersistentCollection $coll - * * @return bool */ public function isCollectionScheduledForDeletion(PersistentCollection $coll) @@ -2621,26 +2653,25 @@ private function newInstance($class) * * Internal note: Highly performance-sensitive method. * - * @ignore - * * @param string $className The name of the entity class. * @param array $data The data for the entity. * @param array $hints Any hints to account for during reconstitution/lookup of the entity. * * @return object The managed entity instance. * + * @ignore * @todo Rename: getOrCreateEntity */ public function createEntity($className, array $data, &$hints = []) { $class = $this->em->getClassMetadata($className); - $id = $this->identifierFlattener->flattenIdentifier($class, $data); + $id = $this->identifierFlattener->flattenIdentifier($class, $data); $idHash = implode(' ', $id); if (isset($this->identityMap[$class->rootEntityName][$idHash])) { $entity = $this->identityMap[$class->rootEntityName][$idHash]; - $oid = spl_object_hash($entity); + $oid = spl_object_hash($entity); if ( isset($hints[Query::HINT_REFRESH]) @@ -2667,8 +2698,10 @@ public function createEntity($className, array $data, &$hints = []) $entity->addPropertyChangedListener($this); } } else { - if ( ! isset($hints[Query::HINT_REFRESH]) - || (isset($hints[Query::HINT_REFRESH_ENTITY]) && $hints[Query::HINT_REFRESH_ENTITY] !== $entity)) { + if ( + ! isset($hints[Query::HINT_REFRESH]) + || (isset($hints[Query::HINT_REFRESH_ENTITY]) && $hints[Query::HINT_REFRESH_ENTITY] !== $entity) + ) { return $entity; } } @@ -2721,12 +2754,10 @@ public function createEntity($className, array $data, &$hints = []) $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); switch (true) { - case ($assoc['type'] & ClassMetadata::TO_ONE): - if ( ! $assoc['isOwningSide']) { - + case $assoc['type'] & ClassMetadata::TO_ONE: + if (! $assoc['isOwningSide']) { // use the given entity association if (isset($data[$field]) && is_object($data[$field]) && isset($this->entityStates[spl_object_hash($data[$field])])) { - $this->originalEntityData[$oid][$field] = $data[$field]; $class->reflFields[$field]->setValue($entity, $data[$field]); @@ -2761,7 +2792,8 @@ public function createEntity($className, array $data, &$hints = []) } else { $associatedId[$targetClass->fieldNames[$targetColumn]] = $joinColumnValue; } - } elseif ($targetClass->containsForeignIdentifier + } elseif ( + $targetClass->containsForeignIdentifier && in_array($targetClass->getFieldForColumn($targetColumn), $targetClass->identifier, true) ) { // the missing key is part of target's entity primary key @@ -2770,7 +2802,7 @@ public function createEntity($className, array $data, &$hints = []) } } - if ( ! $associatedId) { + if (! $associatedId) { // Foreign key is NULL $class->reflFields[$field]->setValue($entity, null); $this->originalEntityData[$oid][$field] = null; @@ -2778,7 +2810,7 @@ public function createEntity($className, array $data, &$hints = []) break; } - if ( ! isset($hints['fetchMode'][$class->name][$field])) { + if (! isset($hints['fetchMode'][$class->name][$field])) { $hints['fetchMode'][$class->name][$field] = $assoc['fetch']; } @@ -2789,24 +2821,25 @@ public function createEntity($className, array $data, &$hints = []) $relatedIdHash = implode(' ', $associatedId); switch (true) { - case (isset($this->identityMap[$targetClass->rootEntityName][$relatedIdHash])): + 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 && + if ( + $hints['fetchMode'][$class->name][$field] === ClassMetadata::FETCH_EAGER && isset($hints[self::HINT_DEFEREAGERLOAD]) && - !$targetClass->isIdentifierComposite && + ! $targetClass->isIdentifierComposite && $newValue instanceof Proxy && - $newValue->__isInitialized__ === false) { - + $newValue->__isInitialized__ === false + ) { $this->eagerLoadingEntities[$targetClass->rootEntityName][$relatedIdHash] = current($associatedId); } break; - case ($targetClass->subClasses): + 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) @@ -2816,12 +2849,12 @@ public function createEntity($className, array $data, &$hints = []) 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): + 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): + case isset($hints[self::HINT_DEFEREAGERLOAD]) && ! $targetClass->isIdentifierComposite: // TODO: Is there a faster approach? $this->eagerLoadingEntities[$targetClass->rootEntityName][$relatedIdHash] = current($associatedId); @@ -2835,8 +2868,8 @@ public function createEntity($className, array $data, &$hints = []) } // PERF: Inlined & optimized code from UnitOfWork#registerManaged() - $newValueOid = spl_object_hash($newValue); - $this->entityIdentifiers[$newValueOid] = $associatedId; + $newValueOid = spl_object_hash($newValue); + $this->entityIdentifiers[$newValueOid] = $associatedId; $this->identityMap[$targetClass->rootEntityName][$relatedIdHash] = $newValue; if ( @@ -2845,6 +2878,7 @@ public function createEntity($className, array $data, &$hints = []) ) { $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; @@ -2868,7 +2902,6 @@ public function createEntity($className, array $data, &$hints = []) // use the given collection if (isset($data[$field]) && $data[$field] instanceof PersistentCollection) { - $data[$field]->setOwner($entity, $assoc); $class->reflFields[$field]->setValue($entity, $data[$field]); @@ -2878,14 +2911,14 @@ public function createEntity($className, array $data, &$hints = []) } // Inject collection - $pColl = new PersistentCollection($this->em, $targetClass, new ArrayCollection); + $pColl = new PersistentCollection($this->em, $targetClass, new ArrayCollection()); $pColl->setOwner($entity, $assoc); $pColl->setInitialized(false); $reflField = $class->reflFields[$field]; $reflField->setValue($entity, $pColl); - if ($assoc['fetch'] == ClassMetadata::FETCH_EAGER) { + if ($assoc['fetch'] === ClassMetadata::FETCH_EAGER) { $this->loadCollection($pColl); $pColl->takeSnapshot(); } @@ -2906,7 +2939,7 @@ public function createEntity($className, array $data, &$hints = []) */ public function triggerEagerLoads() { - if ( ! $this->eagerLoadingEntities) { + if (! $this->eagerLoadingEntities) { return; } @@ -2915,7 +2948,7 @@ public function triggerEagerLoads() $this->eagerLoadingEntities = []; foreach ($eagerLoadingEntities as $entityName => $ids) { - if ( ! $ids) { + if (! $ids) { continue; } @@ -2930,7 +2963,7 @@ public function triggerEagerLoads() /** * Initializes (loads) an uninitialized persistent collection of an entity. * - * @param \Doctrine\ORM\PersistentCollection $collection The collection to initialize. + * @param PersistentCollection $collection The collection to initialize. * * @return void * @@ -2976,18 +3009,16 @@ public function getOriginalEntityData($entity) { $oid = spl_object_hash($entity); - return isset($this->originalEntityData[$oid]) - ? $this->originalEntityData[$oid] - : []; + return $this->originalEntityData[$oid] ?? []; } /** - * @ignore - * * @param object $entity * @param array $data * * @return void + * + * @ignore */ public function setOriginalEntityData($entity, array $data) { @@ -2998,13 +3029,13 @@ public function setOriginalEntityData($entity, array $data) * INTERNAL: * Sets a property value of the original data array of an entity. * - * @ignore - * * @param string $oid * @param string $property * @param mixed $value * * @return void + * + * @ignore */ public function setOriginalEntityProperty($oid, $property, $value) { @@ -3033,7 +3064,7 @@ public function getEntityIdentifier($entity) * * @return mixed A scalar value. * - * @throws \Doctrine\ORM\ORMInvalidArgumentException + * @throws ORMInvalidArgumentException */ public function getSingleIdentifierValue($entity) { @@ -3047,7 +3078,7 @@ public function getSingleIdentifierValue($entity) ? $this->getEntityIdentifier($entity) : $class->getIdentifierValues($entity); - return isset($values[$class->identifier[0]]) ? $values[$class->identifier[0]] : null; + return $values[$class->identifier[0]] ?? null; } /** @@ -3064,9 +3095,7 @@ public function tryGetById($id, $rootClassName) { $idHash = implode(' ', (array) $id); - return isset($this->identityMap[$rootClassName][$idHash]) - ? $this->identityMap[$rootClassName][$idHash] - : false; + return $this->identityMap[$rootClassName][$idHash] ?? false; } /** @@ -3088,7 +3117,7 @@ public function scheduleForDirtyCheck($entity) /** * Checks whether the UnitOfWork has any pending insertions. * - * @return boolean TRUE if this UnitOfWork has pending insertions, FALSE otherwise. + * @return bool TRUE if this UnitOfWork has pending insertions, FALSE otherwise. */ public function hasPendingInsertions() { @@ -3099,7 +3128,7 @@ public function hasPendingInsertions() * Calculates the size of the UnitOfWork. The size of the UnitOfWork is the * number of entities in the identity map. * - * @return integer + * @return int */ public function size() { @@ -3113,7 +3142,7 @@ public function size() * * @param string $entityName The name of the Entity. * - * @return \Doctrine\ORM\Persisters\Entity\EntityPersister + * @return EntityPersister */ public function getEntityPersister($entityName) { @@ -3124,20 +3153,20 @@ public function getEntityPersister($entityName) $class = $this->em->getClassMetadata($entityName); switch (true) { - case ($class->isInheritanceTypeNone()): + case $class->isInheritanceTypeNone(): $persister = new BasicEntityPersister($this->em, $class); break; - case ($class->isInheritanceTypeSingleTable()): + case $class->isInheritanceTypeSingleTable(): $persister = new SingleTablePersister($this->em, $class); break; - case ($class->isInheritanceTypeJoined()): + case $class->isInheritanceTypeJoined(): $persister = new JoinedSubclassPersister($this->em, $class); break; default: - throw new \RuntimeException('No persister found for entity.'); + throw new RuntimeException('No persister found for entity.'); } if ($this->hasCache && $class->cache !== null) { @@ -3157,7 +3186,7 @@ public function getEntityPersister($entityName) * * @param array $association * - * @return \Doctrine\ORM\Persisters\Collection\CollectionPersister + * @return CollectionPersister */ public function getCollectionPersister(array $association) { @@ -3169,7 +3198,7 @@ public function getCollectionPersister(array $association) return $this->collectionPersisters[$role]; } - $persister = ClassMetadata::ONE_TO_MANY === $association['type'] + $persister = $association['type'] === ClassMetadata::ONE_TO_MANY ? new OneToManyPersister($this->em) : new ManyToManyPersister($this->em); @@ -3242,14 +3271,14 @@ public function propertyChanged($sender, $propertyName, $oldValue, $newValue) $isAssocField = isset($class->associationMappings[$propertyName]); - if ( ! $isAssocField && ! isset($class->fieldMappings[$propertyName])) { + if (! $isAssocField && ! isset($class->fieldMappings[$propertyName])) { return; // ignore non-persistent fields } // Update changeset and mark entity for synchronization $this->entityChangeSets[$oid][$propertyName] = [$oldValue, $newValue]; - if ( ! isset($this->scheduledForSynchronization[$class->rootEntityName][$oid])) { + if (! isset($this->scheduledForSynchronization[$class->rootEntityName][$oid])) { $this->scheduleForDirtyCheck($sender); } } @@ -3333,7 +3362,7 @@ public function initializeObject($obj) */ private static function objToStr($obj) { - return method_exists($obj, '__toString') ? (string) $obj : get_class($obj).'@'.spl_object_hash($obj); + return method_exists($obj, '__toString') ? (string) $obj : get_class($obj) . '@' . spl_object_hash($obj); } /** @@ -3350,7 +3379,7 @@ private static function objToStr($obj) */ public function markReadOnly($object) { - if ( ! is_object($object) || ! $this->isInIdentityMap($object)) { + if (! is_object($object) || ! $this->isInIdentityMap($object)) { throw ORMInvalidArgumentException::readOnlyRequiresManagedEntity($object); } @@ -3368,7 +3397,7 @@ public function markReadOnly($object) */ public function isReadOnly($object) { - if ( ! is_object($object)) { + if (! is_object($object)) { throw ORMInvalidArgumentException::readOnlyRequiresManagedEntity($object); } @@ -3380,7 +3409,7 @@ public function isReadOnly($object) */ private function afterTransactionComplete() { - $this->performCallbackOnCachedPersister(function (CachedPersister $persister) { + $this->performCallbackOnCachedPersister(static function (CachedPersister $persister) { $persister->afterTransactionComplete(); }); } @@ -3390,19 +3419,17 @@ private function afterTransactionComplete() */ private function afterTransactionRolledBack() { - $this->performCallbackOnCachedPersister(function (CachedPersister $persister) { + $this->performCallbackOnCachedPersister(static function (CachedPersister $persister) { $persister->afterTransactionRolledBack(); }); } /** * Performs an action after the transaction. - * - * @param callable $callback */ private function performCallbackOnCachedPersister(callable $callback) { - if ( ! $this->hasCache) { + if (! $this->hasCache) { return; } @@ -3450,12 +3477,8 @@ private function isIdentifierEquals($entity1, $entity2) $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)); - $id2 = isset($this->entityIdentifiers[$oid2]) - ? $this->entityIdentifiers[$oid2] - : $this->identifierFlattener->flattenIdentifier($class, $class->getIdentifierValues($entity2)); + $id1 = $this->entityIdentifiers[$oid1] ?? $this->identifierFlattener->flattenIdentifier($class, $class->getIdentifierValues($entity1)); + $id2 = $this->entityIdentifiers[$oid2] ?? $this->identifierFlattener->flattenIdentifier($class, $class->getIdentifierValues($entity2)); return $id1 === $id2 || implode(' ', $id1) === implode(' ', $id2); } @@ -3463,15 +3486,15 @@ private function isIdentifierEquals($entity1, $entity2) /** * @throws ORMInvalidArgumentException */ - private function assertThatThereAreNoUnintentionallyNonPersistedAssociations() : void + private function assertThatThereAreNoUnintentionallyNonPersistedAssociations(): void { - $entitiesNeedingCascadePersist = \array_diff_key($this->nonCascadedNewDetectedEntities, $this->entityInsertions); + $entitiesNeedingCascadePersist = array_diff_key($this->nonCascadedNewDetectedEntities, $this->entityInsertions); $this->nonCascadedNewDetectedEntities = []; if ($entitiesNeedingCascadePersist) { throw ORMInvalidArgumentException::newEntitiesFoundThroughRelationships( - \array_values($entitiesNeedingCascadePersist) + array_values($entitiesNeedingCascadePersist) ); } } @@ -3501,8 +3524,8 @@ private function mergeEntityStateIntoManagedCopy($entity, $managedCopy) $prop->setAccessible(true); - if ( ! isset($class->associationMappings[$name])) { - if ( ! $class->isIdentifier($name)) { + if (! isset($class->associationMappings[$name])) { + if (! $class->isIdentifier($name)) { $prop->setValue($managedCopy, $prop->getValue($entity)); } } else { @@ -3513,12 +3536,12 @@ private function mergeEntityStateIntoManagedCopy($entity, $managedCopy) if ($other === null) { $prop->setValue($managedCopy, null); } else { - if ($other instanceof Proxy && !$other->__isInitialized()) { + if ($other instanceof Proxy && ! $other->__isInitialized()) { // do not merge fields marked lazy that have not been fetched. continue; } - if ( ! $assoc2['isCascadeMerge']) { + if (! $assoc2['isCascadeMerge']) { if ($this->getEntityState($other) === self::STATE_DETACHED) { $targetClass = $this->em->getClassMetadata($assoc2['targetEntity']); $relatedId = $targetClass->getIdentifierValues($other); @@ -3548,11 +3571,11 @@ private function mergeEntityStateIntoManagedCopy($entity, $managedCopy) $managedCol = $prop->getValue($managedCopy); - if ( ! $managedCol) { + if (! $managedCol) { $managedCol = new PersistentCollection( $this->em, $this->em->getClassMetadata($assoc2['targetEntity']), - new ArrayCollection + new ArrayCollection() ); $managedCol->setOwner($managedCopy, $assoc2); $prop->setValue($managedCopy, $managedCol); @@ -3562,12 +3585,13 @@ private function mergeEntityStateIntoManagedCopy($entity, $managedCopy) $managedCol->initialize(); // clear and set dirty a managed collection if its not also the same collection to merge from. - if ( ! $managedCol->isEmpty() && $managedCol !== $mergeCol) { + if (! $managedCol->isEmpty() && $managedCol !== $mergeCol) { $managedCol->unwrap()->clear(); $managedCol->setDirty(true); - if ($assoc2['isOwningSide'] - && $assoc2['type'] == ClassMetadata::MANY_TO_MANY + if ( + $assoc2['isOwningSide'] + && $assoc2['type'] === ClassMetadata::MANY_TO_MANY && $class->isChangeTrackingNotify() ) { $this->scheduleForDirtyCheck($managedCopy); @@ -3625,12 +3649,11 @@ private function clearEntityInsertionsForEntityName($entityName) } /** - * @param ClassMetadata $class - * @param mixed $identifierValue + * @param mixed $identifierValue * * @return mixed the identifier after type conversion * - * @throws \Doctrine\ORM\Mapping\MappingException if the entity has more than a single identifier + * @throws MappingException if the entity has more than a single identifier */ private function convertSingleFieldIdentifierToPHPValue(ClassMetadata $class, $identifierValue) { diff --git a/lib/Doctrine/ORM/Utility/HierarchyDiscriminatorResolver.php b/lib/Doctrine/ORM/Utility/HierarchyDiscriminatorResolver.php index d4ac8fbd333..42156edcfbd 100644 --- a/lib/Doctrine/ORM/Utility/HierarchyDiscriminatorResolver.php +++ b/lib/Doctrine/ORM/Utility/HierarchyDiscriminatorResolver.php @@ -2,9 +2,8 @@ namespace Doctrine\ORM\Utility; -use Doctrine\Persistence\Mapping\ClassMetadata; use Doctrine\ORM\EntityManagerInterface; -use function interface_exists; +use Doctrine\Persistence\Mapping\ClassMetadata; /** * @internal This class exists only to avoid code duplication, do not reuse it externally @@ -27,16 +26,16 @@ public static function resolveDiscriminatorsForClass( ClassMetadata $rootClassMetadata, EntityManagerInterface $entityManager ): array { - $hierarchyClasses = $rootClassMetadata->subClasses; + $hierarchyClasses = $rootClassMetadata->subClasses; $hierarchyClasses[] = $rootClassMetadata->name; $discriminators = []; foreach ($hierarchyClasses as $class) { - $currentMetadata = $entityManager->getClassMetadata($class); + $currentMetadata = $entityManager->getClassMetadata($class); $currentDiscriminator = $currentMetadata->discriminatorValue; - if (null !== $currentDiscriminator) { + if ($currentDiscriminator !== null) { $discriminators[$currentDiscriminator] = null; } } diff --git a/lib/Doctrine/ORM/Utility/IdentifierFlattener.php b/lib/Doctrine/ORM/Utility/IdentifierFlattener.php index 992e8540e6f..9f2c40ee32d 100644 --- a/lib/Doctrine/ORM/Utility/IdentifierFlattener.php +++ b/lib/Doctrine/ORM/Utility/IdentifierFlattener.php @@ -1,4 +1,5 @@ */ final class IdentifierFlattener { @@ -48,21 +50,17 @@ final class IdentifierFlattener /** * Initializes a new IdentifierFlattener instance, bound to the given EntityManager. - * - * @param UnitOfWork $unitOfWork - * @param ClassMetadataFactory $metadataFactory */ public function __construct(UnitOfWork $unitOfWork, ClassMetadataFactory $metadataFactory) { - $this->unitOfWork = $unitOfWork; + $this->unitOfWork = $unitOfWork; $this->metadataFactory = $metadataFactory; } /** * convert foreign identifiers into scalar foreign key values to avoid object to string conversion failures. * - * @param ClassMetadata $class - * @param array $id + * @param array $id * * @return array */ @@ -72,10 +70,10 @@ public function flattenIdentifier(ClassMetadata $class, array $id) foreach ($class->identifier as $field) { if (isset($class->associationMappings[$field]) && isset($id[$field]) && is_object($id[$field])) { - /* @var $targetClassMetadata ClassMetadata */ $targetClassMetadata = $this->metadataFactory->getMetadataFor( $class->associationMappings[$field]['targetEntity'] ); + assert($targetClassMetadata instanceof ClassMetadata); if ($this->unitOfWork->isInIdentityMap($id[$field])) { $associatedId = $this->flattenIdentifier($targetClassMetadata, $this->unitOfWork->getEntityIdentifier($id[$field])); diff --git a/lib/Doctrine/ORM/Utility/PersisterHelper.php b/lib/Doctrine/ORM/Utility/PersisterHelper.php index fc6e492556f..7d1ce9b0341 100644 --- a/lib/Doctrine/ORM/Utility/PersisterHelper.php +++ b/lib/Doctrine/ORM/Utility/PersisterHelper.php @@ -23,21 +23,20 @@ use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Query\QueryException; +use RuntimeException; + +use function sprintf; /** * The PersisterHelper contains logic to infer binding types which is used in * several persisters. * * @link www.doctrine-project.org - * @since 2.5 - * @author Jasper N. Brouwer */ class PersisterHelper { /** - * @param string $fieldName - * @param ClassMetadata $class - * @param EntityManagerInterface $em + * @param string $fieldName * * @return array * @@ -49,7 +48,7 @@ public static function getTypeOfField($fieldName, ClassMetadata $class, EntityMa return [$class->fieldMappings[$fieldName]['type']]; } - if ( ! isset($class->associationMappings[$fieldName])) { + if (! isset($class->associationMappings[$fieldName])) { return []; } @@ -76,13 +75,11 @@ public static function getTypeOfField($fieldName, ClassMetadata $class, EntityMa } /** - * @param string $columnName - * @param ClassMetadata $class - * @param EntityManagerInterface $em + * @param string $columnName * * @return string * - * @throws \RuntimeException + * @throws RuntimeException */ public static function getTypeOfColumn($columnName, ClassMetadata $class, EntityManagerInterface $em) { @@ -96,12 +93,12 @@ public static function getTypeOfColumn($columnName, ClassMetadata $class, Entity // iterate over to-one association mappings foreach ($class->associationMappings as $assoc) { - if ( ! isset($assoc['joinColumns'])) { + if (! isset($assoc['joinColumns'])) { continue; } foreach ($assoc['joinColumns'] as $joinColumn) { - if ($joinColumn['name'] == $columnName) { + if ($joinColumn['name'] === $columnName) { $targetColumnName = $joinColumn['referencedColumnName']; $targetClass = $em->getClassMetadata($assoc['targetEntity']); @@ -112,12 +109,12 @@ public static function getTypeOfColumn($columnName, ClassMetadata $class, Entity // iterate over to-many association mappings foreach ($class->associationMappings as $assoc) { - if ( ! (isset($assoc['joinTable']) && isset($assoc['joinTable']['joinColumns']))) { + if (! (isset($assoc['joinTable']) && isset($assoc['joinTable']['joinColumns']))) { continue; } foreach ($assoc['joinTable']['joinColumns'] as $joinColumn) { - if ($joinColumn['name'] == $columnName) { + if ($joinColumn['name'] === $columnName) { $targetColumnName = $joinColumn['referencedColumnName']; $targetClass = $em->getClassMetadata($assoc['targetEntity']); @@ -126,7 +123,7 @@ public static function getTypeOfColumn($columnName, ClassMetadata $class, Entity } } - throw new \RuntimeException(sprintf( + throw new RuntimeException(sprintf( 'Could not resolve type of column "%s" of class "%s"', $columnName, $class->getName() diff --git a/lib/Doctrine/ORM/Version.php b/lib/Doctrine/ORM/Version.php index aa286eba4d0..18b819ebcf7 100644 --- a/lib/Doctrine/ORM/Version.php +++ b/lib/Doctrine/ORM/Version.php @@ -1,4 +1,5 @@ - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - * * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement + * + * @link www.doctrine-project.org */ class Version { /** * Current Doctrine Version */ - const VERSION = '2.7.1-DEV'; + public const VERSION = '2.7.1-DEV'; /** * Compares a Doctrine version with the current one. diff --git a/tests/Doctrine/Performance/ChangeSet/UnitOfWorkComputeChangesBench.php b/tests/Doctrine/Performance/ChangeSet/UnitOfWorkComputeChangesBench.php index 25cc2fffdbb..fecadc98ad7 100644 --- a/tests/Doctrine/Performance/ChangeSet/UnitOfWorkComputeChangesBench.php +++ b/tests/Doctrine/Performance/ChangeSet/UnitOfWorkComputeChangesBench.php @@ -1,35 +1,34 @@ unitOfWork = EntityManagerFactory::getEntityManager([])->getUnitOfWork(); for ($i = 1; $i <= 100; ++$i) { - $user = new CmsUser; + $user = new CmsUser(); $user->id = $i; $user->status = 'user'; $user->username = 'user' . $i; @@ -38,9 +37,7 @@ public function init() $this->unitOfWork->registerManaged( $user, - [ - 'id' => $i, - ], + ['id' => $i], [ 'id' => $user->id, 'status' => $user->status, @@ -55,19 +52,18 @@ public function init() $this->unitOfWork->computeChangeSets(); if ($this->unitOfWork->getScheduledEntityUpdates()) { - throw new \LogicException('Unit of work should be clean at this stage'); + throw new LogicException('Unit of work should be clean at this stage'); } - foreach ($this->users AS $user) { + foreach ($this->users as $user) { $user->status = 'other'; $user->username .= '++'; $user->name = str_replace('Mr.', 'Mrs.', $user->name); } } - public function benchChangeSetComputation() + public function benchChangeSetComputation(): void { $this->unitOfWork->computeChangeSets(); } } - diff --git a/tests/Doctrine/Performance/EntityManagerFactory.php b/tests/Doctrine/Performance/EntityManagerFactory.php index 0e891875db8..eb0f9a31368 100644 --- a/tests/Doctrine/Performance/EntityManagerFactory.php +++ b/tests/Doctrine/Performance/EntityManagerFactory.php @@ -14,12 +14,13 @@ use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Proxy\ProxyFactory; use Doctrine\ORM\Tools\SchemaTool; + use function array_map; use function realpath; final class EntityManagerFactory { - public static function getEntityManager(array $schemaClassNames) : EntityManagerInterface + public static function getEntityManager(array $schemaClassNames): EntityManagerInterface { $config = new Configuration(); @@ -45,7 +46,7 @@ public static function getEntityManager(array $schemaClassNames) : EntityManager return $entityManager; } - public static function makeEntityManagerWithNoResultsConnection() : EntityManagerInterface + public static function makeEntityManagerWithNoResultsConnection(): EntityManagerInterface { $config = new Configuration(); diff --git a/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinArrayHydrationPerformanceBench.php b/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinArrayHydrationPerformanceBench.php index bbda1f23dd8..87c3340620e 100644 --- a/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinArrayHydrationPerformanceBench.php +++ b/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinArrayHydrationPerformanceBench.php @@ -1,5 +1,7 @@ 'romanb', 'u__name' => 'Roman', 'sclr0' => 'JWAGE', - 'p__phonenumber' => '91' - ] + 'p__phonenumber' => '91', + ], ]; for ($i = 4; $i < 10000; ++$i) { @@ -66,13 +62,13 @@ public function init() 'u__username' => 'jwage', 'u__name' => 'Jonathan', 'sclr0' => 'JWAGE' . $i, - 'p__phonenumber' => '91' + 'p__phonenumber' => '91', ]; } $this->stmt = new HydratorMockStatement($resultSet); $this->hydrator = new ArrayHydrator(EntityManagerFactory::getEntityManager([])); - $this->rsm = new ResultSetMapping; + $this->rsm = new ResultSetMapping(); $this->rsm->addEntityResult(CmsUser::class, 'u'); $this->rsm->addJoinedEntityResult(CmsPhonenumber::class, 'p', 'u', 'phonenumbers'); @@ -84,9 +80,8 @@ public function init() $this->rsm->addFieldResult('p', 'p__phonenumber', 'phonenumber'); } - public function benchHydration() + public function benchHydration(): void { $this->hydrator->hydrateAll($this->stmt, $this->rsm); } } - diff --git a/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinFullObjectHydrationPerformanceBench.php b/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinFullObjectHydrationPerformanceBench.php index c70ca77cb10..a69f74f4e64 100644 --- a/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinFullObjectHydrationPerformanceBench.php +++ b/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinFullObjectHydrationPerformanceBench.php @@ -1,5 +1,7 @@ 'Roman', 'sclr0' => 'ROMANB', 'p__phonenumber' => '42', - 'a__id' => '1' - ] + 'a__id' => '1', + ], ]; for ($i = 2; $i < 2000; ++$i) { @@ -53,13 +49,13 @@ public function init() 'u__name' => 'Jonathan', 'sclr0' => 'JWAGE' . $i, 'p__phonenumber' => '91', - 'a__id' => $i + 'a__id' => $i, ]; } $this->stmt = new HydratorMockStatement($resultSet); $this->hydrator = new ObjectHydrator(EntityManagerFactory::getEntityManager([])); - $this->rsm = new ResultSetMapping; + $this->rsm = new ResultSetMapping(); $this->rsm->addEntityResult(CmsUser::class, 'u'); $this->rsm->addJoinedEntityResult(CmsPhonenumber::class, 'p', 'u', 'phonenumbers'); @@ -73,9 +69,8 @@ public function init() $this->rsm->addFieldResult('a', 'a__id', 'id'); } - public function benchHydration() + public function benchHydration(): void { $this->hydrator->hydrateAll($this->stmt, $this->rsm); } } - diff --git a/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinPartialObjectHydrationPerformanceBench.php b/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinPartialObjectHydrationPerformanceBench.php index f2e33f76dbd..51b12f70d2d 100644 --- a/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinPartialObjectHydrationPerformanceBench.php +++ b/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinPartialObjectHydrationPerformanceBench.php @@ -1,5 +1,7 @@ 'romanb', 'u__name' => 'Roman', 'sclr0' => 'JWAGE', - 'p__phonenumber' => '91' - ] + 'p__phonenumber' => '91', + ], ]; for ($i = 4; $i < 2000; ++$i) { @@ -67,13 +63,13 @@ public function init() 'u__username' => 'jwage', 'u__name' => 'Jonathan', 'sclr0' => 'JWAGE' . $i, - 'p__phonenumber' => '91' + 'p__phonenumber' => '91', ]; } $this->stmt = new HydratorMockStatement($resultSet); $this->hydrator = new ObjectHydrator(EntityManagerFactory::getEntityManager([])); - $this->rsm = new ResultSetMapping; + $this->rsm = new ResultSetMapping(); $this->rsm->addEntityResult(CmsUser::class, 'u'); $this->rsm->addJoinedEntityResult(CmsPhonenumber::class, 'p', 'u', 'phonenumbers'); @@ -85,9 +81,8 @@ public function init() $this->rsm->addFieldResult('p', 'p__phonenumber', 'phonenumber'); } - public function benchHydration() + public function benchHydration(): void { $this->hydrator->hydrateAll($this->stmt, $this->rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); } } - diff --git a/tests/Doctrine/Performance/Hydration/SimpleHydrationBench.php b/tests/Doctrine/Performance/Hydration/SimpleHydrationBench.php index 4c7700835d6..85b66d92153 100644 --- a/tests/Doctrine/Performance/Hydration/SimpleHydrationBench.php +++ b/tests/Doctrine/Performance/Hydration/SimpleHydrationBench.php @@ -1,5 +1,7 @@ entityManager = EntityManagerFactory::getEntityManager([ CMS\CmsUser::class, @@ -51,7 +49,7 @@ public function init() $this->repository = $this->entityManager->getRepository(CMS\CmsUser::class); } - public function benchHydration() + public function benchHydration(): void { $this->repository->findAll(); } diff --git a/tests/Doctrine/Performance/Hydration/SimpleInsertPerformanceBench.php b/tests/Doctrine/Performance/Hydration/SimpleInsertPerformanceBench.php index 5806b6b9da4..15a9f457ac1 100644 --- a/tests/Doctrine/Performance/Hydration/SimpleInsertPerformanceBench.php +++ b/tests/Doctrine/Performance/Hydration/SimpleInsertPerformanceBench.php @@ -1,5 +1,7 @@ entityManager = EntityManagerFactory::getEntityManager([ CMS\CmsUser::class, @@ -41,7 +37,7 @@ public function init() ]); for ($i = 1; $i <= 10000; ++$i) { - $user = new CMS\CmsUser; + $user = new CMS\CmsUser(); $user->status = 'user'; $user->username = 'user' . $i; $user->name = 'Mr.Smith-' . $i; @@ -52,7 +48,7 @@ public function init() $this->tableName = $this->entityManager->getClassMetadata(CMS\CmsUser::class)->getTableName(); } - public function benchHydration() + public function benchHydration(): void { // Yes, this is a lot of overhead, but I have no better solution other than // completely mocking out the DB, which would be silly (query impact is @@ -62,7 +58,7 @@ public function benchHydration() foreach ($this->users as $key => $user) { $this->entityManager->persist($user); - if (! ($key % 20)) { + if (! $key % 20) { $this->entityManager->flush(); $this->entityManager->clear(); } diff --git a/tests/Doctrine/Performance/Hydration/SimpleQueryArrayHydrationPerformanceBench.php b/tests/Doctrine/Performance/Hydration/SimpleQueryArrayHydrationPerformanceBench.php index aa404554dc8..017632ea33d 100644 --- a/tests/Doctrine/Performance/Hydration/SimpleQueryArrayHydrationPerformanceBench.php +++ b/tests/Doctrine/Performance/Hydration/SimpleQueryArrayHydrationPerformanceBench.php @@ -1,9 +1,10 @@ 'developer', 'u__username' => 'romanb', 'u__name' => 'Roman', - ] + ], ]; for ($i = 4; $i < 10000; ++$i) { @@ -64,7 +59,7 @@ public function init() $this->stmt = new HydratorMockStatement($resultSet); $this->hydrator = new ArrayHydrator(EntityManagerFactory::getEntityManager([])); - $this->rsm = new ResultSetMapping; + $this->rsm = new ResultSetMapping(); $this->rsm->addEntityResult(CmsUser::class, 'u'); $this->rsm->addFieldResult('u', 'u__id', 'id'); @@ -73,9 +68,8 @@ public function init() $this->rsm->addFieldResult('u', 'u__name', 'name'); } - public function benchHydration() + public function benchHydration(): void { $this->hydrator->hydrateAll($this->stmt, $this->rsm); } } - diff --git a/tests/Doctrine/Performance/Hydration/SimpleQueryFullObjectHydrationPerformanceBench.php b/tests/Doctrine/Performance/Hydration/SimpleQueryFullObjectHydrationPerformanceBench.php index 173001ff80c..7242cf8ada1 100644 --- a/tests/Doctrine/Performance/Hydration/SimpleQueryFullObjectHydrationPerformanceBench.php +++ b/tests/Doctrine/Performance/Hydration/SimpleQueryFullObjectHydrationPerformanceBench.php @@ -1,9 +1,10 @@ 'developer', 'u__username' => 'romanb', 'u__name' => 'Roman', - 'a__id' => '1' - ] + 'a__id' => '1', + ], ]; for ($i = 2; $i < 10000; ++$i) { @@ -49,13 +44,13 @@ public function init() 'u__status' => 'developer', 'u__username' => 'jwage', 'u__name' => 'Jonathan', - 'a__id' => $i + 'a__id' => $i, ]; } $this->stmt = new HydratorMockStatement($resultSet); $this->hydrator = new ObjectHydrator(EntityManagerFactory::getEntityManager([])); - $this->rsm = new ResultSetMapping; + $this->rsm = new ResultSetMapping(); $this->rsm->addEntityResult(CmsUser::class, 'u'); $this->rsm->addFieldResult('u', 'u__id', 'id'); @@ -66,9 +61,8 @@ public function init() $this->rsm->addFieldResult('a', 'a__id', 'id'); } - public function benchHydration() + public function benchHydration(): void { $this->hydrator->hydrateAll($this->stmt, $this->rsm); } } - diff --git a/tests/Doctrine/Performance/Hydration/SimpleQueryPartialObjectHydrationPerformanceBench.php b/tests/Doctrine/Performance/Hydration/SimpleQueryPartialObjectHydrationPerformanceBench.php index 55d78973fe2..e77cc413022 100644 --- a/tests/Doctrine/Performance/Hydration/SimpleQueryPartialObjectHydrationPerformanceBench.php +++ b/tests/Doctrine/Performance/Hydration/SimpleQueryPartialObjectHydrationPerformanceBench.php @@ -1,5 +1,7 @@ 'developer', 'u__username' => 'romanb', 'u__name' => 'Roman', - ] + ], ]; for ($i = 4; $i < 10000; ++$i) { @@ -64,7 +60,7 @@ public function init() $this->stmt = new HydratorMockStatement($resultSet); $this->hydrator = new ObjectHydrator(EntityManagerFactory::getEntityManager([])); - $this->rsm = new ResultSetMapping; + $this->rsm = new ResultSetMapping(); $this->rsm->addEntityResult(CmsUser::class, 'u'); $this->rsm->addFieldResult('u', 'u__id', 'id'); @@ -73,9 +69,8 @@ public function init() $this->rsm->addFieldResult('u', 'u__name', 'name'); } - public function benchHydration() + public function benchHydration(): void { $this->hydrator->hydrateAll($this->stmt, $this->rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); } } - diff --git a/tests/Doctrine/Performance/Hydration/SimpleQueryScalarHydrationPerformanceBench.php b/tests/Doctrine/Performance/Hydration/SimpleQueryScalarHydrationPerformanceBench.php index 4af2c0791bf..223c73b59b5 100644 --- a/tests/Doctrine/Performance/Hydration/SimpleQueryScalarHydrationPerformanceBench.php +++ b/tests/Doctrine/Performance/Hydration/SimpleQueryScalarHydrationPerformanceBench.php @@ -1,9 +1,10 @@ 'developer', 'u__username' => 'romanb', 'u__name' => 'Roman', - ] + ], ]; for ($i = 4; $i < 10000; ++$i) { @@ -64,7 +59,7 @@ public function init() $this->stmt = new HydratorMockStatement($resultSet); $this->hydrator = new ScalarHydrator(EntityManagerFactory::getEntityManager([])); - $this->rsm = new ResultSetMapping; + $this->rsm = new ResultSetMapping(); $this->rsm->addEntityResult(CmsUser::class, 'u'); $this->rsm->addFieldResult('u', 'u__id', 'id'); @@ -73,9 +68,8 @@ public function init() $this->rsm->addFieldResult('u', 'u__name', 'name'); } - public function benchHydration() + public function benchHydration(): void { $this->hydrator->hydrateAll($this->stmt, $this->rsm); } } - diff --git a/tests/Doctrine/Performance/Hydration/SingleTableInheritanceHydrationPerformanceBench.php b/tests/Doctrine/Performance/Hydration/SingleTableInheritanceHydrationPerformanceBench.php index b143dcddeae..6dd9f780ee9 100644 --- a/tests/Doctrine/Performance/Hydration/SingleTableInheritanceHydrationPerformanceBench.php +++ b/tests/Doctrine/Performance/Hydration/SingleTableInheritanceHydrationPerformanceBench.php @@ -1,5 +1,7 @@ clear(); } - public function benchHydrateFixContracts() + public function benchHydrateFixContracts(): void { $this->fixContractsRepository->findAll(); } - public function benchHydrateFlexContracts() + public function benchHydrateFlexContracts(): void { $this->flexContractRepository->findAll(); } - public function benchHydrateUltraContracts() + public function benchHydrateUltraContracts(): void { $this->ultraContractRepository->findAll(); } - public function benchHydrateAllContracts() + public function benchHydrateAllContracts(): void { $this->contractsRepository->findAll(); } diff --git a/tests/Doctrine/Performance/Hydration/SingleTableInheritanceInsertPerformanceBench.php b/tests/Doctrine/Performance/Hydration/SingleTableInheritanceInsertPerformanceBench.php index 8014b0ed1f3..4e244d25987 100644 --- a/tests/Doctrine/Performance/Hydration/SingleTableInheritanceInsertPerformanceBench.php +++ b/tests/Doctrine/Performance/Hydration/SingleTableInheritanceInsertPerformanceBench.php @@ -1,5 +1,7 @@ entityManager = EntityManagerFactory::getEntityManager([ Company\CompanyPerson::class, @@ -72,25 +68,25 @@ public function init() } } - public function benchInsertFixContracts() + public function benchInsertFixContracts(): void { array_map([$this->entityManager, 'persist'], $this->fixContracts); $this->entityManager->flush(); } - public function benchInsertFlexContracts() + public function benchInsertFlexContracts(): void { array_map([$this->entityManager, 'persist'], $this->flexContracts); $this->entityManager->flush(); } - public function benchInsertUltraContracts() + public function benchInsertUltraContracts(): void { array_map([$this->entityManager, 'persist'], $this->ultraContracts); $this->entityManager->flush(); } - public function benchInsertAllContracts() + public function benchInsertAllContracts(): void { array_map([$this->entityManager, 'persist'], $this->fixContracts); array_map([$this->entityManager, 'persist'], $this->flexContracts); diff --git a/tests/Doctrine/Performance/LazyLoading/ProxyInitializationTimeBench.php b/tests/Doctrine/Performance/LazyLoading/ProxyInitializationTimeBench.php index aeb5a1d2dee..f3741c90521 100644 --- a/tests/Doctrine/Performance/LazyLoading/ProxyInitializationTimeBench.php +++ b/tests/Doctrine/Performance/LazyLoading/ProxyInitializationTimeBench.php @@ -1,5 +1,7 @@ getProxyFactory(); @@ -50,32 +44,31 @@ public function init() } } - public function benchCmsUserInitialization() + public function benchCmsUserInitialization(): void { foreach ($this->cmsUsers as $proxy) { $proxy->__load(); } } - public function benchCmsEmployeeInitialization() + public function benchCmsEmployeeInitialization(): void { foreach ($this->cmsEmployees as $proxy) { $proxy->__load(); } } - public function benchInitializationOfAlreadyInitializedCmsUsers() + public function benchInitializationOfAlreadyInitializedCmsUsers(): void { foreach ($this->initializedUsers as $proxy) { $proxy->__load(); } } - public function benchInitializationOfAlreadyInitializedCmsEmployees() + public function benchInitializationOfAlreadyInitializedCmsEmployees(): void { foreach ($this->initializedEmployees as $proxy) { $proxy->__load(); } } } - diff --git a/tests/Doctrine/Performance/LazyLoading/ProxyInstantiationTimeBench.php b/tests/Doctrine/Performance/LazyLoading/ProxyInstantiationTimeBench.php index da5a2c94ff9..7dde30f09ff 100644 --- a/tests/Doctrine/Performance/LazyLoading/ProxyInstantiationTimeBench.php +++ b/tests/Doctrine/Performance/LazyLoading/ProxyInstantiationTimeBench.php @@ -1,5 +1,7 @@ proxyFactory = EntityManagerFactory::getEntityManager([])->getProxyFactory(); } - public function benchCmsUserInstantiation() + public function benchCmsUserInstantiation(): void { for ($i = 0; $i < 100000; ++$i) { $this->proxyFactory->getProxy(CmsUser::class, ['id' => $i]); } } - public function benchCmsEmployeeInstantiation() + public function benchCmsEmployeeInstantiation(): void { for ($i = 0; $i < 100000; ++$i) { $this->proxyFactory->getProxy(CmsEmployee::class, ['id' => $i]); } } } - diff --git a/tests/Doctrine/Performance/Mock/NonLoadingPersister.php b/tests/Doctrine/Performance/Mock/NonLoadingPersister.php index 390beb5457a..7fdf5203091 100644 --- a/tests/Doctrine/Performance/Mock/NonLoadingPersister.php +++ b/tests/Doctrine/Performance/Mock/NonLoadingPersister.php @@ -1,9 +1,10 @@ parsedQueryWithDeclaredParameterType->getSQL(); } - public function benchExecuteParsedQueryWithInferredParameterType() : void + public function benchExecuteParsedQueryWithInferredParameterType(): void { $this->parsedQueryWithInferredParameterType->execute(); } - public function benchExecuteParsedQueryWithDeclaredParameterType() : void + public function benchExecuteParsedQueryWithDeclaredParameterType(): void { $this->parsedQueryWithDeclaredParameterType->execute(); } diff --git a/tests/Doctrine/Tests/DbalFunctionalTestCase.php b/tests/Doctrine/Tests/DbalFunctionalTestCase.php index c566e0e1dde..8767a845131 100644 --- a/tests/Doctrine/Tests/DbalFunctionalTestCase.php +++ b/tests/Doctrine/Tests/DbalFunctionalTestCase.php @@ -1,38 +1,38 @@ sharedFixture['conn'] = null; - self::$_sharedConn = null; + self::$_sharedConn = null; } - protected function setUp() : void + protected function setUp(): void { if (isset($this->sharedFixture['conn'])) { $this->_conn = $this->sharedFixture['conn']; } else { - if ( ! isset(self::$_sharedConn)) { + 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 @@ id = (string) $id; } - /** - * @return string - */ - public function __toString() + public function __toString(): string { return $this->id; } diff --git a/tests/Doctrine/Tests/DbalTypes/CustomIdObjectType.php b/tests/Doctrine/Tests/DbalTypes/CustomIdObjectType.php index 0ebae5dff0e..538cbb634a1 100644 --- a/tests/Doctrine/Tests/DbalTypes/CustomIdObjectType.php +++ b/tests/Doctrine/Tests/DbalTypes/CustomIdObjectType.php @@ -1,5 +1,7 @@ getClassMetadata(); - $em = $event->getObjectManager(); + $em = $event->getObjectManager(); - /** @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */ + /** @var ClassMetadata $metadata */ if (strstr($metadata->name, 'Doctrine\Tests\Models\Cache')) { return; } @@ -35,36 +35,24 @@ public function loadClassMetadata(LoadClassMetadataEventArgs $event) $this->enableCaching($metadata, $em); } - /** - * @param ClassMetadata $metadata - * - * @return bool - */ - private function isVisited(ClassMetadata $metadata) + private function isVisited(ClassMetadata $metadata): bool { return isset($this->enabledItems[$metadata->getName()]); } - /** - * @param ClassMetadata $metadata - */ - private function recordVisit(ClassMetadata $metadata) + private function recordVisit(ClassMetadata $metadata): void { $this->enabledItems[$metadata->getName()] = true; } - /** - * @param ClassMetadata $metadata - * @param EntityManager $em - */ - protected function enableCaching(ClassMetadata $metadata, EntityManager $em) + protected function enableCaching(ClassMetadata $metadata, EntityManager $em): void { if ($this->isVisited($metadata)) { return; // Already handled in the past } $cache = [ - 'usage' => ClassMetadata::CACHE_USAGE_NONSTRICT_READ_WRITE + 'usage' => ClassMetadata::CACHE_USAGE_NONSTRICT_READ_WRITE, ]; if ($metadata->isVersioned) { diff --git a/tests/Doctrine/Tests/IterableTester.php b/tests/Doctrine/Tests/IterableTester.php index 2859ed3989c..e6e425e0683 100644 --- a/tests/Doctrine/Tests/IterableTester.php +++ b/tests/Doctrine/Tests/IterableTester.php @@ -7,12 +7,13 @@ use Doctrine\ORM\AbstractQuery; use Doctrine\ORM\Query; use PHPUnit\Framework\Assert; + use function is_array; use function iterator_to_array; final class IterableTester { - public static function assertResultsAreTheSame(Query $query) : void + public static function assertResultsAreTheSame(Query $query): void { $result = $query->getResult(); $iterable = $query->toIterable(); @@ -30,7 +31,7 @@ public static function assertResultsAreTheSame(Query $query) : void * * @return mixed[] */ - public static function iterableToArray(iterable $iterable) : array + public static function iterableToArray(iterable $iterable): array { return is_array($iterable) ? $iterable : iterator_to_array($iterable, true); } diff --git a/tests/Doctrine/Tests/Mapping/UnderscoreNamingStrategyTest.php b/tests/Doctrine/Tests/Mapping/UnderscoreNamingStrategyTest.php index ed7a351c664..c20b13fa73f 100644 --- a/tests/Doctrine/Tests/Mapping/UnderscoreNamingStrategyTest.php +++ b/tests/Doctrine/Tests/Mapping/UnderscoreNamingStrategyTest.php @@ -7,6 +7,7 @@ use Doctrine\ORM\Mapping\UnderscoreNamingStrategy; use Doctrine\Tests\VerifyDeprecations; use PHPUnit\Framework\TestCase; + use const CASE_LOWER; final class UnderscoreNamingStrategyTest extends TestCase @@ -14,7 +15,7 @@ final class UnderscoreNamingStrategyTest extends TestCase use VerifyDeprecations; /** @test */ - public function checkDeprecationMessage() : void + public function checkDeprecationMessage(): void { $this->expectDeprecationMessageSame('Creating Doctrine\ORM\Mapping\UnderscoreNamingStrategy without making it number aware is deprecated and will be removed in Doctrine ORM 3.0.'); new UnderscoreNamingStrategy(CASE_LOWER, false); diff --git a/tests/Doctrine/Tests/Mocks/CacheEntryMock.php b/tests/Doctrine/Tests/Mocks/CacheEntryMock.php index 7053df563ba..6f7822b39de 100644 --- a/tests/Doctrine/Tests/Mocks/CacheEntryMock.php +++ b/tests/Doctrine/Tests/Mocks/CacheEntryMock.php @@ -1,13 +1,15 @@ hash = $hash; } diff --git a/tests/Doctrine/Tests/Mocks/CacheRegionMock.php b/tests/Doctrine/Tests/Mocks/CacheRegionMock.php index 42ffba58504..3f31cd1a78f 100644 --- a/tests/Doctrine/Tests/Mocks/CacheRegionMock.php +++ b/tests/Doctrine/Tests/Mocks/CacheRegionMock.php @@ -1,5 +1,7 @@ returns[$method][] = $value; } @@ -31,12 +34,11 @@ public function addReturn($method, $value) /** * Dequeue a value for a specific method invocation * - * @param string $method * @param mixed $default * * @return mixed */ - private function getReturn($method, $default) + private function getReturn(string $method, $default) { if (isset($this->returns[$method]) && ! empty($this->returns[$method])) { return array_shift($this->returns[$method]); @@ -108,14 +110,14 @@ public function getMultiple(CollectionCacheEntry $collection) /** * {@inheritdoc} */ - public function put(CacheKey $key, CacheEntry $entry, Lock $lock = null) + public function put(CacheKey $key, CacheEntry $entry, ?Lock $lock = null) { $this->calls[__FUNCTION__][] = ['key' => $key, 'entry' => $entry]; return $this->getReturn(__FUNCTION__, true); } - public function clear() + public function clear(): void { $this->calls = []; $this->returns = []; diff --git a/tests/Doctrine/Tests/Mocks/ClassMetadataMock.php b/tests/Doctrine/Tests/Mocks/ClassMetadataMock.php index 599c4996f98..3d370ffd88a 100644 --- a/tests/Doctrine/Tests/Mocks/ClassMetadataMock.php +++ b/tests/Doctrine/Tests/Mocks/ClassMetadataMock.php @@ -1,5 +1,7 @@ region = $region; @@ -37,17 +37,16 @@ public function __construct(Region $region) /** * Dequeue an exception for a specific method invocation * - * @param string $method * @param mixed $default * * @return mixed */ - private function throwException($method) + private function throwException(string $method) { if (isset($this->exceptions[$method]) && ! empty($this->exceptions[$method])) { $exception = array_shift($this->exceptions[$method]); - if ($exception != null) { + if ($exception !== null) { throw $exception; } } @@ -55,22 +54,16 @@ private function throwException($method) /** * Queue an exception for the next method invocation - * - * @param string $method - * @param \Exception $e */ - public function addException($method, \Exception $e) + public function addException(string $method, Exception $e): void { $this->exceptions[$method][] = $e; } /** * Locks a specific cache entry - * - * @param \Doctrine\ORM\Cache\CacheKey $key - * @param \Doctrine\ORM\Cache\Lock $lock */ - public function setLock(CacheKey $key, Lock $lock) + public function setLock(CacheKey $key, Lock $lock): void { $this->locks[$key->hash] = $lock; } @@ -158,14 +151,13 @@ public function getName() /** * {@inheritdoc} */ - public function put(CacheKey $key, CacheEntry $entry, Lock $lock = null) + public function put(CacheKey $key, CacheEntry $entry, ?Lock $lock = null) { $this->calls[__FUNCTION__][] = ['key' => $key, 'entry' => $entry]; $this->throwException(__FUNCTION__); if (isset($this->locks[$key->hash])) { - if ($lock !== null && $this->locks[$key->hash]->value === $lock->value) { return $this->region->put($key, $entry); } @@ -201,7 +193,7 @@ public function unlock(CacheKey $key, Lock $lock) $this->throwException(__FUNCTION__); - if ( ! isset($this->locks[$key->hash])) { + if (! isset($this->locks[$key->hash])) { return; } diff --git a/tests/Doctrine/Tests/Mocks/ConnectionMock.php b/tests/Doctrine/Tests/Mocks/ConnectionMock.php index af8fc252e99..d1660ae3ffc 100644 --- a/tests/Doctrine/Tests/Mocks/ConnectionMock.php +++ b/tests/Doctrine/Tests/Mocks/ConnectionMock.php @@ -1,57 +1,49 @@ _platformMock = new DatabasePlatformMock(); @@ -98,17 +90,14 @@ public function lastInsertId($seqName = null) */ public function fetchColumn($statement, array $params = [], $colnum = 0, array $types = []) { - if (null !== $this->_fetchOneException) { + if ($this->_fetchOneException !== null) { throw $this->_fetchOneException; } return $this->_fetchOneResult; } - /** - * {@inheritdoc} - */ - public function query() : Statement + public function query(): Statement { return $this->_queryResult; } @@ -121,6 +110,7 @@ public function quote($input, $type = null) if (is_string($input)) { return "'" . $input . "'"; } + return $input; } @@ -128,48 +118,28 @@ public function quote($input, $type = null) /** * @param mixed $fetchOneResult - * - * @return void */ - public function setFetchOneResult($fetchOneResult) + public function setFetchOneResult($fetchOneResult): void { $this->_fetchOneResult = $fetchOneResult; } - /** - * @param \Exception|null $exception - * - * @return void - */ - public function setFetchOneException(\Exception $exception = null) + public function setFetchOneException(?Exception $exception = null): void { $this->_fetchOneException = $exception; } - /** - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform - * - * @return void - */ - public function setDatabasePlatform($platform) + public function setDatabasePlatform(AbstractPlatform $platform): void { $this->_platformMock = $platform; } - /** - * @param int $id - * - * @return void - */ - public function setLastInsertId($id) + public function setLastInsertId(int $id): void { $this->_lastInsertId = $id; } - /** - * @param Statement $result - */ - public function setQueryResult(Statement $result) + public function setQueryResult(Statement $result): void { $this->_queryResult = $result; } @@ -177,7 +147,7 @@ public function setQueryResult(Statement $result) /** * @return array */ - public function getInserts() + public function getInserts(): array { return $this->_inserts; } @@ -185,17 +155,14 @@ public function getInserts() /** * @return array */ - public function getExecuteUpdates() + public function getExecuteUpdates(): array { return $this->_executeUpdates; } - /** - * @return void - */ - public function reset() + public function reset(): void { - $this->_inserts = []; + $this->_inserts = []; $this->_lastInsertId = 0; } } diff --git a/tests/Doctrine/Tests/Mocks/DatabasePlatformMock.php b/tests/Doctrine/Tests/Mocks/DatabasePlatformMock.php index 60807af5ba4..f230ffa2b9e 100644 --- a/tests/Doctrine/Tests/Mocks/DatabasePlatformMock.php +++ b/tests/Doctrine/Tests/Mocks/DatabasePlatformMock.php @@ -1,5 +1,7 @@ _prefersIdentityColumns = $bool; } - /** - * @param bool $bool - * - * @return void - */ - public function setPrefersSequences($bool) + public function setPrefersSequences(bool $bool): void { $this->_prefersSequences = $bool; } - /** - * @param string $sql - * - * @return void - */ - public function setSequenceNextValSql($sql) + public function setSequenceNextValSql(string $sql): void { $this->_sequenceNextValSql = $sql; } diff --git a/tests/Doctrine/Tests/Mocks/DriverConnectionMock.php b/tests/Doctrine/Tests/Mocks/DriverConnectionMock.php index af1a4977f49..5a4352d3f47 100644 --- a/tests/Doctrine/Tests/Mocks/DriverConnectionMock.php +++ b/tests/Doctrine/Tests/Mocks/DriverConnectionMock.php @@ -1,31 +1,27 @@ statementMock; } - /** - * @param \Doctrine\DBAL\Driver\Statement $statementMock - */ - public function setStatementMock($statementMock) + public function setStatementMock(Statement $statementMock): void { $this->statementMock = $statementMock; } @@ -49,7 +45,7 @@ public function query() /** * {@inheritdoc} */ - public function quote($input, $type=\PDO::PARAM_STR) + public function quote($input, $type = PDO::PARAM_STR) { } diff --git a/tests/Doctrine/Tests/Mocks/DriverMock.php b/tests/Doctrine/Tests/Mocks/DriverMock.php index 21ae4e3bbab..ec55d5fc166 100644 --- a/tests/Doctrine/Tests/Mocks/DriverMock.php +++ b/tests/Doctrine/Tests/Mocks/DriverMock.php @@ -1,25 +1,24 @@ _platformMock) { - $this->_platformMock = new DatabasePlatformMock; + if (! $this->_platformMock) { + $this->_platformMock = new DatabasePlatformMock(); } + return $this->_platformMock; } @@ -46,7 +46,7 @@ public function getDatabasePlatform() */ public function getSchemaManager(Connection $conn) { - if ($this->_schemaManagerMock == null) { + if ($this->_schemaManagerMock === null) { return new SchemaManagerMock($conn); } @@ -55,22 +55,12 @@ public function getSchemaManager(Connection $conn) /* MOCK API */ - /** - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform - * - * @return void - */ - public function setDatabasePlatform(AbstractPlatform $platform) + public function setDatabasePlatform(AbstractPlatform $platform): void { $this->_platformMock = $platform; } - /** - * @param \Doctrine\DBAL\Schema\AbstractSchemaManager $sm - * - * @return void - */ - public function setSchemaManager(AbstractSchemaManager $sm) + public function setSchemaManager(AbstractSchemaManager $sm): void { $this->_schemaManagerMock = $sm; } @@ -91,7 +81,7 @@ public function getDatabase(Connection $conn) return; } - public function convertExceptionCode(\Exception $exception) + public function convertExceptionCode(Exception $exception) { return 0; } diff --git a/tests/Doctrine/Tests/Mocks/EntityManagerMock.php b/tests/Doctrine/Tests/Mocks/EntityManagerMock.php index f7af70227dd..3eeae02c28c 100644 --- a/tests/Doctrine/Tests/Mocks/EntityManagerMock.php +++ b/tests/Doctrine/Tests/Mocks/EntityManagerMock.php @@ -1,24 +1,24 @@ _uowMock) ? $this->_uowMock : parent::getUnitOfWork(); + return $this->_uowMock ?? parent::getUnitOfWork(); } /* Mock API */ /** * Sets a (mock) UnitOfWork that will be returned when getUnitOfWork() is called. - * - * @param \Doctrine\ORM\UnitOfWork $uow - * - * @return void */ - public function setUnitOfWork($uow) + public function setUnitOfWork(UnitOfWork $uow): void { $this->_uowMock = $uow; } - /** - * @param \Doctrine\ORM\Proxy\ProxyFactory $proxyFactory - * - * @return void - */ - public function setProxyFactory($proxyFactory) + public function setProxyFactory(ProxyFactory $proxyFactory): void { $this->_proxyFactoryMock = $proxyFactory; } - /** - * @return \Doctrine\ORM\Proxy\ProxyFactory - */ - public function getProxyFactory() + public function getProxyFactory(): ProxyFactory { - return isset($this->_proxyFactoryMock) ? $this->_proxyFactoryMock : parent::getProxyFactory(); + return $this->_proxyFactoryMock ?? parent::getProxyFactory(); } /** @@ -66,15 +54,16 @@ public function getProxyFactory() * * {@inheritdoc} */ - public static function create($conn, Configuration $config = null, EventManager $eventManager = null) + public static function create($conn, ?Configuration $config = null, ?EventManager $eventManager = null) { - if (null === $config) { + if ($config === null) { $config = new Configuration(); $config->setProxyDir(__DIR__ . '/../Proxies'); $config->setProxyNamespace('Doctrine\Tests\Proxies'); $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver([], true)); } - if (null === $eventManager) { + + if ($eventManager === null) { $eventManager = new EventManager(); } diff --git a/tests/Doctrine/Tests/Mocks/EntityPersisterMock.php b/tests/Doctrine/Tests/Mocks/EntityPersisterMock.php index 63be3397e68..9bdf26822b2 100644 --- a/tests/Doctrine/Tests/Mocks/EntityPersisterMock.php +++ b/tests/Doctrine/Tests/Mocks/EntityPersisterMock.php @@ -1,85 +1,72 @@ inserts[] = $entity; - if ( ! is_null($this->mockIdGeneratorType) && $this->mockIdGeneratorType == ClassMetadata::GENERATOR_TYPE_IDENTITY - || $this->class->isIdGeneratorIdentity()) { - $id = $this->identityColumnValueCounter++; + 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; } /** * @return array */ - public function executeInserts() + public function executeInserts(): array { return $this->postInsertIds; } - /** - * @param int $genType - * - * @return void - */ - public function setMockIdGeneratorType($genType) + public function setMockIdGeneratorType(int $genType): void { $this->mockIdGeneratorType = $genType; } @@ -95,7 +82,7 @@ public function update($entity) /** * {@inheritdoc} */ - public function exists($entity, Criteria $extraConditions = null) + public function exists($entity, ?Criteria $extraConditions = null) { $this->existsCalled = true; } @@ -111,7 +98,7 @@ public function delete($entity) /** * @return array */ - public function getInserts() + public function getInserts(): array { return $this->inserts; } @@ -119,7 +106,7 @@ public function getInserts() /** * @return array */ - public function getUpdates() + public function getUpdates(): array { return $this->updates; } @@ -127,27 +114,21 @@ public function getUpdates() /** * @return array */ - public function getDeletes() + public function getDeletes(): array { return $this->deletes; } - /** - * @return void - */ - public function reset() + public function reset(): void { - $this->existsCalled = false; + $this->existsCalled = false; $this->identityColumnValueCounter = 0; - $this->inserts = []; - $this->updates = []; - $this->deletes = []; + $this->inserts = []; + $this->updates = []; + $this->deletes = []; } - /** - * @return bool - */ - public function isExistsCalled() + public function isExistsCalled(): bool { return $this->existsCalled; } diff --git a/tests/Doctrine/Tests/Mocks/HydratorMockStatement.php b/tests/Doctrine/Tests/Mocks/HydratorMockStatement.php index 4f6df40e59d..e308925df18 100644 --- a/tests/Doctrine/Tests/Mocks/HydratorMockStatement.php +++ b/tests/Doctrine/Tests/Mocks/HydratorMockStatement.php @@ -1,20 +1,25 @@ */ -class HydratorMockStatement implements \IteratorAggregate, Statement +class HydratorMockStatement implements IteratorAggregate, Statement { - /** - * @var array - */ + /** @var array */ private $_resultSet; /** @@ -30,12 +35,11 @@ public function __construct(array $resultSet) /** * Fetches all rows from the result set. * - * @param int|null $fetchMode - * @param int|null $fetchArgument * @param array|null $ctorArgs + * * @return array */ - public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = null) + public function fetchAll(?int $fetchMode = null, ?int $fetchArgument = null, ?array $ctorArgs = null): array { return $this->_resultSet; } @@ -46,18 +50,23 @@ public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = n public function fetchColumn($columnNumber = 0) { $row = current($this->_resultSet); - if ( ! is_array($row)) return false; + if (! is_array($row)) { + return false; + } + $val = array_shift($row); - return $val !== null ? $val : false; + + return $val ?? false; } /** * {@inheritdoc} */ - public function fetch($fetchStyle = null, $cursorOrientation = \PDO::FETCH_ORI_NEXT, $cursorOffset = 0) + public function fetch($fetchStyle = null, $cursorOrientation = PDO::FETCH_ORI_NEXT, $cursorOffset = 0) { $current = current($this->_resultSet); next($this->_resultSet); + return $current; } diff --git a/tests/Doctrine/Tests/Mocks/MetadataDriverMock.php b/tests/Doctrine/Tests/Mocks/MetadataDriverMock.php index 4b947c3b304..7dca960d9ce 100644 --- a/tests/Doctrine/Tests/Mocks/MetadataDriverMock.php +++ b/tests/Doctrine/Tests/Mocks/MetadataDriverMock.php @@ -1,5 +1,7 @@ _sequenceNumber = 0; } diff --git a/tests/Doctrine/Tests/Mocks/StatementArrayMock.php b/tests/Doctrine/Tests/Mocks/StatementArrayMock.php index 0f1747c42dc..cf62683fc61 100644 --- a/tests/Doctrine/Tests/Mocks/StatementArrayMock.php +++ b/tests/Doctrine/Tests/Mocks/StatementArrayMock.php @@ -1,7 +1,16 @@ _result); + return new ArrayIterator($this->_result); } public function columnCount() @@ -39,7 +46,7 @@ public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = n return $this->_result; } - public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NEXT, $cursorOffset = 0) + public function fetch($fetchMode = null, $cursorOrientation = PDO::FETCH_ORI_NEXT, $cursorOffset = 0) { $current = current($this->_result); next($this->_result); @@ -52,6 +59,7 @@ public function fetchColumn($columnIndex = 0) $current = current($this->_result); if ($current) { next($this->_result); + return reset($current); } diff --git a/tests/Doctrine/Tests/Mocks/StatementMock.php b/tests/Doctrine/Tests/Mocks/StatementMock.php index efba7d841b4..9bf1d0fd66e 100644 --- a/tests/Doctrine/Tests/Mocks/StatementMock.php +++ b/tests/Doctrine/Tests/Mocks/StatementMock.php @@ -1,15 +1,17 @@ */ -class StatementMock implements \IteratorAggregate, Statement +class StatementMock implements IteratorAggregate, Statement { /** * {@inheritdoc} @@ -35,7 +37,9 @@ public function errorCode() /** * {@inheritdoc} */ - public function errorInfo(){} + public function errorInfo() + { + } /** * {@inheritdoc} @@ -75,7 +79,7 @@ public function setFetchMode($fetchStyle, $arg2 = null, $arg3 = null) /** * {@inheritdoc} */ - public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NEXT, $cursorOffset = 0) + public function fetch($fetchMode = null, $cursorOrientation = PDO::FETCH_ORI_NEXT, $cursorOffset = 0) { } diff --git a/tests/Doctrine/Tests/Mocks/TaskMock.php b/tests/Doctrine/Tests/Mocks/TaskMock.php index f6ce095add1..0270010d646 100644 --- a/tests/Doctrine/Tests/Mocks/TaskMock.php +++ b/tests/Doctrine/Tests/Mocks/TaskMock.php @@ -1,15 +1,16 @@ */ -class TaskMock extends \Doctrine\Common\Cli\Tasks\AbstractTask +class TaskMock extends AbstractTask { /** * Since instances of this class can be created elsewhere all instances @@ -17,11 +18,9 @@ class TaskMock extends \Doctrine\Common\Cli\Tasks\AbstractTask * * @var array (TaskMock) */ - static public $instances = []; + public static $instances = []; - /** - * @var int - */ + /** @var int */ private $runCounter = 0; /** @@ -39,10 +38,8 @@ function __construct(AbstractNamespace $namespace) /** * Returns the number of times run() was called on this object. - * - * @return int */ - public function getRunCounter() + public function getRunCounter(): int { return $this->runCounter; } @@ -51,20 +48,16 @@ public function getRunCounter() /** * Method invoked by CLI to run task. - * - * @return void */ - public function run() + public function run(): void { $this->runCounter++; } /** * Method supposed to generate the CLI Task Documentation. - * - * @return void */ - public function buildDocumentation() + public function buildDocumentation(): void { } } diff --git a/tests/Doctrine/Tests/Mocks/TimestampRegionMock.php b/tests/Doctrine/Tests/Mocks/TimestampRegionMock.php index 3f088a4e492..69da26187e7 100644 --- a/tests/Doctrine/Tests/Mocks/TimestampRegionMock.php +++ b/tests/Doctrine/Tests/Mocks/TimestampRegionMock.php @@ -1,9 +1,11 @@ calls[__FUNCTION__][] = ['key' => $key]; } diff --git a/tests/Doctrine/Tests/Mocks/UnitOfWorkMock.php b/tests/Doctrine/Tests/Mocks/UnitOfWorkMock.php index f11f7152322..48c20401098 100644 --- a/tests/Doctrine/Tests/Mocks/UnitOfWorkMock.php +++ b/tests/Doctrine/Tests/Mocks/UnitOfWorkMock.php @@ -1,22 +1,23 @@ _persisterMock[$entityName]) - ? $this->_persisterMock[$entityName] - : parent::getEntityPersister($entityName); + return $this->_persisterMock[$entityName] ?? parent::getEntityPersister($entityName); } /** @@ -50,13 +49,8 @@ public function & getEntityChangeSet($entity) /** * Sets a (mock) persister for an entity class that will be returned when * getEntityPersister() is invoked for that class. - * - * @param string $entityName - * @param \Doctrine\ORM\Persisters\Entity\BasicEntityPersister $persister - * - * @return void */ - public function setEntityPersister($entityName, $persister) + public function setEntityPersister(string $entityName, BasicEntityPersister $persister): void { $this->_persisterMock[$entityName] = $persister; } diff --git a/tests/Doctrine/Tests/Models/CMS/CmsAddress.php b/tests/Doctrine/Tests/Models/CMS/CmsAddress.php index f5c0b9af766..56c219732e3 100644 --- a/tests/Doctrine/Tests/Models/CMS/CmsAddress.php +++ b/tests/Doctrine/Tests/Models/CMS/CmsAddress.php @@ -1,14 +1,17 @@ id; } - public function getUser() { + public function getUser() + { return $this->user; } - public function getCountry() { + public function getCountry() + { return $this->country; } - public function getZipCode() { + public function getZipCode() + { return $this->zip; } - public function getCity() { + public function getCity() + { return $this->city; } - public function setUser(CmsUser $user) { + public function setUser(CmsUser $user): void + { if ($this->user !== $user) { $this->user = $user; $user->setAddress($this); } } - public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) + public static function loadMetadata(ClassMetadataInfo $metadata): void { $metadata->setPrimaryTable( - [ - 'name' => 'company_person', - ] + ['name' => 'company_person'] ); $metadata->mapField( [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', + 'id' => true, + 'fieldName' => 'id', + 'type' => 'integer', ] ); $metadata->mapField( [ - 'fieldName' => 'zip', - 'length' => 50, + 'fieldName' => 'zip', + 'length' => 50, ] ); $metadata->mapField( [ - 'fieldName' => 'city', - 'length' => 50, + 'fieldName' => 'city', + 'length' => 50, ] ); $metadata->mapOneToOne( [ - 'fieldName' => 'user', - 'targetEntity' => 'CmsUser', - 'joinColumns' => [['referencedColumnName' => 'id']] + 'fieldName' => 'user', + 'targetEntity' => 'CmsUser', + 'joinColumns' => [['referencedColumnName' => 'id']], ] ); $metadata->addNamedNativeQuery( [ - 'name' => 'find-all', - 'query' => 'SELECT id, country, city FROM cms_addresses', - 'resultSetMapping' => 'mapping-find-all', + '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, + 'name' => 'find-by-id', + 'query' => 'SELECT * FROM cms_addresses WHERE id = ?', + 'resultClass' => self::class, ] ); $metadata->addNamedNativeQuery( [ - 'name' => 'count', - 'query' => 'SELECT COUNT(*) AS count FROM cms_addresses', - 'resultSetMapping' => 'mapping-count', + '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, + 'name' => 'mapping-find-all', + 'columns' => [], + 'entities' => [ + [ + 'fields' => [ + [ + 'name' => 'id', + 'column' => 'id', + ], + [ + 'name' => 'city', + 'column' => 'city', + ], + [ + 'name' => 'country', + 'column' => 'country', + ], + ], + 'entityClass' => self::class, + ], ], - ], ] ); $metadata->addSqlResultSetMapping( [ - 'name' => 'mapping-without-fields', - 'columns' => [], - 'entities' => [ - [ - 'entityClass' => CmsAddress::class, - 'fields' => [] - ] - ] + 'name' => 'mapping-without-fields', + 'columns' => [], + 'entities' => [ + [ + 'entityClass' => self::class, + 'fields' => [], + ], + ], ] ); $metadata->addSqlResultSetMapping( [ - 'name' => 'mapping-count', - 'columns' => [ - [ - 'name' => 'count', + 'name' => 'mapping-count', + 'columns' => [ + ['name' => 'count'], ], ] - ] ); - $metadata->addEntityListener(\Doctrine\ORM\Events::postPersist, 'CmsAddressListener', 'postPersist'); - $metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CmsAddressListener', 'prePersist'); + $metadata->addEntityListener(Events::postPersist, 'CmsAddressListener', 'postPersist'); + $metadata->addEntityListener(Events::prePersist, 'CmsAddressListener', 'prePersist'); - $metadata->addEntityListener(\Doctrine\ORM\Events::postUpdate, 'CmsAddressListener', 'postUpdate'); - $metadata->addEntityListener(\Doctrine\ORM\Events::preUpdate, 'CmsAddressListener', 'preUpdate'); + $metadata->addEntityListener(Events::postUpdate, 'CmsAddressListener', 'postUpdate'); + $metadata->addEntityListener(Events::preUpdate, 'CmsAddressListener', 'preUpdate'); - $metadata->addEntityListener(\Doctrine\ORM\Events::postRemove, 'CmsAddressListener', 'postRemove'); - $metadata->addEntityListener(\Doctrine\ORM\Events::preRemove, 'CmsAddressListener', 'preRemove'); + $metadata->addEntityListener(Events::postRemove, 'CmsAddressListener', 'postRemove'); + $metadata->addEntityListener(Events::preRemove, 'CmsAddressListener', 'preRemove'); - $metadata->addEntityListener(\Doctrine\ORM\Events::preFlush, 'CmsAddressListener', 'preFlush'); - $metadata->addEntityListener(\Doctrine\ORM\Events::postLoad, 'CmsAddressListener', 'postLoad'); + $metadata->addEntityListener(Events::preFlush, 'CmsAddressListener', 'preFlush'); + $metadata->addEntityListener(Events::postLoad, 'CmsAddressListener', 'postLoad'); } } diff --git a/tests/Doctrine/Tests/Models/CMS/CmsAddressDTO.php b/tests/Doctrine/Tests/Models/CMS/CmsAddressDTO.php index d01f1c90bea..ec549bb76cd 100644 --- a/tests/Doctrine/Tests/Models/CMS/CmsAddressDTO.php +++ b/tests/Doctrine/Tests/Models/CMS/CmsAddressDTO.php @@ -1,5 +1,7 @@ country = $country; - $this->city = $city; - $this->zip = $zip; + $this->country = $country; + $this->city = $city; + $this->zip = $zip; } } diff --git a/tests/Doctrine/Tests/Models/CMS/CmsAddressListener.php b/tests/Doctrine/Tests/Models/CMS/CmsAddressListener.php index 75bdf86099d..61d616ccecb 100644 --- a/tests/Doctrine/Tests/Models/CMS/CmsAddressListener.php +++ b/tests/Doctrine/Tests/Models/CMS/CmsAddressListener.php @@ -1,58 +1,64 @@ calls[__FUNCTION__][] = func_get_args(); } - public function postPersist() + public function postPersist(): void { $this->calls[__FUNCTION__][] = func_get_args(); } - - public function preUpdate() + + public function preUpdate(): void { $this->calls[__FUNCTION__][] = func_get_args(); } - public function postUpdate() + public function postUpdate(): void { $this->calls[__FUNCTION__][] = func_get_args(); } - public function preRemove() + public function preRemove(): void { $this->calls[__FUNCTION__][] = func_get_args(); } - public function postRemove() + public function postRemove(): void { $this->calls[__FUNCTION__][] = func_get_args(); } - public function postLoad() + public function postLoad(): void { $this->calls[__FUNCTION__][] = func_get_args(); } - public function preFlush() + public function preFlush(): void { $this->calls[__FUNCTION__][] = func_get_args(); } - protected function postPersistHandler() + protected function postPersistHandler(): void { - throw new \BadMethodCallException("This is not a valid callback"); + throw new BadMethodCallException('This is not a valid callback'); } - protected function prePersistHandler() + protected function prePersistHandler(): void { - throw new \BadMethodCallException("This is not a valid callback"); + throw new BadMethodCallException('This is not a valid callback'); } } diff --git a/tests/Doctrine/Tests/Models/CMS/CmsArticle.php b/tests/Doctrine/Tests/Models/CMS/CmsArticle.php index 266cbc6622f..001bd439662 100644 --- a/tests/Doctrine/Tests/Models/CMS/CmsArticle.php +++ b/tests/Doctrine/Tests/Models/CMS/CmsArticle.php @@ -1,5 +1,7 @@ user = $author; } - public function addComment(CmsComment $comment) { + public function addComment(CmsComment $comment): void + { $this->comments[] = $comment; $comment->setArticle($this); } diff --git a/tests/Doctrine/Tests/Models/CMS/CmsComment.php b/tests/Doctrine/Tests/Models/CMS/CmsComment.php index 3e238210b7f..96c26734851 100644 --- a/tests/Doctrine/Tests/Models/CMS/CmsComment.php +++ b/tests/Doctrine/Tests/Models/CMS/CmsComment.php @@ -1,5 +1,7 @@ article = $article; } - public function __toString() { - return __CLASS__."[id=".$this->id."]"; + public function __toString() + { + return self::class . '[id=' . $this->id . ']'; } } diff --git a/tests/Doctrine/Tests/Models/CMS/CmsEmail.php b/tests/Doctrine/Tests/Models/CMS/CmsEmail.php index e72a597d882..bc82035a6ce 100644 --- a/tests/Doctrine/Tests/Models/CMS/CmsEmail.php +++ b/tests/Doctrine/Tests/Models/CMS/CmsEmail.php @@ -1,5 +1,7 @@ id; } - public function getEmail() { + public function getEmail() + { return $this->email; } - public function setEmail($email) { + public function setEmail($email): void + { $this->email = $email; } - public function getUser() { + public function getUser() + { return $this->user; } - public function setUser(CmsUser $user) { + public function setUser(CmsUser $user): void + { $this->user = $user; } } diff --git a/tests/Doctrine/Tests/Models/CMS/CmsEmployee.php b/tests/Doctrine/Tests/Models/CMS/CmsEmployee.php index c1697150fc4..1da674bafb8 100644 --- a/tests/Doctrine/Tests/Models/CMS/CmsEmployee.php +++ b/tests/Doctrine/Tests/Models/CMS/CmsEmployee.php @@ -1,11 +1,12 @@ id; } - public function getName() { + public function getName() + { return $this->name; } - public function getSpouse() { + public function getSpouse() + { return $this->spouse; } } - diff --git a/tests/Doctrine/Tests/Models/CMS/CmsGroup.php b/tests/Doctrine/Tests/Models/CMS/CmsGroup.php index 49581869418..86e4807163d 100644 --- a/tests/Doctrine/Tests/Models/CMS/CmsGroup.php +++ b/tests/Doctrine/Tests/Models/CMS/CmsGroup.php @@ -1,5 +1,7 @@ users = new ArrayCollection(); } - public function setName($name) { + public function setName($name): void + { $this->name = $name; } - public function getName() { + public function getName() + { return $this->name; } - public function addUser(CmsUser $user) { + public function addUser(CmsUser $user): void + { $this->users[] = $user; } - public function getUsers() { + public function getUsers() + { return $this->users; } @@ -59,4 +60,3 @@ public function getIterator() return $this->getUsers(); } } - diff --git a/tests/Doctrine/Tests/Models/CMS/CmsPhonenumber.php b/tests/Doctrine/Tests/Models/CMS/CmsPhonenumber.php index ff28dfd9bff..7f24c63246c 100644 --- a/tests/Doctrine/Tests/Models/CMS/CmsPhonenumber.php +++ b/tests/Doctrine/Tests/Models/CMS/CmsPhonenumber.php @@ -1,5 +1,7 @@ user = $user; } - public function getUser() { + public function getUser() + { return $this->user; } } diff --git a/tests/Doctrine/Tests/Models/CMS/CmsTag.php b/tests/Doctrine/Tests/Models/CMS/CmsTag.php index 2d443b4543b..162b9d2dc75 100644 --- a/tests/Doctrine/Tests/Models/CMS/CmsTag.php +++ b/tests/Doctrine/Tests/Models/CMS/CmsTag.php @@ -1,5 +1,7 @@ name = $name; } - public function getName() { + public function getName() + { return $this->name; } - public function addUser(CmsUser $user) { + public function addUser(CmsUser $user): void + { $this->users[] = $user; } - public function getUsers() { + public function getUsers() + { return $this->users; } } - diff --git a/tests/Doctrine/Tests/Models/CMS/CmsUser.php b/tests/Doctrine/Tests/Models/CMS/CmsUser.php index 153033605bd..d52428c56b6 100644 --- a/tests/Doctrine/Tests/Models/CMS/CmsUser.php +++ b/tests/Doctrine/Tests/Models/CMS/CmsUser.php @@ -1,8 +1,11 @@ phonenumbers = new ArrayCollection; - $this->articles = new ArrayCollection; - $this->groups = new ArrayCollection; - $this->tags = new ArrayCollection; + public function __construct() + { + $this->phonenumbers = new ArrayCollection(); + $this->articles = new ArrayCollection(); + $this->groups = new ArrayCollection(); + $this->tags = new ArrayCollection(); } - public function getId() { + public function getId() + { return $this->id; } - public function getStatus() { + public function getStatus() + { return $this->status; } - public function getUsername() { + public function getUsername() + { return $this->username; } - public function getName() { + public function getName() + { return $this->name; } /** * Adds a phonenumber to the user. - * - * @param CmsPhonenumber $phone */ - public function addPhonenumber(CmsPhonenumber $phone) { + public function addPhonenumber(CmsPhonenumber $phone): void + { $this->phonenumbers[] = $phone; $phone->setUser($this); } - public function getPhonenumbers() { + public function getPhonenumbers() + { return $this->phonenumbers; } - public function addArticle(CmsArticle $article) { + public function addArticle(CmsArticle $article): void + { $this->articles[] = $article; $article->setAuthor($this); } - public function addGroup(CmsGroup $group) { + public function addGroup(CmsGroup $group): void + { $this->groups[] = $group; $group->addUser($this); } - public function getGroups() { + public function getGroups() + { return $this->groups; } - public function addTag(CmsTag $tag) { + public function addTag(CmsTag $tag): void + { $this->tags[] = $tag; $tag->addUser($this); } - public function getTags() { + public function getTags() + { return $this->tags; } - public function removePhonenumber($index) { + public function removePhonenumber($index) + { if (isset($this->phonenumbers[$index])) { $ph = $this->phonenumbers[$index]; unset($this->phonenumbers[$index]); $ph->user = null; + return true; } + return false; } - public function getAddress() { return $this->address; } + public function getAddress() + { + return $this->address; + } - public function setAddress(CmsAddress $address) { + public function setAddress(CmsAddress $address): void + { if ($this->address !== $address) { $this->address = $address; $address->setUser($this); } } - /** - * @return CmsEmail - */ - public function getEmail() { return $this->email; } + public function getEmail(): CmsEmail + { + return $this->email; + } - public function setEmail(CmsEmail $email = null) { + public function setEmail(?CmsEmail $email = null): void + { if ($this->email !== $email) { $this->email = $email; @@ -269,216 +276,209 @@ public function setEmail(CmsEmail $email = null) { } } - public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) + public static function loadMetadata(ClassMetadataInfo $metadata): void { $metadata->setPrimaryTable( - [ - 'name' => 'cms_users', - ] + ['name' => 'cms_users'] ); $metadata->addNamedNativeQuery( [ - 'name' => 'fetchIdAndUsernameWithResultClass', - 'query' => 'SELECT id, username FROM cms_users WHERE username = ?', - 'resultClass' => CmsUser::class, + 'name' => 'fetchIdAndUsernameWithResultClass', + 'query' => 'SELECT id, username FROM cms_users WHERE username = ?', + 'resultClass' => self::class, ] ); $metadata->addNamedNativeQuery( [ - 'name' => 'fetchAllColumns', - 'query' => 'SELECT * FROM cms_users WHERE username = ?', - 'resultClass' => CmsUser::class, + 'name' => 'fetchAllColumns', + 'query' => 'SELECT * FROM cms_users WHERE username = ?', + 'resultClass' => self::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', + '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', + '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', + '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" + '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 + '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' => self::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 + 'name' => 'mappingJoinedPhonenumber', + 'columns' => [], + 'entities' => [ + [ + 'fields' => [ + [ + 'name' => 'id', + 'column' => 'id', + ], + [ + 'name' => 'name', + 'column' => 'name', + ], + [ + 'name' => 'status', + 'column' => 'status', + ], + [ + 'name' => 'phonenumbers.phonenumber', + 'column' => 'number', + ], + ], + 'entityClass' => self::class, + 'discriminatorColumn' => null, + ], ], - ], ] ); $metadata->addSqlResultSetMapping( [ - 'name' => 'mappingUserPhonenumberCount', - 'columns' => [], - 'entities' => [ - [ - 'fields' => [ - [ - 'name' => 'id', - 'column' => 'id', - ], - [ - 'name' => 'name', - 'column' => 'name', - ], - [ - 'name' => 'status', - 'column' => 'status', - ] + 'name' => 'mappingUserPhonenumberCount', + 'columns' => [], + 'entities' => [ + [ + 'fields' => [ + [ + 'name' => 'id', + 'column' => 'id', + ], + [ + 'name' => 'name', + 'column' => 'name', + ], + [ + 'name' => 'status', + 'column' => 'status', + ], + ], + 'entityClass' => self::class, + 'discriminatorColumn' => null, + ], + ], + 'columns' => [ + ['name' => 'numphones'], ], - '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' => 'mappingMultipleJoinsEntityResults', + 'entities' => [ + [ + 'fields' => [ + [ + 'name' => 'id', + 'column' => 'u_id', + ], + [ + 'name' => 'name', + 'column' => 'u_name', + ], + [ + 'name' => 'status', + 'column' => 'u_status', + ], ], - [ - 'name' => 'status', - 'column' => 'u_status', - ] + 'entityClass' => self::class, + 'discriminatorColumn' => null, ], - 'entityClass' => CmsUser::class, - 'discriminatorColumn' => null, - ], - [ - 'fields' => [ - [ - 'name' => 'id', - 'column' => 'a_id', - ], - [ - 'name' => 'zip', - 'column' => 'a_zip', - ], - [ - 'name' => 'country', - 'column' => 'a_country', + [ + 'fields' => [ + [ + 'name' => 'id', + 'column' => 'a_id', + ], + [ + 'name' => 'zip', + 'column' => 'a_zip', + ], + [ + 'name' => 'country', + 'column' => 'a_country', + ], ], + 'entityClass' => CmsAddress::class, + 'discriminatorColumn' => null, ], - 'entityClass' => CmsAddress::class, - 'discriminatorColumn' => null, ], - ], - 'columns' => [ - [ - 'name' => 'numphones', - ] - ] + 'columns' => [ + ['name' => 'numphones'], + ], ] ); - } } diff --git a/tests/Doctrine/Tests/Models/CMS/CmsUserDTO.php b/tests/Doctrine/Tests/Models/CMS/CmsUserDTO.php index ba9fb379e02..e8e724f47a1 100644 --- a/tests/Doctrine/Tests/Models/CMS/CmsUserDTO.php +++ b/tests/Doctrine/Tests/Models/CMS/CmsUserDTO.php @@ -1,5 +1,7 @@ name = $name; - $this->email = $email; - $this->address = $address; - $this->phonenumbers = $phonenumbers; + $this->name = $name; + $this->email = $email; + $this->address = $address; + $this->phonenumbers = $phonenumbers; } } diff --git a/tests/Doctrine/Tests/Models/Cache/Action.php b/tests/Doctrine/Tests/Models/Cache/Action.php index 72bbba4c173..1eda4e36bcf 100644 --- a/tests/Doctrine/Tests/Models/Cache/Action.php +++ b/tests/Doctrine/Tests/Models/Cache/Action.php @@ -1,5 +1,7 @@ name = $name; + $this->name = $name; $this->tokens = new ArrayCollection(); } - public function addToken(Token $token) + public function addToken(Token $token): void { $this->tokens[] = $token; - $token->action = $this; + $token->action = $this; } } diff --git a/tests/Doctrine/Tests/Models/Cache/Address.php b/tests/Doctrine/Tests/Models/Cache/Address.php index 5ccb349d0a0..c6e1f8a09cb 100644 --- a/tests/Doctrine/Tests/Models/Cache/Address.php +++ b/tests/Doctrine/Tests/Models/Cache/Address.php @@ -1,5 +1,7 @@ id; } - public function setId($id) + public function setId($id): void { $this->id = $id; } @@ -64,7 +64,7 @@ public function getName() return $this->name; } - public function setName($name) + public function setName($name): void { $this->name = $name; } @@ -74,7 +74,7 @@ public function getCity() return $this->city; } - public function setCity(City $city) + public function setCity(City $city): void { $this->city = $city; } @@ -84,9 +84,9 @@ public function getInfos() return $this->infos; } - public function addInfo(AttractionInfo $info) + public function addInfo(AttractionInfo $info): void { - if ( ! $this->infos->contains($info)) { + if (! $this->infos->contains($info)) { $this->infos->add($info); } } diff --git a/tests/Doctrine/Tests/Models/Cache/AttractionContactInfo.php b/tests/Doctrine/Tests/Models/Cache/AttractionContactInfo.php index e25665528ad..f052c6d6070 100644 --- a/tests/Doctrine/Tests/Models/Cache/AttractionContactInfo.php +++ b/tests/Doctrine/Tests/Models/Cache/AttractionContactInfo.php @@ -1,5 +1,7 @@ fone; } - public function setFone($fone) + public function setFone($fone): void { $this->fone = $fone; } diff --git a/tests/Doctrine/Tests/Models/Cache/AttractionInfo.php b/tests/Doctrine/Tests/Models/Cache/AttractionInfo.php index 978d8587e25..7d0ada988c4 100644 --- a/tests/Doctrine/Tests/Models/Cache/AttractionInfo.php +++ b/tests/Doctrine/Tests/Models/Cache/AttractionInfo.php @@ -1,5 +1,7 @@ id; } - public function setId($id) + public function setId($id): void { $this->id = $id; } @@ -43,7 +45,7 @@ public function getAttraction() return $this->attraction; } - public function setAttraction(Attraction $attraction) + public function setAttraction(Attraction $attraction): void { $this->attraction = $attraction; diff --git a/tests/Doctrine/Tests/Models/Cache/AttractionLocationInfo.php b/tests/Doctrine/Tests/Models/Cache/AttractionLocationInfo.php index e7419fb4a67..8561aa117bb 100644 --- a/tests/Doctrine/Tests/Models/Cache/AttractionLocationInfo.php +++ b/tests/Doctrine/Tests/Models/Cache/AttractionLocationInfo.php @@ -1,5 +1,7 @@ address; } - public function setAddress($address) + public function setAddress($address): void { $this->address = $address; } diff --git a/tests/Doctrine/Tests/Models/Cache/Bar.php b/tests/Doctrine/Tests/Models/Cache/Bar.php index cc54d547c90..99102d258aa 100644 --- a/tests/Doctrine/Tests/Models/Cache/Bar.php +++ b/tests/Doctrine/Tests/Models/Cache/Bar.php @@ -1,5 +1,7 @@ name = $name; - $this->state = $state; - $this->travels = new ArrayCollection(); - $this->attractions = new ArrayCollection(); + $this->name = $name; + $this->state = $state; + $this->travels = new ArrayCollection(); + $this->attractions = new ArrayCollection(); } public function getId() @@ -55,7 +54,7 @@ public function getId() return $this->id; } - public function setId($id) + public function setId($id): void { $this->id = $id; } @@ -65,7 +64,7 @@ public function getName() return $this->name; } - public function setName($name) + public function setName($name): void { $this->name = $name; } @@ -75,12 +74,12 @@ public function getState() return $this->state; } - public function setState(State $state) + public function setState(State $state): void { $this->state = $state; } - public function addTravel(Travel $travel) + public function addTravel(Travel $travel): void { $this->travels[] = $travel; } @@ -90,7 +89,7 @@ public function getTravels() return $this->travels; } - public function addAttraction(Attraction $attraction) + public function addAttraction(Attraction $attraction): void { $this->attractions[] = $attraction; } @@ -100,7 +99,7 @@ public function getAttractions() return $this->attractions; } - public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) + public static function loadMetadata(ClassMetadataInfo $metadata): void { 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..17d3941ead9 100644 --- a/tests/Doctrine/Tests/Models/Cache/Client.php +++ b/tests/Doctrine/Tests/Models/Cache/Client.php @@ -1,5 +1,7 @@ name = $name; + $this->name = $name; $this->action1 = $action1; $this->action2 = $action2; - $this->tokens = new ArrayCollection(); + $this->tokens = new ArrayCollection(); } - public function addToken(Token $token) + public function addToken(Token $token): void { - $this->tokens[] = $token; + $this->tokens[] = $token; $token->complexAction = $this; } - /** - * @return Action - */ - public function getAction1() + public function getAction1(): Action { return $this->action1; } - /** - * @return Action - */ - public function getAction2() + public function getAction2(): Action { return $this->action2; } diff --git a/tests/Doctrine/Tests/Models/Cache/Country.php b/tests/Doctrine/Tests/Models/Cache/Country.php index f4179f63e75..07a1763c2c0 100644 --- a/tests/Doctrine/Tests/Models/Cache/Country.php +++ b/tests/Doctrine/Tests/Models/Cache/Country.php @@ -1,5 +1,7 @@ id; } - public function setId($id) + public function setId($id): void { $this->id = $id; } @@ -41,7 +41,7 @@ public function getName() return $this->name; } - public function setName($name) + public function setName($name): void { $this->name = $name; } diff --git a/tests/Doctrine/Tests/Models/Cache/Flight.php b/tests/Doctrine/Tests/Models/Cache/Flight.php index f109c34da38..f31ce9a2f6f 100644 --- a/tests/Doctrine/Tests/Models/Cache/Flight.php +++ b/tests/Doctrine/Tests/Models/Cache/Flight.php @@ -1,7 +1,11 @@ goingTo = $goingTo; - $this->leavingFrom = $leavingFrom; - $this->departure = new \DateTime(); + $this->goingTo = $goingTo; + $this->leavingFrom = $leavingFrom; + $this->departure = new DateTime(); } public function getLeavingFrom() @@ -56,7 +54,7 @@ public function getDeparture() return $this->departure; } - public function setDeparture($departure) + public function setDeparture($departure): void { $this->departure = $departure; } diff --git a/tests/Doctrine/Tests/Models/Cache/Login.php b/tests/Doctrine/Tests/Models/Cache/Login.php index 24e5b133dac..4badfc11742 100644 --- a/tests/Doctrine/Tests/Models/Cache/Login.php +++ b/tests/Doctrine/Tests/Models/Cache/Login.php @@ -1,5 +1,7 @@ name = $name; } - /** - * @return Token - */ - public function getToken() + public function getToken(): Token { return $this->token; } diff --git a/tests/Doctrine/Tests/Models/Cache/Person.php b/tests/Doctrine/Tests/Models/Cache/Person.php index 01ab416aac4..d026e153e7b 100644 --- a/tests/Doctrine/Tests/Models/Cache/Person.php +++ b/tests/Doctrine/Tests/Models/Cache/Person.php @@ -1,5 +1,7 @@ name = $name; - $this->country = $country; - $this->cities = new ArrayCollection(); + $this->name = $name; + $this->country = $country; + $this->cities = new ArrayCollection(); } public function getId() @@ -48,7 +48,7 @@ public function getId() return $this->id; } - public function setId($id) + public function setId($id): void { $this->id = $id; } @@ -58,7 +58,7 @@ public function getName() return $this->name; } - public function setName($name) + public function setName($name): void { $this->name = $name; } @@ -68,7 +68,7 @@ public function getCountry() return $this->country; } - public function setCountry(Country $country) + public function setCountry(Country $country): void { $this->country = $country; } @@ -78,12 +78,12 @@ public function getCities() return $this->cities; } - public function setCities(ArrayCollection $cities) + public function setCities(ArrayCollection $cities): void { $this->cities = $cities; } - public function addCity(City $city) + public function addCity(City $city): void { $this->cities[] = $city; } diff --git a/tests/Doctrine/Tests/Models/Cache/Token.php b/tests/Doctrine/Tests/Models/Cache/Token.php index bcfbb1b9121..d2511ecfd39 100644 --- a/tests/Doctrine/Tests/Models/Cache/Token.php +++ b/tests/Doctrine/Tests/Models/Cache/Token.php @@ -1,8 +1,15 @@ logins = new ArrayCollection(); $this->token = $token; $this->client = $client; - $this->expiresAt = new \DateTime(date('Y-m-d H:i:s', strtotime("+7 day"))); + $this->expiresAt = new DateTime(date('Y-m-d H:i:s', strtotime('+7 day'))); } - /** - * @param Login $login - */ - public function addLogin(Login $login) + public function addLogin(Login $login): void { $this->logins[] = $login; - $login->token = $this; + $login->token = $this; } - /** - * @return Client - */ - public function getClient() + public function getClient(): Client { return $this->client; } - /** - * @return Action - */ - public function getAction() + public function getAction(): Action { return $this->action; } - /** - * @return ComplexAction - */ - public function getComplexAction() + public function getComplexAction(): ComplexAction { return $this->complexAction; } - } diff --git a/tests/Doctrine/Tests/Models/Cache/Travel.php b/tests/Doctrine/Tests/Models/Cache/Travel.php index 1e0240066a5..7e8bdc0c631 100644 --- a/tests/Doctrine/Tests/Models/Cache/Travel.php +++ b/tests/Doctrine/Tests/Models/Cache/Travel.php @@ -1,7 +1,10 @@ traveler = $traveler; - $this->createdAt = new \DateTime('now'); + $this->createdAt = new DateTime('now'); $this->visitedCities = new ArrayCollection(); } - /** - * @return integer - */ - public function getId() + public function getId(): int { return $this->id; } - /** - * @return \Doctrine\Tests\Models\Cache\Traveler - */ - public function getTraveler() + public function getTraveler(): Traveler { return $this->traveler; } - /** - * @param \Doctrine\Tests\Models\Cache\Traveler $traveler - */ - public function setTraveler(Traveler $traveler) + public function setTraveler(Traveler $traveler): void { $this->traveler = $traveler; } - /** - * @return \Doctrine\Common\Collections\ArrayCollection - */ - public function getVisitedCities() + public function getVisitedCities(): ArrayCollection { return $this->visitedCities; } - /** - * @param \Doctrine\Tests\Models\Cache\City $city - */ - public function addVisitedCity(City $city) + public function addVisitedCity(City $city): void { $this->visitedCities->add($city); } - /** - * @param \Doctrine\Tests\Models\Cache\City $city - */ - public function removeVisitedCity(City $city) + public function removeVisitedCity(City $city): void { $this->visitedCities->removeElement($city); } - /** - * @return \DateTime - */ - public function getCreatedAt() + public function getCreatedAt(): DateTime { return $this->createdAt; } diff --git a/tests/Doctrine/Tests/Models/Cache/Traveler.php b/tests/Doctrine/Tests/Models/Cache/Traveler.php index c8b68565b99..36ce811ee3d 100644 --- a/tests/Doctrine/Tests/Models/Cache/Traveler.php +++ b/tests/Doctrine/Tests/Models/Cache/Traveler.php @@ -1,8 +1,11 @@ name = $name; - $this->travels = new ArrayCollection(); + $this->name = $name; + $this->travels = new ArrayCollection(); } public function getId() @@ -51,7 +48,7 @@ public function getId() return $this->id; } - public function setId($id) + public function setId($id): void { $this->id = $id; } @@ -61,23 +58,17 @@ public function getName() return $this->name; } - public function setName($name) + public function setName($name): void { $this->name = $name; } - /** - * @return \Doctrine\Tests\Models\Cache\TravelerProfile - */ - public function getProfile() + public function getProfile(): TravelerProfile { return $this->profile; } - /** - * @param \Doctrine\Tests\Models\Cache\TravelerProfile $profile - */ - public function setProfile(TravelerProfile $profile) + public function setProfile(TravelerProfile $profile): void { $this->profile = $profile; } @@ -87,12 +78,9 @@ public function getTravels() return $this->travels; } - /** - * @param \Doctrine\Tests\Models\Cache\Travel $item - */ - public function addTravel(Travel $item) + public function addTravel(Travel $item): void { - if ( ! $this->travels->contains($item)) { + if (! $this->travels->contains($item)) { $this->travels->add($item); } @@ -101,10 +89,7 @@ public function addTravel(Travel $item) } } - /** - * @param \Doctrine\Tests\Models\Cache\Travel $item - */ - public function removeTravel(Travel $item) + public function removeTravel(Travel $item): void { $this->travels->removeElement($item); } diff --git a/tests/Doctrine/Tests/Models/Cache/TravelerProfile.php b/tests/Doctrine/Tests/Models/Cache/TravelerProfile.php index 03b9c7d3d9e..5749ad15222 100644 --- a/tests/Doctrine/Tests/Models/Cache/TravelerProfile.php +++ b/tests/Doctrine/Tests/Models/Cache/TravelerProfile.php @@ -1,5 +1,7 @@ id; } - public function setId($id) + public function setId($id): void { $this->id = $id; } @@ -47,7 +47,7 @@ public function getName() return $this->name; } - public function setName($nae) + public function setName($nae): void { $this->name = $nae; } @@ -57,7 +57,7 @@ public function getInfo() return $this->info; } - public function setInfo(TravelerProfileInfo $info) + public function setInfo(TravelerProfileInfo $info): void { $this->info = $info; } diff --git a/tests/Doctrine/Tests/Models/Cache/TravelerProfileInfo.php b/tests/Doctrine/Tests/Models/Cache/TravelerProfileInfo.php index 154ce9600dd..0402f60cc9b 100644 --- a/tests/Doctrine/Tests/Models/Cache/TravelerProfileInfo.php +++ b/tests/Doctrine/Tests/Models/Cache/TravelerProfileInfo.php @@ -1,5 +1,7 @@ id; } - public function setId($id) + public function setId($id): void { $this->id = $id; } @@ -49,7 +49,7 @@ public function getDescription() return $this->description; } - public function setDescription($description) + public function setDescription($description): void { $this->description = $description; } @@ -59,7 +59,7 @@ public function getProfile() return $this->profile; } - public function setProfile(TravelerProfile $profile) + public function setProfile(TravelerProfile $profile): void { $this->profile = $profile; } diff --git a/tests/Doctrine/Tests/Models/Company/CompanyAuction.php b/tests/Doctrine/Tests/Models/Company/CompanyAuction.php index 5743122bc77..ddf04227457 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyAuction.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyAuction.php @@ -1,17 +1,22 @@ data = $data; } - public function getData() { + public function getData() + { return $this->data; } } diff --git a/tests/Doctrine/Tests/Models/Company/CompanyCar.php b/tests/Doctrine/Tests/Models/Company/CompanyCar.php index 9c7b7286aae..5e940d814f7 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyCar.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyCar.php @@ -1,5 +1,7 @@ brand = $brand; } - public function getId() { + public function getId() + { return $this->id; } - public function getBrand() { + public function getBrand() + { return $this->title; } } diff --git a/tests/Doctrine/Tests/Models/Company/CompanyContract.php b/tests/Doctrine/Tests/Models/Company/CompanyContract.php index 15e691ba087..7751b5ea933 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyContract.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyContract.php @@ -1,7 +1,14 @@ engineers = new \Doctrine\Common\Collections\ArrayCollection; + $this->engineers = new ArrayCollection(); } public function getId() @@ -93,7 +94,7 @@ public function getId() return $this->id; } - public function markCompleted() + public function markCompleted(): void { $this->completed = true; } @@ -108,7 +109,7 @@ public function getSalesPerson() return $this->salesPerson; } - public function setSalesPerson(CompanyEmployee $salesPerson) + public function setSalesPerson(CompanyEmployee $salesPerson): void { $this->salesPerson = $salesPerson; } @@ -118,63 +119,63 @@ public function getEngineers() return $this->engineers; } - public function addEngineer(CompanyEmployee $engineer) + public function addEngineer(CompanyEmployee $engineer): void { $this->engineers[] = $engineer; } - public function removeEngineer(CompanyEmployee $engineer) + public function removeEngineer(CompanyEmployee $engineer): void { $this->engineers->removeElement($engineer); } - abstract public function calculatePrice(); + abstract public function calculatePrice(): void; - static public function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) + public static function loadMetadata(ClassMetadataInfo $metadata): void { - $metadata->setInheritanceType(\Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_JOINED); - $metadata->setTableName( 'company_contracts'); + $metadata->setInheritanceType(ClassMetadata::INHERITANCE_TYPE_JOINED); + $metadata->setTableName('company_contracts'); $metadata->setDiscriminatorColumn( [ - 'name' => 'discr', - 'type' => 'string', + 'name' => 'discr', + 'type' => 'string', ] ); $metadata->mapField( [ - 'id' => true, - 'name' => 'id', - 'fieldName' => 'id', + 'id' => true, + 'name' => 'id', + 'fieldName' => 'id', ] ); $metadata->mapField( [ - 'type' => 'boolean', - 'name' => 'completed', - 'fieldName' => 'completed', + 'type' => 'boolean', + 'name' => 'completed', + 'fieldName' => 'completed', ] ); $metadata->setDiscriminatorMap( [ - "fix" => "CompanyFixContract", - "flexible" => "CompanyFlexContract", - "flexultra" => "CompanyFlexUltraContract" + 'fix' => 'CompanyFixContract', + 'flexible' => 'CompanyFlexContract', + 'flexultra' => 'CompanyFlexUltraContract', ] ); - $metadata->addEntityListener(\Doctrine\ORM\Events::postPersist, 'CompanyContractListener', 'postPersistHandler'); - $metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CompanyContractListener', 'prePersistHandler'); + $metadata->addEntityListener(Events::postPersist, 'CompanyContractListener', 'postPersistHandler'); + $metadata->addEntityListener(Events::prePersist, 'CompanyContractListener', 'prePersistHandler'); - $metadata->addEntityListener(\Doctrine\ORM\Events::postUpdate, 'CompanyContractListener', 'postUpdateHandler'); - $metadata->addEntityListener(\Doctrine\ORM\Events::preUpdate, 'CompanyContractListener', 'preUpdateHandler'); + $metadata->addEntityListener(Events::postUpdate, 'CompanyContractListener', 'postUpdateHandler'); + $metadata->addEntityListener(Events::preUpdate, 'CompanyContractListener', 'preUpdateHandler'); - $metadata->addEntityListener(\Doctrine\ORM\Events::postRemove, 'CompanyContractListener', 'postRemoveHandler'); - $metadata->addEntityListener(\Doctrine\ORM\Events::preRemove, 'CompanyContractListener', 'preRemoveHandler'); + $metadata->addEntityListener(Events::postRemove, 'CompanyContractListener', 'postRemoveHandler'); + $metadata->addEntityListener(Events::preRemove, 'CompanyContractListener', 'preRemoveHandler'); - $metadata->addEntityListener(\Doctrine\ORM\Events::preFlush, 'CompanyContractListener', 'preFlushHandler'); - $metadata->addEntityListener(\Doctrine\ORM\Events::postLoad, 'CompanyContractListener', 'postLoadHandler'); + $metadata->addEntityListener(Events::preFlush, 'CompanyContractListener', 'preFlushHandler'); + $metadata->addEntityListener(Events::postLoad, 'CompanyContractListener', 'postLoadHandler'); } } diff --git a/tests/Doctrine/Tests/Models/Company/CompanyContractListener.php b/tests/Doctrine/Tests/Models/Company/CompanyContractListener.php index 23714f32983..6df9076a440 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyContractListener.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyContractListener.php @@ -1,7 +1,11 @@ postPersistCalls[] = func_get_args(); } @@ -28,7 +32,7 @@ public function postPersistHandler(CompanyContract $contract) /** * @PrePersist */ - public function prePersistHandler(CompanyContract $contract) + public function prePersistHandler(CompanyContract $contract): void { $this->prePersistCalls[] = func_get_args(); } @@ -36,7 +40,7 @@ public function prePersistHandler(CompanyContract $contract) /** * @PostUpdate */ - public function postUpdateHandler(CompanyContract $contract) + public function postUpdateHandler(CompanyContract $contract): void { $this->postUpdateCalls[] = func_get_args(); } @@ -44,7 +48,7 @@ public function postUpdateHandler(CompanyContract $contract) /** * @PreUpdate */ - public function preUpdateHandler(CompanyContract $contract) + public function preUpdateHandler(CompanyContract $contract): void { $this->preUpdateCalls[] = func_get_args(); } @@ -52,7 +56,7 @@ public function preUpdateHandler(CompanyContract $contract) /** * @PostRemove */ - public function postRemoveHandler(CompanyContract $contract) + public function postRemoveHandler(CompanyContract $contract): void { $this->postRemoveCalls[] = func_get_args(); } @@ -60,7 +64,7 @@ public function postRemoveHandler(CompanyContract $contract) /** * @PreRemove */ - public function preRemoveHandler(CompanyContract $contract) + public function preRemoveHandler(CompanyContract $contract): void { $this->preRemoveCalls[] = func_get_args(); } @@ -68,7 +72,7 @@ public function preRemoveHandler(CompanyContract $contract) /** * @PreFlush */ - public function preFlushHandler(CompanyContract $contract) + public function preFlushHandler(CompanyContract $contract): void { $this->preFlushCalls[] = func_get_args(); } @@ -76,7 +80,7 @@ public function preFlushHandler(CompanyContract $contract) /** * @PostLoad */ - public function postLoadHandler(CompanyContract $contract) + public function postLoadHandler(CompanyContract $contract): void { $this->postLoadCalls[] = func_get_args(); } diff --git a/tests/Doctrine/Tests/Models/Company/CompanyEmployee.php b/tests/Doctrine/Tests/Models/Company/CompanyEmployee.php index 9d153770e0c..09c67fb2354 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyEmployee.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyEmployee.php @@ -1,5 +1,7 @@ salary; } - public function setSalary($salary) { + public function setSalary($salary): void + { $this->salary = $salary; } - public function getDepartment() { + public function getDepartment() + { return $this->department; } - public function setDepartment($dep) { + public function setDepartment($dep): void + { $this->department = $dep; } - public function getStartDate() { + public function getStartDate() + { return $this->startDate; } - public function setStartDate($date) { + public function setStartDate($date): void + { $this->startDate = $date; } } diff --git a/tests/Doctrine/Tests/Models/Company/CompanyEvent.php b/tests/Doctrine/Tests/Models/Company/CompanyEvent.php index bf6620e4723..c44fcf6cf7d 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyEvent.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyEvent.php @@ -1,5 +1,7 @@ id; - } - - public function getOrganization() { - return $this->organization; - } + public function getId() + { + return $this->id; + } - public function setOrganization(CompanyOrganization $org) { - $this->organization = $org; - } + public function getOrganization() + { + return $this->organization; + } + public function setOrganization(CompanyOrganization $org): void + { + $this->organization = $org; + } } diff --git a/tests/Doctrine/Tests/Models/Company/CompanyFixContract.php b/tests/Doctrine/Tests/Models/Company/CompanyFixContract.php index 8fe94e2584d..4cd31c0a893 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyFixContract.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyFixContract.php @@ -1,7 +1,11 @@ fixPrice; } - public function setFixPrice($fixPrice) + public function setFixPrice($fixPrice): void { $this->fixPrice = $fixPrice; } - static public function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) + public static function loadMetadata(ClassMetadataInfo $metadata): void { $metadata->mapField( [ - 'type' => 'integer', - 'name' => 'fixPrice', - 'fieldName' => 'fixPrice', + '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..ff13f1e9a97 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyFlexContract.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyFlexContract.php @@ -1,9 +1,13 @@ hoursWorked; } - public function setHoursWorked($hoursWorked) + public function setHoursWorked($hoursWorked): void { $this->hoursWorked = $hoursWorked; } @@ -89,40 +92,41 @@ public function getPricePerHour() return $this->pricePerHour; } - public function setPricePerHour($pricePerHour) + public function setPricePerHour($pricePerHour): void { $this->pricePerHour = $pricePerHour; } + public function getManagers() { return $this->managers; } - public function addManager(CompanyManager $manager) + public function addManager(CompanyManager $manager): void { $this->managers[] = $manager; } - public function removeManager(CompanyManager $manager) + public function removeManager(CompanyManager $manager): void { $this->managers->removeElement($manager); } - static public function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) + public static function loadMetadata(ClassMetadataInfo $metadata): void { $metadata->mapField( [ - 'type' => 'integer', - 'name' => 'hoursWorked', - 'fieldName' => 'hoursWorked', + 'type' => 'integer', + 'name' => 'hoursWorked', + 'fieldName' => 'hoursWorked', ] ); $metadata->mapField( [ - 'type' => 'integer', - 'name' => 'pricePerHour', - 'fieldName' => 'pricePerHour', + '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..893a0383c60 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyFlexUltraContract.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyFlexUltraContract.php @@ -1,7 +1,14 @@ maxPrice; } - public function setMaxPrice($maxPrice) + public function setMaxPrice($maxPrice): void { $this->maxPrice = $maxPrice; } - static public function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) + public static function loadMetadata(ClassMetadataInfo $metadata): void { $metadata->mapField( [ - 'type' => 'integer', - 'name' => 'maxPrice', - 'fieldName' => 'maxPrice', + 'type' => 'integer', + 'name' => 'maxPrice', + 'fieldName' => 'maxPrice', ] ); - $metadata->addEntityListener(\Doctrine\ORM\Events::postPersist, 'CompanyContractListener', 'postPersistHandler'); - $metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CompanyContractListener', 'prePersistHandler'); + $metadata->addEntityListener(Events::postPersist, 'CompanyContractListener', 'postPersistHandler'); + $metadata->addEntityListener(Events::prePersist, 'CompanyContractListener', 'prePersistHandler'); - $metadata->addEntityListener(\Doctrine\ORM\Events::postUpdate, 'CompanyContractListener', 'postUpdateHandler'); - $metadata->addEntityListener(\Doctrine\ORM\Events::preUpdate, 'CompanyContractListener', 'preUpdateHandler'); + $metadata->addEntityListener(Events::postUpdate, 'CompanyContractListener', 'postUpdateHandler'); + $metadata->addEntityListener(Events::preUpdate, 'CompanyContractListener', 'preUpdateHandler'); - $metadata->addEntityListener(\Doctrine\ORM\Events::postRemove, 'CompanyContractListener', 'postRemoveHandler'); - $metadata->addEntityListener(\Doctrine\ORM\Events::preRemove, 'CompanyContractListener', 'preRemoveHandler'); + $metadata->addEntityListener(Events::postRemove, 'CompanyContractListener', 'postRemoveHandler'); + $metadata->addEntityListener(Events::preRemove, 'CompanyContractListener', 'preRemoveHandler'); - $metadata->addEntityListener(\Doctrine\ORM\Events::preFlush, 'CompanyContractListener', 'preFlushHandler'); - $metadata->addEntityListener(\Doctrine\ORM\Events::postLoad, 'CompanyContractListener', 'postLoadHandler'); + $metadata->addEntityListener(Events::preFlush, 'CompanyContractListener', 'preFlushHandler'); + $metadata->addEntityListener(Events::postLoad, 'CompanyContractListener', 'postLoadHandler'); - $metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CompanyFlexUltraContractListener', 'prePersistHandler1'); - $metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CompanyFlexUltraContractListener', 'prePersistHandler2'); + $metadata->addEntityListener(Events::prePersist, 'CompanyFlexUltraContractListener', 'prePersistHandler1'); + $metadata->addEntityListener(Events::prePersist, 'CompanyFlexUltraContractListener', 'prePersistHandler2'); } } diff --git a/tests/Doctrine/Tests/Models/Company/CompanyFlexUltraContractListener.php b/tests/Doctrine/Tests/Models/Company/CompanyFlexUltraContractListener.php index 2f028e35f0f..dfc997ee829 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyFlexUltraContractListener.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyFlexUltraContractListener.php @@ -1,9 +1,13 @@ prePersistCalls[] = func_get_args(); } @@ -19,7 +23,7 @@ public function prePersistHandler1(CompanyContract $contract, LifecycleEventArgs /** * @PrePersist */ - public function prePersistHandler2(CompanyContract $contract, LifecycleEventArgs $args) + public function prePersistHandler2(CompanyContract $contract, LifecycleEventArgs $args): void { $this->prePersistCalls[] = func_get_args(); } diff --git a/tests/Doctrine/Tests/Models/Company/CompanyManager.php b/tests/Doctrine/Tests/Models/Company/CompanyManager.php index aec9a77ae9e..9bd25caade4 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyManager.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyManager.php @@ -1,5 +1,7 @@ title; } - public function setTitle($title) { + public function setTitle($title): void + { $this->title = $title; } - public function getCar() { + public function getCar() + { return $this->car; } - public function setCar(CompanyCar $car) { + public function setCar(CompanyCar $car): void + { $this->car = $car; } } diff --git a/tests/Doctrine/Tests/Models/Company/CompanyOrganization.php b/tests/Doctrine/Tests/Models/Company/CompanyOrganization.php index ca9941062d5..320e11b29e7 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyOrganization.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyOrganization.php @@ -1,29 +1,33 @@ id; } - public function getEvents() { + public function getEvents() + { return $this->events; } - public function addEvent(CompanyEvent $event) { + public function addEvent(CompanyEvent $event): void + { $this->events[] = $event; $event->setOrganization($this); } @@ -34,11 +38,13 @@ public function addEvent(CompanyEvent $event) { */ private $mainevent; - public function getMainEvent() { + public function getMainEvent() + { return $this->mainevent; } - public function setMainEvent($event) { + public function setMainEvent($event): void + { $this->mainevent = $event; } } diff --git a/tests/Doctrine/Tests/Models/Company/CompanyPerson.php b/tests/Doctrine/Tests/Models/Company/CompanyPerson.php index ca80c953dcb..63f7dbe8242 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyPerson.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyPerson.php @@ -1,11 +1,15 @@ friends = new \Doctrine\Common\Collections\ArrayCollection; + public function __construct() + { + $this->friends = new ArrayCollection(); } - public function getId() { - return $this->id; + public function getId() + { + return $this->id; } - public function getName() { + public function getName() + { return $this->name; } - public function setName($name) { + public function setName($name): void + { $this->name = $name; } - public function getSpouse() { + public function getSpouse() + { return $this->spouse; } - public function getFriends() { + public function getFriends() + { return $this->friends; } - public function addFriend(CompanyPerson $friend) { - if ( ! $this->friends->contains($friend)) { + public function addFriend(CompanyPerson $friend): void + { + if (! $this->friends->contains($friend)) { $this->friends->add($friend); $friend->addFriend($this); } } - public function setSpouse(CompanyPerson $spouse) { + public function setSpouse(CompanyPerson $spouse): void + { if ($spouse !== $this->spouse) { $this->spouse = $spouse; $this->spouse->setSpouse($this); } } - public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) + public static function loadMetadata(ClassMetadataInfo $metadata): void { - $metadata->setPrimaryTable( - [ - 'name' => 'company_person', - ] + ['name' => 'company_person'] ); $metadata->addNamedNativeQuery( [ - 'name' => 'fetchAllWithResultClass', - 'query' => 'SELECT id, name, discr FROM company_persons ORDER BY name', - 'resultClass' => CompanyPerson::class, + 'name' => 'fetchAllWithResultClass', + 'query' => 'SELECT id, name, discr FROM company_persons ORDER BY name', + 'resultClass' => self::class, ] ); $metadata->addNamedNativeQuery( [ - 'name' => 'fetchAllWithSqlResultSetMapping', - 'query' => 'SELECT id, name, discr AS discriminator FROM company_persons ORDER BY name', - 'resultSetMapping' => 'mappingFetchAll', + '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', - ], + 'name' => 'mappingFetchAll', + 'columns' => [], + 'entities' => [ + [ + 'fields' => [ + [ + 'name' => 'id', + 'column' => 'id', + ], + [ + 'name' => 'name', + 'column' => 'name', + ], + ], + 'entityClass' => self::class, + 'discriminatorColumn' => 'discriminator', + ], ], - 'entityClass' => CompanyPerson::class, - 'discriminatorColumn' => 'discriminator', - ], - ], ] ); } } - diff --git a/tests/Doctrine/Tests/Models/Company/CompanyRaffle.php b/tests/Doctrine/Tests/Models/Company/CompanyRaffle.php index f893c0db9a9..08194609c4d 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyRaffle.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyRaffle.php @@ -1,17 +1,22 @@ data = $data; } - public function getData() { + public function getData() + { return $this->data; } } diff --git a/tests/Doctrine/Tests/Models/CompositeKeyInheritance/JoinedChildClass.php b/tests/Doctrine/Tests/Models/CompositeKeyInheritance/JoinedChildClass.php index ba59736470d..baa5cfc73ce 100644 --- a/tests/Doctrine/Tests/Models/CompositeKeyInheritance/JoinedChildClass.php +++ b/tests/Doctrine/Tests/Models/CompositeKeyInheritance/JoinedChildClass.php @@ -1,4 +1,7 @@ id = $id; diff --git a/tests/Doctrine/Tests/Models/CustomType/CustomIdObjectTypeParent.php b/tests/Doctrine/Tests/Models/CustomType/CustomIdObjectTypeParent.php index 21ce535b8a8..6a00b6326a4 100644 --- a/tests/Doctrine/Tests/Models/CustomType/CustomIdObjectTypeParent.php +++ b/tests/Doctrine/Tests/Models/CustomType/CustomIdObjectTypeParent.php @@ -1,9 +1,11 @@ id = $id; diff --git a/tests/Doctrine/Tests/Models/CustomType/CustomTypeChild.php b/tests/Doctrine/Tests/Models/CustomType/CustomTypeChild.php index e178ab51c39..cdb61a00469 100644 --- a/tests/Doctrine/Tests/Models/CustomType/CustomTypeChild.php +++ b/tests/Doctrine/Tests/Models/CustomType/CustomTypeChild.php @@ -1,5 +1,7 @@ friendsWithMe = new \Doctrine\Common\Collections\ArrayCollection(); - $this->myFriends = new \Doctrine\Common\Collections\ArrayCollection(); + $this->friendsWithMe = new ArrayCollection(); + $this->myFriends = new ArrayCollection(); } - public function addMyFriend(CustomTypeParent $friend) + public function addMyFriend(CustomTypeParent $friend): void { $this->getMyFriends()->add($friend); $friend->addFriendWithMe($this); @@ -56,7 +54,7 @@ public function getMyFriends() return $this->myFriends; } - public function addFriendWithMe(CustomTypeParent $friend) + public function addFriendWithMe(CustomTypeParent $friend): void { $this->getFriendsWithMe()->add($friend); } diff --git a/tests/Doctrine/Tests/Models/CustomType/CustomTypeUpperCase.php b/tests/Doctrine/Tests/Models/CustomType/CustomTypeUpperCase.php index e4b46e8809b..2c1fd1e1cbb 100644 --- a/tests/Doctrine/Tests/Models/CustomType/CustomTypeUpperCase.php +++ b/tests/Doctrine/Tests/Models/CustomType/CustomTypeUpperCase.php @@ -1,5 +1,7 @@ articleDetails = $details; - $this->reference = $reference; - $this->translation = $translation; + $this->reference = $reference; + $this->translation = $translation; } public function getId() diff --git a/tests/Doctrine/Tests/Models/DDC117/DDC117Article.php b/tests/Doctrine/Tests/Models/DDC117/DDC117Article.php index 9d57b56523a..f84d3d37efe 100644 --- a/tests/Doctrine/Tests/Models/DDC117/DDC117Article.php +++ b/tests/Doctrine/Tests/Models/DDC117/DDC117Article.php @@ -1,7 +1,11 @@ title = $title; - $this->references = new \Doctrine\Common\Collections\ArrayCollection(); - $this->translations = new \Doctrine\Common\Collections\ArrayCollection(); + $this->title = $title; + $this->references = new ArrayCollection(); + $this->translations = new ArrayCollection(); } - public function setDetails($details) + public function setDetails($details): void { $this->details = $details; } @@ -50,7 +46,7 @@ public function id() return $this->id; } - public function addReference($reference) + public function addReference($reference): void { $this->references[] = $reference; } @@ -60,7 +56,7 @@ public function references() return $this->references; } - public function addTranslation($language, $title) + public function addTranslation($language, $title): void { $this->translations[] = new DDC117Translation($this, $language, $title); } @@ -79,7 +75,8 @@ public function getLinks() { return $this->links; } - public function resetText() + + public function resetText(): void { $this->details = null; } diff --git a/tests/Doctrine/Tests/Models/DDC117/DDC117ArticleDetails.php b/tests/Doctrine/Tests/Models/DDC117/DDC117ArticleDetails.php index ab1d4bfb9fb..29be3e5f7ca 100644 --- a/tests/Doctrine/Tests/Models/DDC117/DDC117ArticleDetails.php +++ b/tests/Doctrine/Tests/Models/DDC117/DDC117ArticleDetails.php @@ -1,5 +1,7 @@ update($text); } - public function update($text) + public function update($text): void { $this->text = $text; } diff --git a/tests/Doctrine/Tests/Models/DDC117/DDC117Editor.php b/tests/Doctrine/Tests/Models/DDC117/DDC117Editor.php index 2b1c502d6f0..068d8c1ceda 100644 --- a/tests/Doctrine/Tests/Models/DDC117/DDC117Editor.php +++ b/tests/Doctrine/Tests/Models/DDC117/DDC117Editor.php @@ -1,20 +1,20 @@ name = $name; - $this->reviewingTranslations = new \Doctrine\Common\Collections\ArrayCollection(); + $this->name = $name; + $this->reviewingTranslations = new ArrayCollection(); } - public function addLastTranslation(DDC117Translation $t) + public function addLastTranslation(DDC117Translation $t): void { $this->lastTranslation = $t; $t->lastTranslatedBy[] = $this; diff --git a/tests/Doctrine/Tests/Models/DDC117/DDC117Link.php b/tests/Doctrine/Tests/Models/DDC117/DDC117Link.php index 7e0084a67d7..af221950b69 100644 --- a/tests/Doctrine/Tests/Models/DDC117/DDC117Link.php +++ b/tests/Doctrine/Tests/Models/DDC117/DDC117Link.php @@ -1,5 +1,7 @@ addReference($this); $target->addReference($this); - $this->source = $source; - $this->target = $target; + $this->source = $source; + $this->target = $target; $this->description = $description; - $this->created = new \DateTime("now"); + $this->created = new DateTime('now'); } public function source() @@ -52,7 +52,7 @@ public function target() return $this->target; } - public function setDescription($desc) + public function setDescription($desc): void { $this->description = $desc; } diff --git a/tests/Doctrine/Tests/Models/DDC117/DDC117Translation.php b/tests/Doctrine/Tests/Models/DDC117/DDC117Translation.php index b0fb4375db7..308d84f9bd6 100644 --- a/tests/Doctrine/Tests/Models/DDC117/DDC117Translation.php +++ b/tests/Doctrine/Tests/Models/DDC117/DDC117Translation.php @@ -1,7 +1,11 @@ article = $article; - $this->language = $language; - $this->title = $title; - $this->reviewedByEditors = new \Doctrine\Common\Collections\ArrayCollection(); - $this->lastTranslatedBy = new \Doctrine\Common\Collections\ArrayCollection(); + $this->article = $article; + $this->language = $language; + $this->title = $title; + $this->reviewedByEditors = new ArrayCollection(); + $this->lastTranslatedBy = new ArrayCollection(); } public function getArticleId() diff --git a/tests/Doctrine/Tests/Models/DDC1476/DDC1476EntityWithDefaultFieldType.php b/tests/Doctrine/Tests/Models/DDC1476/DDC1476EntityWithDefaultFieldType.php index b543b0fe589..ad9a9ea57c2 100644 --- a/tests/Doctrine/Tests/Models/DDC1476/DDC1476EntityWithDefaultFieldType.php +++ b/tests/Doctrine/Tests/Models/DDC1476/DDC1476EntityWithDefaultFieldType.php @@ -1,13 +1,16 @@ id; } - /** - * @return string - */ - public function getName() + public function getName(): string { return $this->name; } - /** - * @param string $name - */ - public function setName($name) + public function setName(string $name): void { $this->name = $name; } - public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) + public static function loadMetadata(ClassMetadataInfo $metadata): void { $metadata->mapField( [ - 'id' => true, - 'fieldName' => 'id', + 'id' => true, + 'fieldName' => 'id', ] ); $metadata->mapField( - [ - 'fieldName' => 'name', - ] + ['fieldName' => 'name'] ); - $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadataInfo::GENERATOR_TYPE_NONE); + $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE); } - } diff --git a/tests/Doctrine/Tests/Models/DDC1590/DDC1590Entity.php b/tests/Doctrine/Tests/Models/DDC1590/DDC1590Entity.php index 2bb75f2e0e8..ed2dbe8984d 100644 --- a/tests/Doctrine/Tests/Models/DDC1590/DDC1590Entity.php +++ b/tests/Doctrine/Tests/Models/DDC1590/DDC1590Entity.php @@ -1,7 +1,11 @@ id; } /** * Set createdAt - * - * @param \DateTime $createdAt - * - * @return DDC1590User */ - public function setCreatedAt($createdAt) + public function setCreatedAt(DateTime $createdAt): DDC1590User { $this->created_at = $createdAt; @@ -46,10 +42,8 @@ public function setCreatedAt($createdAt) /** * Get createdAt - * - * @return \DateTime */ - public function getCreatedAt() + public function getCreatedAt(): DateTime { return $this->created_at; } diff --git a/tests/Doctrine/Tests/Models/DDC1590/DDC1590User.php b/tests/Doctrine/Tests/Models/DDC1590/DDC1590User.php index 436ab0d54b3..bd04239124a 100644 --- a/tests/Doctrine/Tests/Models/DDC1590/DDC1590User.php +++ b/tests/Doctrine/Tests/Models/DDC1590/DDC1590User.php @@ -1,8 +1,8 @@ street; } - public function setStreet($street) + public function setStreet($street): void { $this->street = $street; } @@ -35,7 +37,7 @@ public function getUser() return $this->user; } - public function setUser(User $user) + public function setUser(User $user): void { if ($this->user !== $user) { $this->user = $user; diff --git a/tests/Doctrine/Tests/Models/DDC2372/DDC2372Admin.php b/tests/Doctrine/Tests/Models/DDC2372/DDC2372Admin.php index ca620513ef6..e1070469233 100644 --- a/tests/Doctrine/Tests/Models/DDC2372/DDC2372Admin.php +++ b/tests/Doctrine/Tests/Models/DDC2372/DDC2372Admin.php @@ -1,5 +1,7 @@ name; } - public function setName($name) + public function setName($name): void { $this->name = $name; } diff --git a/tests/Doctrine/Tests/Models/DDC2372/Traits/DDC2372AddressTrait.php b/tests/Doctrine/Tests/Models/DDC2372/Traits/DDC2372AddressTrait.php index 2253f25812c..34891e8b6d3 100644 --- a/tests/Doctrine/Tests/Models/DDC2372/Traits/DDC2372AddressTrait.php +++ b/tests/Doctrine/Tests/Models/DDC2372/Traits/DDC2372AddressTrait.php @@ -1,5 +1,7 @@ address; } - public function setAddress(Address $address) + public function setAddress(Address $address): void { if ($this->address !== $address) { $this->address = $address; diff --git a/tests/Doctrine/Tests/Models/DDC2504/DDC2504ChildClass.php b/tests/Doctrine/Tests/Models/DDC2504/DDC2504ChildClass.php index a43de5bbfe7..00bed85d37c 100644 --- a/tests/Doctrine/Tests/Models/DDC2504/DDC2504ChildClass.php +++ b/tests/Doctrine/Tests/Models/DDC2504/DDC2504ChildClass.php @@ -1,5 +1,7 @@ setAssociationOverride('groups', [ - 'inversedBy' => 'admins' - ] - ); + $metadata->setAssociationOverride('groups', ['inversedBy' => 'admins']); } } diff --git a/tests/Doctrine/Tests/Models/DDC3579/DDC3579Group.php b/tests/Doctrine/Tests/Models/DDC3579/DDC3579Group.php index 821c06b57ce..f9f92527b80 100644 --- a/tests/Doctrine/Tests/Models/DDC3579/DDC3579Group.php +++ b/tests/Doctrine/Tests/Models/DDC3579/DDC3579Group.php @@ -1,5 +1,7 @@ name = $name; + $this->name = $name; $this->users = new ArrayCollection(); } - /** - * @param string $name - */ - public function setName($name) + public function setName(string $name): void { $this->name = $name; } - /** - * @return string - */ - public function getName() + public function getName(): string { return $this->name; } - /** - * @param DDC3579Admin $admin - */ - public function addAdmin(DDC3579Admin $admin) + public function addAdmin(DDC3579Admin $admin): void { $this->admins[] = $admin; } - /** - * @return ArrayCollection - */ - public function getAdmins() + public function getAdmins(): ArrayCollection { return $this->admins; } - } - diff --git a/tests/Doctrine/Tests/Models/DDC3579/DDC3579User.php b/tests/Doctrine/Tests/Models/DDC3579/DDC3579User.php index 000b977f628..818a21efd45 100644 --- a/tests/Doctrine/Tests/Models/DDC3579/DDC3579User.php +++ b/tests/Doctrine/Tests/Models/DDC3579/DDC3579User.php @@ -1,15 +1,17 @@ name = $name; - $this->groups = new ArrayCollection; + $this->name = $name; + $this->groups = new ArrayCollection(); } - /** - * @return integer - */ - public function getId() + public function getId(): int { return $this->id; } - /** - * @return string - */ - public function getName() + public function getName(): string { return $this->name; } - /** - * @param string $name - */ - public function setName($name) + public function setName(string $name): void { $this->name = $name; } - /** - * @param DDC3579Group $group - */ - public function addGroup(DDC3579Group $group) + public function addGroup(DDC3579Group $group): void { $this->groups->add($group); $group->addUser($this); } - /** - * @return ArrayCollection - */ - public function getGroups() + public function getGroups(): ArrayCollection { return $this->groups; } - public static function loadMetadata($metadata) + public static function loadMetadata($metadata): void { $metadata->isMappedSuperclass = true; $metadata->mapField( [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - 'columnName' => 'user_id', - 'length' => 150, + '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, + 'fieldName' => 'name', + 'type' => 'string', + 'columnName' => 'user_name', + 'nullable' => true, + 'unique' => false, + 'length' => 250, ] ); $metadata->mapManyToMany( [ - 'fieldName' => 'groups', - 'targetEntity' => 'DDC3579Group' + 'fieldName' => 'groups', + 'targetEntity' => 'DDC3579Group', ] ); - $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadataInfo::GENERATOR_TYPE_AUTO); + $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); } } diff --git a/tests/Doctrine/Tests/Models/DDC3597/DDC3597Image.php b/tests/Doctrine/Tests/Models/DDC3597/DDC3597Image.php index 5d1acfeb6ad..dbed620a68e 100644 --- a/tests/Doctrine/Tests/Models/DDC3597/DDC3597Image.php +++ b/tests/Doctrine/Tests/Models/DDC3597/DDC3597Image.php @@ -1,5 +1,7 @@ * @Entity */ -class DDC3597Image extends DDC3597Media { - +class DDC3597Image extends DDC3597Media +{ /** * @var DDC3597Dimension * @Embedded(class = "Doctrine\Tests\Models\DDC3597\Embeddable\DDC3597Dimension", columnPrefix = false) */ private $dimension; - /** - * @param string $distributionHash - */ - function __construct($distributionHash) { + function __construct(string $distributionHash) + { parent::__construct($distributionHash); $this->dimension = new DDC3597Dimension(); } - /** - * @return DDC3597Dimension - */ - public function getDimension() { + public function getDimension(): DDC3597Dimension + { return $this->dimension; } } diff --git a/tests/Doctrine/Tests/Models/DDC3597/DDC3597Media.php b/tests/Doctrine/Tests/Models/DDC3597/DDC3597Media.php index c285b3c40e6..fba27c689fc 100644 --- a/tests/Doctrine/Tests/Models/DDC3597/DDC3597Media.php +++ b/tests/Doctrine/Tests/Models/DDC3597/DDC3597Media.php @@ -1,25 +1,24 @@ * @Entity */ -abstract class DDC3597Media extends DDC3597Root { - +abstract class DDC3597Media extends DDC3597Root +{ /** * @var string - * * @Column */ private $distributionHash; /** - * @var integer - * + * @var int * @Column */ private $size = 0; @@ -30,45 +29,33 @@ abstract class DDC3597Media extends DDC3597Root { */ private $format; - function __construct($distributionHash) { + function __construct($distributionHash) + { $this->distributionHash = $distributionHash; } - /** - * @return string - */ - public function getDistributionHash() { + public function getDistributionHash(): string + { return $this->distributionHash; } - /** - * @return int - */ - public function getSize() { + public function getSize(): int + { return $this->size; } - /** - * @param int $size - */ - public function setSize($size) { + public function setSize(int $size): void + { $this->size = $size; } - /** - * @return string - */ - public function getFormat() { + public function getFormat(): string + { return $this->format; } - /** - * @param string $format - */ - public function setFormat($format) { + public function setFormat(string $format): void + { $this->format = $format; } - - - } diff --git a/tests/Doctrine/Tests/Models/DDC3597/DDC3597Root.php b/tests/Doctrine/Tests/Models/DDC3597/DDC3597Root.php index 3bdb67f13d7..93da278efa6 100644 --- a/tests/Doctrine/Tests/Models/DDC3597/DDC3597Root.php +++ b/tests/Doctrine/Tests/Models/DDC3597/DDC3597Root.php @@ -1,23 +1,25 @@ updatedAt = $this->createdAt = new \DateTime(); + public function _prePersist(): void + { + $this->updatedAt = $this->createdAt = new DateTime(); } /** @@ -50,29 +53,23 @@ public function _prePersist() { * * @PreUpdate */ - public function _preUpdate() { - $this->updatedAt = new \DateTime(); + public function _preUpdate(): void + { + $this->updatedAt = new DateTime(); } - /** - * @return int - */ - public function getId() { - return (int)$this->id; + public function getId(): int + { + return (int) $this->id; } - - /** - * @return \DateTime - */ - public function getCreatedAt() { + public function getCreatedAt(): DateTime + { return $this->createdAt; } - /** - * @return \DateTime - */ - public function getUpdatedAt() { + public function getUpdatedAt(): DateTime + { return $this->updatedAt; } } diff --git a/tests/Doctrine/Tests/Models/DDC3597/Embeddable/DDC3597Dimension.php b/tests/Doctrine/Tests/Models/DDC3597/Embeddable/DDC3597Dimension.php index 5bff5b54079..fac422ad97c 100644 --- a/tests/Doctrine/Tests/Models/DDC3597/Embeddable/DDC3597Dimension.php +++ b/tests/Doctrine/Tests/Models/DDC3597/Embeddable/DDC3597Dimension.php @@ -1,5 +1,7 @@ setWidth($width); $this->setHeight($height); } - /** - * @return int - */ - public function getWidth() { + public function getWidth(): int + { return $this->width; } - /** - * @param int $width - */ - public function setWidth($width) { - $this->width = (int)$width; + public function setWidth(int $width): void + { + $this->width = (int) $width; } - /** - * @return int - */ - public function getHeight() { + public function getHeight(): int + { return $this->height; } - /** - * @param int $height - */ - public function setHeight($height) { - $this->height = (int)$height; + public function setHeight(int $height): void + { + $this->height = (int) $height; } } diff --git a/tests/Doctrine/Tests/Models/DDC3699/DDC3699Child.php b/tests/Doctrine/Tests/Models/DDC3699/DDC3699Child.php index dc2ccfddde1..52939eadf14 100644 --- a/tests/Doctrine/Tests/Models/DDC3699/DDC3699Child.php +++ b/tests/Doctrine/Tests/Models/DDC3699/DDC3699Child.php @@ -1,5 +1,7 @@ - */ class DDC3711EntityA { - /** - * @var int - */ + /** @var int */ private $id1; - /** - * @var int - */ + /** @var int */ private $id2; - /** - * @var ArrayCollection - */ + /** @var ArrayCollection */ private $entityB; /** @@ -36,7 +28,7 @@ public function getId1() /** * @param mixed $id1 */ - public function setId1($id1) + public function setId1($id1): void { $this->id1 = $id1; } @@ -52,25 +44,17 @@ public function getId2() /** * @param mixed $id2 */ - public function setId2($id2) + public function setId2($id2): void { $this->id2 = $id2; } - /** - * @return ArrayCollection - */ - public function getEntityB() + public function getEntityB(): ArrayCollection { return $this->entityB; } - /** - * @param ArrayCollection $entityB - * - * @return DDC3711EntityA - */ - public function addEntityB($entityB) + public function addEntityB(ArrayCollection $entityB): DDC3711EntityA { $this->entityB[] = $entityB; diff --git a/tests/Doctrine/Tests/Models/DDC3711/DDC3711EntityB.php b/tests/Doctrine/Tests/Models/DDC3711/DDC3711EntityB.php index 48c4fd8602d..cdca9cd2fe4 100644 --- a/tests/Doctrine/Tests/Models/DDC3711/DDC3711EntityB.php +++ b/tests/Doctrine/Tests/Models/DDC3711/DDC3711EntityB.php @@ -1,76 +1,49 @@ - */ class DDC3711EntityB { - /** - * @var int - */ + /** @var int */ private $id1; - /** - * @var int - */ + /** @var int */ private $id2; - /** - * @var ArrayCollection - */ + /** @var ArrayCollection */ private $entityA; - /** - * @return int - */ - public function getId1() + public function getId1(): int { return $this->id1; } - /** - * @param int $id1 - */ - public function setId1($id1) + public function setId1(int $id1): void { $this->id1 = $id1; } - /** - * @return int - */ - public function getId2() + public function getId2(): int { return $this->id2; } - /** - * @param int $id2 - */ - public function setId2($id2) + public function setId2(int $id2): void { $this->id2 = $id2; } - /** - * @return ArrayCollection - */ - public function getEntityA() + public function getEntityA(): ArrayCollection { return $this->entityA; } - /** - * @param ArrayCollection $entityA - */ - public function addEntityA($entityA) + public function addEntityA(ArrayCollection $entityA): void { $this->entityA[] = $entityA; } - } diff --git a/tests/Doctrine/Tests/Models/DDC3899/DDC3899Contract.php b/tests/Doctrine/Tests/Models/DDC3899/DDC3899Contract.php index ddccd8c9a48..43275cde794 100644 --- a/tests/Doctrine/Tests/Models/DDC3899/DDC3899Contract.php +++ b/tests/Doctrine/Tests/Models/DDC3899/DDC3899Contract.php @@ -1,5 +1,7 @@ members = new ArrayCollection(); } - public static function loadMetadata(ClassMetadata $metadata) + public static function loadMetadata(ClassMetadata $metadata): void { $metadata->mapField([ 'id' => true, diff --git a/tests/Doctrine/Tests/Models/DDC5934/DDC5934Contract.php b/tests/Doctrine/Tests/Models/DDC5934/DDC5934Contract.php index e26c4d66501..88de1db620b 100644 --- a/tests/Doctrine/Tests/Models/DDC5934/DDC5934Contract.php +++ b/tests/Doctrine/Tests/Models/DDC5934/DDC5934Contract.php @@ -1,11 +1,13 @@ 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..5b1dbb6ffea 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', + 'fieldName' => 'serialNumber', + 'type' => 'string', ] ); } - } diff --git a/tests/Doctrine/Tests/Models/DDC869/DDC869CreditCardPayment.php b/tests/Doctrine/Tests/Models/DDC869/DDC869CreditCardPayment.php index 6f314e31889..0e070c9b67e 100644 --- a/tests/Doctrine/Tests/Models/DDC869/DDC869CreditCardPayment.php +++ b/tests/Doctrine/Tests/Models/DDC869/DDC869CreditCardPayment.php @@ -1,24 +1,26 @@ mapField( [ - 'fieldName' => 'creditCardNumber', - 'type' => 'string', + 'fieldName' => 'creditCardNumber', + 'type' => 'string', ] ); } - } diff --git a/tests/Doctrine/Tests/Models/DDC869/DDC869Payment.php b/tests/Doctrine/Tests/Models/DDC869/DDC869Payment.php index 992c53ae27a..2b578ebaddb 100644 --- a/tests/Doctrine/Tests/Models/DDC869/DDC869Payment.php +++ b/tests/Doctrine/Tests/Models/DDC869/DDC869Payment.php @@ -1,13 +1,16 @@ mapField( [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - 'columnName' => 'id', + 'id' => true, + 'fieldName' => 'id', + 'type' => 'integer', + 'columnName' => 'id', ] ); $metadata->mapField( [ - 'fieldName' => 'value', - 'type' => 'float', + 'fieldName' => 'value', + 'type' => 'float', ] ); $metadata->isMappedSuperclass = true; $metadata->setCustomRepositoryClass(DDC869PaymentRepository::class); - $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadataInfo::GENERATOR_TYPE_AUTO); + $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); } - } diff --git a/tests/Doctrine/Tests/Models/DDC869/DDC869PaymentRepository.php b/tests/Doctrine/Tests/Models/DDC869/DDC869PaymentRepository.php index 3c11b154bce..72340a3447c 100644 --- a/tests/Doctrine/Tests/Models/DDC869/DDC869PaymentRepository.php +++ b/tests/Doctrine/Tests/Models/DDC869/DDC869PaymentRepository.php @@ -1,18 +1,17 @@ mapField( [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - 'columnName' => 'id', + 'id' => true, + 'fieldName' => 'id', + 'type' => 'integer', + 'columnName' => 'id', ] ); - $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadataInfo::GENERATOR_TYPE_AUTO); + $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); } - } diff --git a/tests/Doctrine/Tests/Models/DDC889/DDC889Entity.php b/tests/Doctrine/Tests/Models/DDC889/DDC889Entity.php index 43884435fa7..e901437c244 100644 --- a/tests/Doctrine/Tests/Models/DDC889/DDC889Entity.php +++ b/tests/Doctrine/Tests/Models/DDC889/DDC889Entity.php @@ -1,15 +1,17 @@ mapField( - [ - 'fieldName' => 'name', - ] + ['fieldName' => 'name'] ); $metadata->isMappedSuperclass = true; - $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadataInfo::GENERATOR_TYPE_NONE); + $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE); } } diff --git a/tests/Doctrine/Tests/Models/DDC964/DDC964Address.php b/tests/Doctrine/Tests/Models/DDC964/DDC964Address.php index d5aced9222e..6c2dbf73ad7 100644 --- a/tests/Doctrine/Tests/Models/DDC964/DDC964Address.php +++ b/tests/Doctrine/Tests/Models/DDC964/DDC964Address.php @@ -1,5 +1,7 @@ zip = $zip; - $this->country = $country; - $this->city = $city; - $this->street = $street; + $this->zip = $zip; + $this->country = $country; + $this->city = $city; + $this->street = $street; } - /** - * @return int - */ - public function getId() + public function getId(): int { return $this->id; } - /** - * @return string - */ - public function getCountry() + public function getCountry(): string { return $this->country; } - /** - * @param string $country - */ - public function setCountry($country) + public function setCountry(string $country): void { $this->country = $country; } - /** - * @return string - */ - public function getZip() + public function getZip(): string { return $this->zip; } - /** - * @param string $zip - */ - public function setZip($zip) + public function setZip(string $zip): void { $this->zip = $zip; } - /** - * @return string - */ - public function getCity() + public function getCity(): string { return $this->city; } - /** - * @param string $city - */ - public function setCity($city) + public function setCity(string $city): void { $this->city = $city; } - /** - * @return string - */ - public function getStreet() + public function getStreet(): string { return $this->street; } - /** - * @param string $street - */ - public function setStreet($street) + public function setStreet(string $street): void { $this->street = $street; } - } diff --git a/tests/Doctrine/Tests/Models/DDC964/DDC964Admin.php b/tests/Doctrine/Tests/Models/DDC964/DDC964Admin.php index 29ea4dd4e14..5dd77696d22 100644 --- a/tests/Doctrine/Tests/Models/DDC964/DDC964Admin.php +++ b/tests/Doctrine/Tests/Models/DDC964/DDC964Admin.php @@ -1,7 +1,11 @@ setAssociationOverride('address', + $metadata->setAssociationOverride( + 'address', [ - 'joinColumns'=> [ - [ - 'name' => 'adminaddress_id', - 'referencedColumnName' => 'id', - ] - ] + 'joinColumns' => [ + [ + 'name' => 'adminaddress_id', + 'referencedColumnName' => 'id', + ], + ], ] ); - $metadata->setAssociationOverride('groups', + $metadata->setAssociationOverride( + 'groups', [ - 'joinTable' => [ - 'name' => 'ddc964_users_admingroups', - 'joinColumns' => [ - [ - 'name' => 'adminuser_id', - ] + 'joinTable' => [ + 'name' => 'ddc964_users_admingroups', + 'joinColumns' => [ + ['name' => 'adminuser_id'], + ], + 'inverseJoinColumns' => [ + ['name' => 'admingroup_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..2e3f61466e3 100644 --- a/tests/Doctrine/Tests/Models/DDC964/DDC964Group.php +++ b/tests/Doctrine/Tests/Models/DDC964/DDC964Group.php @@ -1,5 +1,7 @@ name = $name; + $this->name = $name; $this->users = new ArrayCollection(); } - /** - * @param string $name - */ - public function setName($name) + public function setName(string $name): void { $this->name = $name; } - /** - * @return string - */ - public function getName() + public function getName(): string { return $this->name; } - /** - * @param DDC964User $user - */ - public function addUser(DDC964User $user) + public function addUser(DDC964User $user): void { $this->users[] = $user; } - /** - * @return ArrayCollection - */ - public function getUsers() + public function getUsers(): ArrayCollection { return $this->users; } - } - diff --git a/tests/Doctrine/Tests/Models/DDC964/DDC964Guest.php b/tests/Doctrine/Tests/Models/DDC964/DDC964Guest.php index 23486b0fd6d..d458bab46e2 100644 --- a/tests/Doctrine/Tests/Models/DDC964/DDC964Guest.php +++ b/tests/Doctrine/Tests/Models/DDC964/DDC964Guest.php @@ -1,7 +1,11 @@ setAttributeOverride('id', [ 'columnName' => 'guest_id', 'type' => 'integer', 'length' => 140, - ] - ); + ]); - $metadata->setAttributeOverride('name', + $metadata->setAttributeOverride( + 'name', [ - 'columnName' => 'guest_name', - 'nullable' => false, - 'unique' => true, - 'length' => 240, + '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 b8f4b4130f8..a6c9d93c106 100644 --- a/tests/Doctrine/Tests/Models/DDC964/DDC964User.php +++ b/tests/Doctrine/Tests/Models/DDC964/DDC964User.php @@ -1,15 +1,17 @@ name = $name; - $this->groups = new ArrayCollection; + $this->name = $name; + $this->groups = new ArrayCollection(); } - /** - * @return int - */ - public function getId() + public function getId(): int { return $this->id; } - /** - * @return string - */ - public function getName() + public function getName(): string { return $this->name; } - /** - * @param string $name - */ - public function setName($name) + public function setName(string $name): void { $this->name = $name; } - /** - * @param DDC964Group $group - */ - public function addGroup(DDC964Group $group) + public function addGroup(DDC964Group $group): void { $this->groups->add($group); $group->addUser($this); } - /** - * @return ArrayCollection - */ - public function getGroups() + public function getGroups(): ArrayCollection { return $this->groups; } - /** - * @return DDC964Address - */ - public function getAddress() + public function getAddress(): DDC964Address { return $this->address; } - /** - * @param DDC964Address $address - */ - public function setAddress(DDC964Address $address) + public function setAddress(DDC964Address $address): void { $this->address = $address; } - public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) + public static function loadMetadata(ClassMetadataInfo $metadata): void { $metadata->isMappedSuperclass = true; $metadata->mapField( [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - 'columnName' => 'user_id', - 'length' => 150, + '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, + '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'], + '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', - ] + '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', + ], + ], ], - 'inverseJoinColumns'=> [ - [ - 'name'=>'group_id', - 'referencedColumnName'=>'id', - ] - ] - ] ] ); - $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadataInfo::GENERATOR_TYPE_AUTO); + $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); } } diff --git a/tests/Doctrine/Tests/Models/DirectoryTree/AbstractContentItem.php b/tests/Doctrine/Tests/Models/DirectoryTree/AbstractContentItem.php index 41798724b20..259f935954a 100644 --- a/tests/Doctrine/Tests/Models/DirectoryTree/AbstractContentItem.php +++ b/tests/Doctrine/Tests/Models/DirectoryTree/AbstractContentItem.php @@ -1,5 +1,7 @@ parentDirectory = $parentDir; } @@ -44,7 +42,7 @@ public function getId() return $this->id; } - public function setName($name) + public function setName($name): void { $this->name = $name; } @@ -59,18 +57,12 @@ public function getParent() return $this->parentDirectory; } - /** - * @return bool - */ - public function getNodeIsLoaded() + public function getNodeIsLoaded(): bool { return $this->nodeIsLoaded; } - /** - * @param bool $nodeIsLoaded - */ - public function setNodeIsLoaded($nodeIsLoaded) + public function setNodeIsLoaded(bool $nodeIsLoaded): void { $this->nodeIsLoaded = (bool) $nodeIsLoaded; } diff --git a/tests/Doctrine/Tests/Models/DirectoryTree/Directory.php b/tests/Doctrine/Tests/Models/DirectoryTree/Directory.php index cb3729974bc..afc333e846b 100644 --- a/tests/Doctrine/Tests/Models/DirectoryTree/Directory.php +++ b/tests/Doctrine/Tests/Models/DirectoryTree/Directory.php @@ -1,5 +1,7 @@ path = $path; } diff --git a/tests/Doctrine/Tests/Models/DirectoryTree/File.php b/tests/Doctrine/Tests/Models/DirectoryTree/File.php index f6cbace23ca..2b17e20e645 100644 --- a/tests/Doctrine/Tests/Models/DirectoryTree/File.php +++ b/tests/Doctrine/Tests/Models/DirectoryTree/File.php @@ -1,5 +1,7 @@ extension; } - public function setExtension($ext) + public function setExtension($ext): void { $this->extension = $ext; } diff --git a/tests/Doctrine/Tests/Models/ECommerce/ECommerceCart.php b/tests/Doctrine/Tests/Models/ECommerce/ECommerceCart.php index 3d9f6798f1c..92a62d85f18 100644 --- a/tests/Doctrine/Tests/Models/ECommerce/ECommerceCart.php +++ b/tests/Doctrine/Tests/Models/ECommerce/ECommerceCart.php @@ -1,5 +1,7 @@ products = new ArrayCollection; + $this->products = new ArrayCollection(); } - public function getId() { + public function getId() + { return $this->id; } - public function getPayment() { + public function getPayment() + { return $this->payment; } - public function setPayment($payment) { + public function setPayment($payment): void + { $this->payment = $payment; } - public function setCustomer(ECommerceCustomer $customer) { + public function setCustomer(ECommerceCustomer $customer): void + { if ($this->customer !== $customer) { $this->customer = $customer; $customer->setCart($this); } } - public function removeCustomer() { + public function removeCustomer(): void + { if ($this->customer !== null) { - $customer = $this->customer; + $customer = $this->customer; $this->customer = null; $customer->removeCart(); } } - public function getCustomer() { + public function getCustomer() + { return $this->customer; } @@ -81,11 +86,13 @@ public function getProducts() return $this->products; } - public function addProduct(ECommerceProduct $product) { + public function addProduct(ECommerceProduct $product): void + { $this->products[] = $product; } - public function removeProduct(ECommerceProduct $product) { + public function removeProduct(ECommerceProduct $product) + { return $this->products->removeElement($product); } } diff --git a/tests/Doctrine/Tests/Models/ECommerce/ECommerceCategory.php b/tests/Doctrine/Tests/Models/ECommerce/ECommerceCategory.php index a8d8dc6bbb1..861365f12be 100644 --- a/tests/Doctrine/Tests/Models/ECommerce/ECommerceCategory.php +++ b/tests/Doctrine/Tests/Models/ECommerce/ECommerceCategory.php @@ -1,5 +1,7 @@ name; } - public function setName($name) + public function setName($name): void { $this->name = $name; } - public function addProduct(ECommerceProduct $product) + public function addProduct(ECommerceProduct $product): void { - if (!$this->products->contains($product)) { + if (! $this->products->contains($product)) { $this->products[] = $product; $product->addCategory($this); } } - public function removeProduct(ECommerceProduct $product) + public function removeProduct(ECommerceProduct $product): void { $removed = $this->products->removeElement($product); if ($removed) { @@ -83,7 +78,7 @@ public function getProducts() return $this->products; } - private function setParent(ECommerceCategory $parent) + private function setParent(ECommerceCategory $parent): void { $this->parent = $parent; } @@ -98,20 +93,19 @@ public function getParent() return $this->parent; } - public function addChild(ECommerceCategory $child) + public function addChild(ECommerceCategory $child): void { $this->children[] = $child; $child->setParent($this); } /** does not set the owning side. */ - public function brokenAddChild(ECommerceCategory $child) + public function brokenAddChild(ECommerceCategory $child): void { $this->children[] = $child; } - - public function removeChild(ECommerceCategory $child) + public function removeChild(ECommerceCategory $child): void { $removed = $this->children->removeElement($child); if ($removed) { @@ -119,7 +113,7 @@ public function removeChild(ECommerceCategory $child) } } - private function removeParent() + private function removeParent(): void { $this->parent = null; } diff --git a/tests/Doctrine/Tests/Models/ECommerce/ECommerceCustomer.php b/tests/Doctrine/Tests/Models/ECommerce/ECommerceCustomer.php index a5de9e119c2..0d299264491 100644 --- a/tests/Doctrine/Tests/Models/ECommerce/ECommerceCustomer.php +++ b/tests/Doctrine/Tests/Models/ECommerce/ECommerceCustomer.php @@ -1,12 +1,13 @@ id; } - public function getName() { + public function getName() + { return $this->name; } - public function setName($name) { + public function setName($name): void + { $this->name = $name; } - public function setCart(ECommerceCart $cart) + public function setCart(ECommerceCart $cart): void { if ($this->cart !== $cart) { $this->cart = $cart; @@ -60,29 +60,31 @@ public function setCart(ECommerceCart $cart) } /* Does not properly maintain the bidirectional association! */ - public function brokenSetCart(ECommerceCart $cart) { + public function brokenSetCart(ECommerceCart $cart): void + { $this->cart = $cart; } - public function getCart() { + public function getCart() + { return $this->cart; } - public function removeCart() + public function removeCart(): void { if ($this->cart !== null) { - $cart = $this->cart; + $cart = $this->cart; $this->cart = null; $cart->removeCustomer(); } } - public function setMentor(ECommerceCustomer $mentor) + public function setMentor(ECommerceCustomer $mentor): void { $this->mentor = $mentor; } - public function removeMentor() + public function removeMentor(): void { $this->mentor = null; } diff --git a/tests/Doctrine/Tests/Models/ECommerce/ECommerceFeature.php b/tests/Doctrine/Tests/Models/ECommerce/ECommerceFeature.php index 04fc2bed35d..eca5c19bb01 100644 --- a/tests/Doctrine/Tests/Models/ECommerce/ECommerceFeature.php +++ b/tests/Doctrine/Tests/Models/ECommerce/ECommerceFeature.php @@ -1,11 +1,12 @@ id; } - public function getDescription() { + public function getDescription() + { return $this->description; } - public function setDescription($description) { + public function setDescription($description): void + { $this->description = $description; } - public function setProduct(ECommerceProduct $product) { + public function setProduct(ECommerceProduct $product): void + { $this->product = $product; } - public function removeProduct() { + public function removeProduct(): void + { if ($this->product !== null) { - $product = $this->product; + $product = $this->product; $this->product = null; $product->removeFeature($this); } } - public function getProduct() { + public function getProduct() + { return $this->product; } } diff --git a/tests/Doctrine/Tests/Models/ECommerce/ECommerceProduct.php b/tests/Doctrine/Tests/Models/ECommerce/ECommerceProduct.php index ba4f2a53d20..10999ceb796 100644 --- a/tests/Doctrine/Tests/Models/ECommerce/ECommerceProduct.php +++ b/tests/Doctrine/Tests/Models/ECommerce/ECommerceProduct.php @@ -1,5 +1,7 @@ features = new ArrayCollection; - $this->categories = new ArrayCollection; - $this->related = new ArrayCollection; + $this->features = new ArrayCollection(); + $this->categories = new ArrayCollection(); + $this->related = new ArrayCollection(); } public function getId() @@ -75,7 +73,7 @@ public function getName() return $this->name; } - public function setName($name) + public function setName($name): void { $this->name = $name; } @@ -85,12 +83,12 @@ public function getShipping() return $this->shipping; } - public function setShipping(ECommerceShipping $shipping) + public function setShipping(ECommerceShipping $shipping): void { $this->shipping = $shipping; } - public function removeShipping() + public function removeShipping(): void { $this->shipping = null; } @@ -100,14 +98,14 @@ public function getFeatures() return $this->features; } - public function addFeature(ECommerceFeature $feature) + public function addFeature(ECommerceFeature $feature): void { $this->features[] = $feature; $feature->setProduct($this); } /** does not set the owning side */ - public function brokenAddFeature(ECommerceFeature $feature) + public function brokenAddFeature(ECommerceFeature $feature): void { $this->features[] = $feature; } @@ -118,18 +116,19 @@ public function removeFeature(ECommerceFeature $feature) if ($removed) { $feature->removeProduct(); } + return $removed; } - public function addCategory(ECommerceCategory $category) + public function addCategory(ECommerceCategory $category): void { - if (!$this->categories->contains($category)) { + if (! $this->categories->contains($category)) { $this->categories[] = $category; $category->addProduct($this); } } - public function removeCategory(ECommerceCategory $category) + public function removeCategory(ECommerceCategory $category): void { $removed = $this->categories->removeElement($category); if ($removed) { @@ -137,7 +136,7 @@ public function removeCategory(ECommerceCategory $category) } } - public function setCategories($categories) + public function setCategories($categories): void { $this->categories = $categories; } @@ -152,15 +151,15 @@ public function getRelated() return $this->related; } - public function addRelated(ECommerceProduct $related) + public function addRelated(ECommerceProduct $related): void { - if (!$this->related->contains($related)) { + if (! $this->related->contains($related)) { $this->related[] = $related; $related->addRelated($this); } } - public function removeRelated(ECommerceProduct $related) + public function removeRelated(ECommerceProduct $related): void { $removed = $this->related->removeElement($related); if ($removed) { @@ -179,7 +178,7 @@ public function __clone() /** * Testing docblock contents here */ - public function __wakeup() + public function __wakeup(): void { $this->wakeUp = true; } diff --git a/tests/Doctrine/Tests/Models/ECommerce/ECommerceShipping.php b/tests/Doctrine/Tests/Models/ECommerce/ECommerceShipping.php index a0f302cc22f..fdf9505ae53 100644 --- a/tests/Doctrine/Tests/Models/ECommerce/ECommerceShipping.php +++ b/tests/Doctrine/Tests/Models/ECommerce/ECommerceShipping.php @@ -1,12 +1,13 @@ days; } - public function setDays($days) + public function setDays($days): void { $this->days = $days; } diff --git a/tests/Doctrine/Tests/Models/Forum/ForumAdministrator.php b/tests/Doctrine/Tests/Models/Forum/ForumAdministrator.php index 63d08be4a42..3e237659c9a 100644 --- a/tests/Doctrine/Tests/Models/Forum/ForumAdministrator.php +++ b/tests/Doctrine/Tests/Models/Forum/ForumAdministrator.php @@ -1,5 +1,7 @@ id; } } diff --git a/tests/Doctrine/Tests/Models/Forum/ForumEntry.php b/tests/Doctrine/Tests/Models/Forum/ForumEntry.php index efa359b005d..9304d9e2c6c 100644 --- a/tests/Doctrine/Tests/Models/Forum/ForumEntry.php +++ b/tests/Doctrine/Tests/Models/Forum/ForumEntry.php @@ -1,5 +1,7 @@ topic; } } - diff --git a/tests/Doctrine/Tests/Models/Forum/ForumUser.php b/tests/Doctrine/Tests/Models/Forum/ForumUser.php index 3f3b5d9d2fe..3c30eb9fa8f 100644 --- a/tests/Doctrine/Tests/Models/Forum/ForumUser.php +++ b/tests/Doctrine/Tests/Models/Forum/ForumUser.php @@ -1,5 +1,7 @@ id; + public function getId() + { + return $this->id; } - public function getUsername() { - return $this->username; + public function getUsername() + { + return $this->username; } - public function getAvatar() { - return $this->avatar; + public function getAvatar() + { + return $this->avatar; } - public function setAvatar(ForumAvatar $avatar) { - $this->avatar = $avatar; + public function setAvatar(ForumAvatar $avatar): void + { + $this->avatar = $avatar; } } diff --git a/tests/Doctrine/Tests/Models/GH7141/GH7141Article.php b/tests/Doctrine/Tests/Models/GH7141/GH7141Article.php index 5af97c62ef5..f02941feef8 100644 --- a/tests/Doctrine/Tests/Models/GH7141/GH7141Article.php +++ b/tests/Doctrine/Tests/Models/GH7141/GH7141Article.php @@ -1,5 +1,7 @@ value = $value; } diff --git a/tests/Doctrine/Tests/Models/Generic/SerializationModel.php b/tests/Doctrine/Tests/Models/Generic/SerializationModel.php index 19a05cc2848..0422171a525 100644 --- a/tests/Doctrine/Tests/Models/Generic/SerializationModel.php +++ b/tests/Doctrine/Tests/Models/Generic/SerializationModel.php @@ -1,5 +1,7 @@ id = $id; diff --git a/tests/Doctrine/Tests/Models/GeoNames/City.php b/tests/Doctrine/Tests/Models/GeoNames/City.php index 411f4db9126..c715ec6f148 100644 --- a/tests/Doctrine/Tests/Models/GeoNames/City.php +++ b/tests/Doctrine/Tests/Models/GeoNames/City.php @@ -1,5 +1,7 @@ id = $id; diff --git a/tests/Doctrine/Tests/Models/GeoNames/Country.php b/tests/Doctrine/Tests/Models/GeoNames/Country.php index ebde305f805..5126f93d3c4 100644 --- a/tests/Doctrine/Tests/Models/GeoNames/Country.php +++ b/tests/Doctrine/Tests/Models/GeoNames/Country.php @@ -1,5 +1,7 @@ _user = $author; } } diff --git a/tests/Doctrine/Tests/Models/Legacy/LegacyCar.php b/tests/Doctrine/Tests/Models/Legacy/LegacyCar.php index 4b955be914b..483aab6c064 100644 --- a/tests/Doctrine/Tests/Models/Legacy/LegacyCar.php +++ b/tests/Doctrine/Tests/Models/Legacy/LegacyCar.php @@ -1,5 +1,7 @@ _description; } - public function addUser(LegacyUser $user) { + public function addUser(LegacyUser $user): void + { $this->_users[] = $user; } - public function getUsers() { + public function getUsers() + { return $this->_users; } } diff --git a/tests/Doctrine/Tests/Models/Legacy/LegacyUser.php b/tests/Doctrine/Tests/Models/Legacy/LegacyUser.php index 3e3deedb153..b7abdb94d51 100644 --- a/tests/Doctrine/Tests/Models/Legacy/LegacyUser.php +++ b/tests/Doctrine/Tests/Models/Legacy/LegacyUser.php @@ -1,5 +1,7 @@ _articles = new ArrayCollection; - $this->_references = new ArrayCollection; - $this->_cars = new ArrayCollection; + + public function __construct() + { + $this->_articles = new ArrayCollection(); + $this->_references = new ArrayCollection(); + $this->_cars = new ArrayCollection(); } - public function getId() { + public function getId() + { return $this->_id; } - public function getUsername() { + public function getUsername() + { return $this->_username; } - public function addArticle(LegacyArticle $article) { + public function addArticle(LegacyArticle $article): void + { $this->_articles[] = $article; $article->setAuthor($this); } - public function addReference($reference) + public function addReference($reference): void { $this->_references[] = $reference; } @@ -69,12 +68,14 @@ public function references() return $this->_references; } - public function addCar(LegacyCar $car) { + public function addCar(LegacyCar $car): void + { $this->_cars[] = $car; $car->addUser($this); } - public function getCars() { + public function getCars() + { return $this->_cars; } } diff --git a/tests/Doctrine/Tests/Models/Legacy/LegacyUserReference.php b/tests/Doctrine/Tests/Models/Legacy/LegacyUserReference.php index 8dc20db2323..5e49d6149cc 100644 --- a/tests/Doctrine/Tests/Models/Legacy/LegacyUserReference.php +++ b/tests/Doctrine/Tests/Models/Legacy/LegacyUserReference.php @@ -1,7 +1,11 @@ addReference($this); $target->addReference($this); - $this->_source = $source; - $this->_target = $target; + $this->_source = $source; + $this->_target = $target; $this->_description = $description; - $this->_created = new \DateTime("now"); + $this->_created = new DateTime('now'); } public function source() @@ -53,7 +53,7 @@ public function target() return $this->_target; } - public function setDescription($desc) + public function setDescription($desc): void { $this->_description = $desc; } diff --git a/tests/Doctrine/Tests/Models/ManyToManyPersister/ChildClass.php b/tests/Doctrine/Tests/Models/ManyToManyPersister/ChildClass.php index 1733cd456ae..69a9f1b857c 100644 --- a/tests/Doctrine/Tests/Models/ManyToManyPersister/ChildClass.php +++ b/tests/Doctrine/Tests/Models/ManyToManyPersister/ChildClass.php @@ -1,5 +1,7 @@ */ diff --git a/tests/Doctrine/Tests/Models/ManyToManyPersister/OtherParentClass.php b/tests/Doctrine/Tests/Models/ManyToManyPersister/OtherParentClass.php index 04e27e616d2..973bfc113d2 100644 --- a/tests/Doctrine/Tests/Models/ManyToManyPersister/OtherParentClass.php +++ b/tests/Doctrine/Tests/Models/ManyToManyPersister/OtherParentClass.php @@ -1,5 +1,7 @@ */ diff --git a/tests/Doctrine/Tests/Models/MixedToOneIdentity/CompositeToOneKeyState.php b/tests/Doctrine/Tests/Models/MixedToOneIdentity/CompositeToOneKeyState.php index 09bab229ef6..6393d47712d 100644 --- a/tests/Doctrine/Tests/Models/MixedToOneIdentity/CompositeToOneKeyState.php +++ b/tests/Doctrine/Tests/Models/MixedToOneIdentity/CompositeToOneKeyState.php @@ -1,5 +1,7 @@ name = $name; } - public function getId() { + public function getId() + { return $this->id; } - public function getName() { + public function getName() + { return $this->name; } } diff --git a/tests/Doctrine/Tests/Models/Navigation/NavPhotos.php b/tests/Doctrine/Tests/Models/Navigation/NavPhotos.php index 173aaa3fb01..b76ab52375d 100644 --- a/tests/Doctrine/Tests/Models/Navigation/NavPhotos.php +++ b/tests/Doctrine/Tests/Models/Navigation/NavPhotos.php @@ -1,5 +1,7 @@ poi = $poi; + function __construct($poi, $file) + { + $this->poi = $poi; $this->file = $file; } - public function getId() { + public function getId() + { return $this->id; } - public function getPointOfInterest() { + public function getPointOfInterest() + { return $this->poi; } - public function getFile() { + public function getFile() + { return $this->file; } } diff --git a/tests/Doctrine/Tests/Models/Navigation/NavPointOfInterest.php b/tests/Doctrine/Tests/Models/Navigation/NavPointOfInterest.php index 33d0f70bdb2..e549b4ab4a3 100644 --- a/tests/Doctrine/Tests/Models/Navigation/NavPointOfInterest.php +++ b/tests/Doctrine/Tests/Models/Navigation/NavPointOfInterest.php @@ -1,7 +1,11 @@ lat = $lat; - $this->long = $long; - $this->name = $name; - $this->country = $country; - $this->visitors = new \Doctrine\Common\Collections\ArrayCollection; + $this->lat = $lat; + $this->long = $long; + $this->name = $name; + $this->country = $country; + $this->visitors = new ArrayCollection(); } - public function getLong() { + public function getLong() + { return $this->long; } - public function getLat() { + public function getLat() + { return $this->lat; } - public function getName() { + public function getName() + { return $this->name; } - public function getCountry() { + public function getCountry() + { return $this->country; } - public function addVisitor(NavUser $user) + public function addVisitor(NavUser $user): void { $this->visitors[] = $user; } diff --git a/tests/Doctrine/Tests/Models/Navigation/NavTour.php b/tests/Doctrine/Tests/Models/Navigation/NavTour.php index d54bd2283cc..e8e638db3b8 100644 --- a/tests/Doctrine/Tests/Models/Navigation/NavTour.php +++ b/tests/Doctrine/Tests/Models/Navigation/NavTour.php @@ -1,7 +1,11 @@ name = $name; - $this->pois = new \Doctrine\Common\Collections\ArrayCollection; + $this->pois = new ArrayCollection(); } - public function addPointOfInterest(NavPointOfInterest $poi) + public function addPointOfInterest(NavPointOfInterest $poi): void { $this->pois[] = $poi; } diff --git a/tests/Doctrine/Tests/Models/Navigation/NavUser.php b/tests/Doctrine/Tests/Models/Navigation/NavUser.php index 42117e46b89..a85c7d8ceeb 100644 --- a/tests/Doctrine/Tests/Models/Navigation/NavUser.php +++ b/tests/Doctrine/Tests/Models/Navigation/NavUser.php @@ -1,5 +1,7 @@ name = $name; } } - diff --git a/tests/Doctrine/Tests/Models/NonPublicSchemaJoins/User.php b/tests/Doctrine/Tests/Models/NonPublicSchemaJoins/User.php index be80cea33c4..021f09bf94f 100644 --- a/tests/Doctrine/Tests/Models/NonPublicSchemaJoins/User.php +++ b/tests/Doctrine/Tests/Models/NonPublicSchemaJoins/User.php @@ -1,5 +1,7 @@ user !== $user) { $this->user = $user; $user->setAddress($this); } } - public function getId() { return $this->id; @@ -53,5 +51,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..6aaf7c9ab06 100644 --- a/tests/Doctrine/Tests/Models/Quote/City.php +++ b/tests/Doctrine/Tests/Models/Quote/City.php @@ -1,5 +1,7 @@ name = $name; - $this->parent = $parent; + $this->name = $name; + $this->parent = $parent; } } diff --git a/tests/Doctrine/Tests/Models/Quote/NumericEntity.php b/tests/Doctrine/Tests/Models/Quote/NumericEntity.php index 45ed7a901c5..0fa938a32c4 100644 --- a/tests/Doctrine/Tests/Models/Quote/NumericEntity.php +++ b/tests/Doctrine/Tests/Models/Quote/NumericEntity.php @@ -1,5 +1,7 @@ value = $value; } - } diff --git a/tests/Doctrine/Tests/Models/Quote/Phone.php b/tests/Doctrine/Tests/Models/Quote/Phone.php index 3d4475372c1..950c9d757d0 100644 --- a/tests/Doctrine/Tests/Models/Quote/Phone.php +++ b/tests/Doctrine/Tests/Models/Quote/Phone.php @@ -1,5 +1,7 @@ phones = new ArrayCollection; - $this->groups = new ArrayCollection; + $this->phones = new ArrayCollection(); + $this->groups = new ArrayCollection(); } - public function getPhones() { return $this->phones; @@ -74,7 +71,8 @@ public function getGroups() return $this->groups; } - public function setAddress(Address $address) { + public function setAddress(Address $address): void + { if ($this->address !== $address) { $this->address = $address; $address->setUser($this); diff --git a/tests/Doctrine/Tests/Models/Reflection/AbstractEmbeddable.php b/tests/Doctrine/Tests/Models/Reflection/AbstractEmbeddable.php index 2fecb4613e4..adf2cfc82eb 100644 --- a/tests/Doctrine/Tests/Models/Reflection/AbstractEmbeddable.php +++ b/tests/Doctrine/Tests/Models/Reflection/AbstractEmbeddable.php @@ -1,5 +1,7 @@ id; } - public function addStock(Stock $stock) + public function addStock(Stock $stock): void { $this->stocks[$stock->getSymbol()] = $stock; } diff --git a/tests/Doctrine/Tests/Models/StockExchange/Market.php b/tests/Doctrine/Tests/Models/StockExchange/Market.php index 71e0a0cd727..21c20a08246 100644 --- a/tests/Doctrine/Tests/Models/StockExchange/Market.php +++ b/tests/Doctrine/Tests/Models/StockExchange/Market.php @@ -1,5 +1,7 @@ name = $name; + $this->name = $name; $this->stocks = new ArrayCollection(); } @@ -44,7 +46,7 @@ public function getName() return $this->name; } - public function addStock(Stock $stock) + public function addStock(Stock $stock): void { $this->stocks[$stock->getSymbol()] = $stock; } diff --git a/tests/Doctrine/Tests/Models/StockExchange/Stock.php b/tests/Doctrine/Tests/Models/StockExchange/Stock.php index 25a938721fb..0bd3d13e9e2 100644 --- a/tests/Doctrine/Tests/Models/StockExchange/Stock.php +++ b/tests/Doctrine/Tests/Models/StockExchange/Stock.php @@ -1,5 +1,7 @@ symbol = $symbol; - $this->price = $initialOfferingPrice; + $this->price = $initialOfferingPrice; $this->market = $market; $market->addStock($this); } diff --git a/tests/Doctrine/Tests/Models/Taxi/Car.php b/tests/Doctrine/Tests/Models/Taxi/Car.php index 03cc74c96b8..f58d82f785c 100644 --- a/tests/Doctrine/Tests/Models/Taxi/Car.php +++ b/tests/Doctrine/Tests/Models/Taxi/Car.php @@ -1,5 +1,7 @@ brand; } - public function setBrand($brand) + public function setBrand($brand): void { $this->brand = $brand; } - public function setModel($model) + public function setModel($model): void { $this->model = $model; } diff --git a/tests/Doctrine/Tests/Models/Taxi/Driver.php b/tests/Doctrine/Tests/Models/Taxi/Driver.php index ff0cb41a41e..550474eed3c 100644 --- a/tests/Doctrine/Tests/Models/Taxi/Driver.php +++ b/tests/Doctrine/Tests/Models/Taxi/Driver.php @@ -1,5 +1,7 @@ id; } - public function setName($name) + public function setName($name): void { $this->name = $name; } diff --git a/tests/Doctrine/Tests/Models/Taxi/PaidRide.php b/tests/Doctrine/Tests/Models/Taxi/PaidRide.php index 040e3917ec6..018c171f3d7 100644 --- a/tests/Doctrine/Tests/Models/Taxi/PaidRide.php +++ b/tests/Doctrine/Tests/Models/Taxi/PaidRide.php @@ -1,5 +1,7 @@ driver = $driver; - $this->car = $car; + $this->car = $car; } - public function setFare($fare) + public function setFare($fare): void { $this->fare = $fare; } diff --git a/tests/Doctrine/Tests/Models/Taxi/Ride.php b/tests/Doctrine/Tests/Models/Taxi/Ride.php index e90a382172a..40f5cc2c2fc 100644 --- a/tests/Doctrine/Tests/Models/Taxi/Ride.php +++ b/tests/Doctrine/Tests/Models/Taxi/Ride.php @@ -1,5 +1,7 @@ driver = $driver; - $this->car = $car; + $this->car = $car; } } diff --git a/tests/Doctrine/Tests/Models/Tweet/Tweet.php b/tests/Doctrine/Tests/Models/Tweet/Tweet.php index 5455452c2b6..2102a62ffca 100644 --- a/tests/Doctrine/Tests/Models/Tweet/Tweet.php +++ b/tests/Doctrine/Tests/Models/Tweet/Tweet.php @@ -1,5 +1,7 @@ author = $user; } diff --git a/tests/Doctrine/Tests/Models/Tweet/User.php b/tests/Doctrine/Tests/Models/Tweet/User.php index 4efd6193e4f..490748e8786 100644 --- a/tests/Doctrine/Tests/Models/Tweet/User.php +++ b/tests/Doctrine/Tests/Models/Tweet/User.php @@ -1,5 +1,7 @@ userLists = new ArrayCollection(); } - public function addTweet(Tweet $tweet) + public function addTweet(Tweet $tweet): void { $tweet->setAuthor($this); $this->tweets->add($tweet); } - public function addUserList(UserList $userList) + public function addUserList(UserList $userList): void { $userList->owner = $this; $this->userLists->add($userList); diff --git a/tests/Doctrine/Tests/Models/Tweet/UserList.php b/tests/Doctrine/Tests/Models/Tweet/UserList.php index 0f20f94b938..948912fd202 100644 --- a/tests/Doctrine/Tests/Models/Tweet/UserList.php +++ b/tests/Doctrine/Tests/Models/Tweet/UserList.php @@ -1,5 +1,7 @@ - * * @Entity * @Table(name="first_entity") */ @@ -17,9 +17,7 @@ class FirstRelatedEntity */ public $secondEntity; - /** - * @Column(name="name") - */ + /** @Column(name="name") */ public $name; /** diff --git a/tests/Doctrine/Tests/Models/VersionedOneToOne/SecondRelatedEntity.php b/tests/Doctrine/Tests/Models/VersionedOneToOne/SecondRelatedEntity.php index cb5dcf66c67..b89463645b4 100644 --- a/tests/Doctrine/Tests/Models/VersionedOneToOne/SecondRelatedEntity.php +++ b/tests/Doctrine/Tests/Models/VersionedOneToOne/SecondRelatedEntity.php @@ -1,10 +1,10 @@ - * * @Entity * @Table(name="second_entity") */ @@ -17,9 +17,7 @@ class SecondRelatedEntity */ public $id; - /** - * @Column(name="name") - */ + /** @Column(name="name") */ public $name; /** diff --git a/tests/Doctrine/Tests/ORM/Cache/AbstractRegionTest.php b/tests/Doctrine/Tests/ORM/Cache/AbstractRegionTest.php index 4126e316d04..e8480ceeeb5 100644 --- a/tests/Doctrine/Tests/ORM/Cache/AbstractRegionTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/AbstractRegionTest.php @@ -1,28 +1,27 @@ region = $this->createRegion(); } - /** - * @return \Doctrine\ORM\Cache\Region - */ - protected abstract function createRegion(); + abstract protected function createRegion(): Region; - static public function dataProviderCacheValues() + public static function dataProviderCacheValues() { return [ - [new CacheKeyMock('key.1'), new CacheEntryMock(['id'=>1, 'name' => 'bar'])], - [new CacheKeyMock('key.2'), new CacheEntryMock(['id'=>2, 'name' => 'foo'])], + [new CacheKeyMock('key.1'), new CacheEntryMock(['id' => 1, 'name' => 'bar'])], + [new CacheKeyMock('key.2'), new CacheEntryMock(['id' => 2, 'name' => 'foo'])], ]; } /** * @dataProvider dataProviderCacheValues */ - public function testPutGetContainsEvict($key, $value) + public function testPutGetContainsEvict($key, $value): void { $this->assertFalse($this->region->contains($key)); @@ -63,7 +59,7 @@ public function testPutGetContainsEvict($key, $value) $this->assertFalse($this->region->contains($key)); } - public function testEvictAll() + public function testEvictAll(): void { $key1 = new CacheKeyMock('key.1'); $key2 = new CacheKeyMock('key.2'); diff --git a/tests/Doctrine/Tests/ORM/Cache/CacheConfigTest.php b/tests/Doctrine/Tests/ORM/Cache/CacheConfigTest.php index e77eb8f3b37..d160e544553 100644 --- a/tests/Doctrine/Tests/ORM/Cache/CacheConfigTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/CacheConfigTest.php @@ -1,38 +1,34 @@ config = new CacheConfiguration(); } - public function testSetGetRegionLifetime() + public function testSetGetRegionLifetime(): void { $config = $this->config->getRegionsConfiguration(); @@ -45,7 +41,7 @@ public function testSetGetRegionLifetime() $this->assertEquals(222, $config->getLifetime('foo_region')); } - public function testSetGetCacheLogger() + public function testSetGetCacheLogger(): void { $logger = $this->createMock(CacheLogger::class); @@ -56,7 +52,7 @@ public function testSetGetCacheLogger() $this->assertEquals($logger, $this->config->getCacheLogger()); } - public function testSetGetCacheFactory() + public function testSetGetCacheFactory(): void { $factory = $this->createMock(CacheFactory::class); @@ -67,7 +63,7 @@ public function testSetGetCacheFactory() $this->assertEquals($factory, $this->config->getCacheFactory()); } - public function testSetGetQueryValidator() + public function testSetGetQueryValidator(): void { $factory = $this->createMock(CacheFactory::class); $factory->method('getTimestampRegion')->willReturn($this->createMock(TimestampRegion::class)); diff --git a/tests/Doctrine/Tests/ORM/Cache/CacheKeyTest.php b/tests/Doctrine/Tests/ORM/Cache/CacheKeyTest.php index 63c86d7f1af..7e30ca5aa74 100644 --- a/tests/Doctrine/Tests/ORM/Cache/CacheKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/CacheKeyTest.php @@ -1,9 +1,11 @@ 1]); - $key2 = new EntityCacheKey('Bar', ['id'=>1]); + $key1 = new EntityCacheKey('Foo', ['id' => 1]); + $key2 = new EntityCacheKey('Bar', ['id' => 1]); $this->assertNotEquals($key1->hash, $key2->hash); } - public function testEntityCacheKeyIdentifierType() + public function testEntityCacheKeyIdentifierType(): void { - $key1 = new EntityCacheKey('Foo', ['id'=>1]); - $key2 = new EntityCacheKey('Foo', ['id'=>'1']); + $key1 = new EntityCacheKey('Foo', ['id' => 1]); + $key2 = new EntityCacheKey('Foo', ['id' => '1']); $this->assertEquals($key1->hash, $key2->hash); } - public function testEntityCacheKeyIdentifierOrder() + public function testEntityCacheKeyIdentifierOrder(): void { - $key1 = new EntityCacheKey('Foo', ['foo_bar'=>1, 'bar_foo'=> 2]); - $key2 = new EntityCacheKey('Foo', ['bar_foo'=>2, 'foo_bar'=> 1]); + $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); } - public function testCollectionCacheKeyIdentifierType() + public function testCollectionCacheKeyIdentifierType(): void { - $key1 = new CollectionCacheKey('Foo', 'assoc', ['id'=>1]); - $key2 = new CollectionCacheKey('Foo', 'assoc', ['id'=>'1']); + $key1 = new CollectionCacheKey('Foo', 'assoc', ['id' => 1]); + $key2 = new CollectionCacheKey('Foo', 'assoc', ['id' => '1']); $this->assertEquals($key1->hash, $key2->hash); } - public function testCollectionCacheKeyIdentifierOrder() + public function testCollectionCacheKeyIdentifierOrder(): void { - $key1 = new CollectionCacheKey('Foo', 'assoc', ['foo_bar'=>1, 'bar_foo'=> 2]); - $key2 = new CollectionCacheKey('Foo', 'assoc', ['bar_foo'=>2, 'foo_bar'=> 1]); + $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); } - public function testCollectionCacheKeyIdentifierCollision() + public function testCollectionCacheKeyIdentifierCollision(): void { - $key1 = new CollectionCacheKey('Foo', 'assoc', ['id'=>1]); - $key2 = new CollectionCacheKey('Bar', 'assoc', ['id'=>1]); + $key1 = new CollectionCacheKey('Foo', 'assoc', ['id' => 1]); + $key2 = new CollectionCacheKey('Bar', 'assoc', ['id' => 1]); $this->assertNotEquals($key1->hash, $key2->hash); } - public function testCollectionCacheKeyAssociationCollision() + public function testCollectionCacheKeyAssociationCollision(): void { - $key1 = new CollectionCacheKey('Foo', 'assoc1', ['id'=>1]); - $key2 = new CollectionCacheKey('Foo', 'assoc2', ['id'=>1]); + $key1 = new CollectionCacheKey('Foo', 'assoc1', ['id' => 1]); + $key2 = new CollectionCacheKey('Foo', 'assoc2', ['id' => 1]); $this->assertNotEquals($key1->hash, $key2->hash); } diff --git a/tests/Doctrine/Tests/ORM/Cache/CacheLoggerChainTest.php b/tests/Doctrine/Tests/ORM/Cache/CacheLoggerChainTest.php index 2c54b40071e..49cac36794a 100644 --- a/tests/Doctrine/Tests/ORM/Cache/CacheLoggerChainTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/CacheLoggerChainTest.php @@ -1,31 +1,29 @@ mock = $this->createMock(CacheLogger::class); } - public function testGetAndSetLogger() + public function testGetAndSetLogger(): void { $this->assertEmpty($this->logger->getLoggers()); @@ -45,7 +43,7 @@ public function testGetAndSetLogger() $this->assertEquals(['mock' => $this->mock], $this->logger->getLoggers()); } - public function testEntityCacheChain() + public function testEntityCacheChain(): void { $name = 'my_entity_region'; $key = new EntityCacheKey(State::class, ['id' => 1]); @@ -69,7 +67,7 @@ public function testEntityCacheChain() $this->logger->entityCacheMiss($name, $key); } - public function testCollectionCacheChain() + public function testCollectionCacheChain(): void { $name = 'my_collection_region'; $key = new CollectionCacheKey(State::class, 'cities', ['id' => 1]); @@ -93,7 +91,7 @@ public function testCollectionCacheChain() $this->logger->collectionCacheMiss($name, $key); } - public function testQueryCacheChain() + public function testQueryCacheChain(): void { $name = 'my_query_region'; $key = new QueryCacheKey('my_query_hash'); diff --git a/tests/Doctrine/Tests/ORM/Cache/DefaultCacheFactoryTest.php b/tests/Doctrine/Tests/ORM/Cache/DefaultCacheFactoryTest.php index b83fdff0520..4c2e560d55f 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->regionsConfig = new RegionsConfiguration; + $this->regionsConfig = new RegionsConfiguration(); $arguments = [$this->regionsConfig, $this->getSharedSecondLevelCacheDriverImpl()]; $this->factory = $this->getMockBuilder(DefaultCacheFactory::class) ->setMethods(['getRegion']) @@ -61,12 +62,12 @@ protected function setUp() : void ->getMock(); } - public function testImplementsCacheFactory() + public function testImplementsCacheFactory(): void { $this->assertInstanceOf(CacheFactory::class, $this->factory); } - public function testBuildCachedEntityPersisterReadOnly() + public function testBuildCachedEntityPersisterReadOnly(): void { $em = $this->em; $metadata = clone $em->getClassMetadata(State::class); @@ -86,7 +87,7 @@ public function testBuildCachedEntityPersisterReadOnly() $this->assertInstanceOf(ReadOnlyCachedEntityPersister::class, $cachedPersister); } - public function testBuildCachedEntityPersisterReadWrite() + public function testBuildCachedEntityPersisterReadWrite(): void { $em = $this->em; $metadata = clone $em->getClassMetadata(State::class); @@ -106,7 +107,7 @@ public function testBuildCachedEntityPersisterReadWrite() $this->assertInstanceOf(ReadWriteCachedEntityPersister::class, $cachedPersister); } - public function testBuildCachedEntityPersisterNonStrictReadWrite() + public function testBuildCachedEntityPersisterNonStrictReadWrite(): void { $em = $this->em; $metadata = clone $em->getClassMetadata(State::class); @@ -126,7 +127,7 @@ public function testBuildCachedEntityPersisterNonStrictReadWrite() $this->assertInstanceOf(NonStrictReadWriteCachedEntityPersister::class, $cachedPersister); } - public function testBuildCachedCollectionPersisterReadOnly() + public function testBuildCachedCollectionPersisterReadOnly(): void { $em = $this->em; $metadata = $em->getClassMetadata(State::class); @@ -141,14 +142,13 @@ public function testBuildCachedCollectionPersisterReadOnly() ->with($this->equalTo($mapping['cache'])) ->will($this->returnValue($region)); - $cachedPersister = $this->factory->buildCachedCollectionPersister($em, $persister, $mapping); $this->assertInstanceOf(CachedCollectionPersister::class, $cachedPersister); $this->assertInstanceOf(ReadOnlyCachedCollectionPersister::class, $cachedPersister); } - public function testBuildCachedCollectionPersisterReadWrite() + public function testBuildCachedCollectionPersisterReadWrite(): void { $em = $this->em; $metadata = $em->getClassMetadata(State::class); @@ -169,7 +169,7 @@ public function testBuildCachedCollectionPersisterReadWrite() $this->assertInstanceOf(ReadWriteCachedCollectionPersister::class, $cachedPersister); } - public function testBuildCachedCollectionPersisterNonStrictReadWrite() + public function testBuildCachedCollectionPersisterNonStrictReadWrite(): void { $em = $this->em; $metadata = $em->getClassMetadata(State::class); @@ -190,7 +190,7 @@ public function testBuildCachedCollectionPersisterNonStrictReadWrite() $this->assertInstanceOf(NonStrictReadWriteCachedCollectionPersister::class, $cachedPersister); } - public function testInheritedEntityCacheRegion() + public function testInheritedEntityCacheRegion(): void { $em = $this->em; $metadata1 = clone $em->getClassMetadata(AttractionContactInfo::class); @@ -209,7 +209,7 @@ public function testInheritedEntityCacheRegion() $this->assertSame($cachedPersister1->getCacheRegion(), $cachedPersister2->getCacheRegion()); } - public function testCreateNewCacheDriver() + public function testCreateNewCacheDriver(): void { $em = $this->em; $metadata1 = clone $em->getClassMetadata(State::class); @@ -228,7 +228,7 @@ public function testCreateNewCacheDriver() $this->assertNotSame($cachedPersister1->getCacheRegion(), $cachedPersister2->getCacheRegion()); } - public function testBuildCachedEntityPersisterNonStrictException() + public function testBuildCachedEntityPersisterNonStrictException(): void { $em = $this->em; $metadata = clone $em->getClassMetadata(State::class); @@ -236,13 +236,13 @@ public function testBuildCachedEntityPersisterNonStrictException() $metadata->cache['usage'] = -1; - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Unrecognized access strategy type [-1]'); $this->factory->buildCachedEntityPersister($em, $persister, $metadata); } - public function testBuildCachedCollectionPersisterException() + public function testBuildCachedCollectionPersisterException(): void { $em = $this->em; $metadata = $em->getClassMetadata(State::class); @@ -251,17 +251,17 @@ public function testBuildCachedCollectionPersisterException() $mapping['cache']['usage'] = -1; - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Unrecognized access strategy type [-1]'); $this->factory->buildCachedCollectionPersister($em, $persister, $mapping); } - public function testInvalidFileLockRegionDirectoryException() + public function testInvalidFileLockRegionDirectoryException(): void { $factory = new DefaultCacheFactory($this->regionsConfig, $this->getSharedSecondLevelCacheDriverImpl()); - $this->expectException(\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage( '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 ' @@ -271,18 +271,18 @@ public function testInvalidFileLockRegionDirectoryException() $factory->getRegion( [ 'usage' => ClassMetadata::CACHE_USAGE_READ_WRITE, - 'region' => 'foo' + 'region' => 'foo', ] ); } - public function testInvalidFileLockRegionDirectoryExceptionWithEmptyString() + public function testInvalidFileLockRegionDirectoryExceptionWithEmptyString(): void { $factory = new DefaultCacheFactory($this->regionsConfig, $this->getSharedSecondLevelCacheDriverImpl()); $factory->setFileLockRegionDirectory(''); - $this->expectException(\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage( '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 ' @@ -292,12 +292,12 @@ public function testInvalidFileLockRegionDirectoryExceptionWithEmptyString() $factory->getRegion( [ 'usage' => ClassMetadata::CACHE_USAGE_READ_WRITE, - 'region' => 'foo' + 'region' => 'foo', ] ); } - public function testBuildsNewNamespacedCacheInstancePerRegionInstance() + public function testBuildsNewNamespacedCacheInstancePerRegionInstance(): void { $factory = new DefaultCacheFactory($this->regionsConfig, $this->getSharedSecondLevelCacheDriverImpl()); @@ -318,7 +318,7 @@ public function testBuildsNewNamespacedCacheInstancePerRegionInstance() $this->assertSame('bar', $barRegion->getCache()->getNamespace()); } - public function testAppendsNamespacedCacheInstancePerRegionInstanceWhenItsAlreadySet() + public function testAppendsNamespacedCacheInstancePerRegionInstanceWhenItsAlreadySet(): void { $cache = clone $this->getSharedSecondLevelCacheDriverImpl(); $cache->setNamespace('testing'); @@ -342,10 +342,10 @@ public function testAppendsNamespacedCacheInstancePerRegionInstanceWhenItsAlread $this->assertSame('testing:bar', $barRegion->getCache()->getNamespace()); } - public function testBuildsDefaultCacheRegionFromGenericCacheRegion() + public function testBuildsDefaultCacheRegionFromGenericCacheRegion(): void { - /* @var $cache \Doctrine\Common\Cache\Cache */ $cache = $this->createMock(Cache::class); + assert($cache instanceof Cache); $factory = new DefaultCacheFactory($this->regionsConfig, $cache); @@ -360,10 +360,10 @@ public function testBuildsDefaultCacheRegionFromGenericCacheRegion() ); } - public function testBuildsMultiGetCacheRegionFromGenericCacheRegion() + public function testBuildsMultiGetCacheRegionFromGenericCacheRegion(): void { - /* @var $cache \Doctrine\Common\Cache\CacheProvider */ $cache = $this->getMockForAbstractClass(CacheProvider::class); + assert($cache instanceof CacheProvider); $factory = new DefaultCacheFactory($this->regionsConfig, $cache); @@ -377,5 +377,4 @@ public function testBuildsMultiGetCacheRegionFromGenericCacheRegion() ) ); } - } diff --git a/tests/Doctrine/Tests/ORM/Cache/DefaultCacheTest.php b/tests/Doctrine/Tests/ORM/Cache/DefaultCacheTest.php index 7d73e99a0cc..bc97977241f 100644 --- a/tests/Doctrine/Tests/ORM/Cache/DefaultCacheTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/DefaultCacheTest.php @@ -1,34 +1,37 @@ em->getClassMetadata($className); $cacheKey = new EntityCacheKey($metadata->name, $identifier); @@ -53,12 +55,10 @@ private function putEntityCacheEntry($className, array $identifier, array $data) } /** - * @param string $className - * @param string $association * @param array $ownerIdentifier * @param array $data */ - private function putCollectionCacheEntry($className, $association, array $ownerIdentifier, array $data) + private function putCollectionCacheEntry(string $className, string $association, array $ownerIdentifier, array $data): void { $metadata = $this->em->getClassMetadata($className); $cacheKey = new CollectionCacheKey($metadata->name, $association, $ownerIdentifier); @@ -68,26 +68,26 @@ private function putCollectionCacheEntry($className, $association, array $ownerI $persister->getCacheRegion()->put($cacheKey, $cacheEntry); } - public function testImplementsCache() + public function testImplementsCache(): void { $this->assertInstanceOf(Cache::class, $this->cache); } - public function testGetEntityCacheRegionAccess() + public function testGetEntityCacheRegionAccess(): void { $this->assertInstanceOf(Cache\Region::class, $this->cache->getEntityCacheRegion(State::class)); $this->assertNull($this->cache->getEntityCacheRegion(CmsUser::class)); } - public function testGetCollectionCacheRegionAccess() + public function testGetCollectionCacheRegionAccess(): void { $this->assertInstanceOf(Cache\Region::class, $this->cache->getCollectionCacheRegion(State::class, 'cities')); $this->assertNull($this->cache->getCollectionCacheRegion(CmsUser::class, 'phonenumbers')); } - public function testContainsEntity() + public function testContainsEntity(): void { - $identifier = ['id'=>1]; + $identifier = ['id' => 1]; $className = Country::class; $cacheEntry = array_merge($identifier, ['name' => 'Brazil']); @@ -99,9 +99,9 @@ public function testContainsEntity() $this->assertFalse($this->cache->containsEntity(CmsUser::class, 1)); } - public function testEvictEntity() + public function testEvictEntity(): void { - $identifier = ['id'=>1]; + $identifier = ['id' => 1]; $className = Country::class; $cacheEntry = array_merge($identifier, ['name' => 'Brazil']); @@ -115,9 +115,9 @@ public function testEvictEntity() $this->assertFalse($this->cache->containsEntity(Country::class, 1)); } - public function testEvictEntityRegion() + public function testEvictEntityRegion(): void { - $identifier = ['id'=>1]; + $identifier = ['id' => 1]; $className = Country::class; $cacheEntry = array_merge($identifier, ['name' => 'Brazil']); @@ -131,9 +131,9 @@ public function testEvictEntityRegion() $this->assertFalse($this->cache->containsEntity(Country::class, 1)); } - public function testEvictEntityRegions() + public function testEvictEntityRegions(): void { - $identifier = ['id'=>1]; + $identifier = ['id' => 1]; $className = Country::class; $cacheEntry = array_merge($identifier, ['name' => 'Brazil']); @@ -146,12 +146,12 @@ public function testEvictEntityRegions() $this->assertFalse($this->cache->containsEntity(Country::class, 1)); } - public function testContainsCollection() + public function testContainsCollection(): void { - $ownerId = ['id'=>1]; - $className = State::class; - $association = 'cities'; - $cacheEntry = [ + $ownerId = ['id' => 1]; + $className = State::class; + $association = 'cities'; + $cacheEntry = [ ['id' => 11], ['id' => 12], ]; @@ -164,12 +164,12 @@ public function testContainsCollection() $this->assertFalse($this->cache->containsCollection(CmsUser::class, 'phonenumbers', 1)); } - public function testEvictCollection() + public function testEvictCollection(): void { - $ownerId = ['id'=>1]; - $className = State::class; - $association = 'cities'; - $cacheEntry = [ + $ownerId = ['id' => 1]; + $className = State::class; + $association = 'cities'; + $cacheEntry = [ ['id' => 11], ['id' => 12], ]; @@ -184,12 +184,12 @@ public function testEvictCollection() $this->assertFalse($this->cache->containsCollection(State::class, $association, 1)); } - public function testEvictCollectionRegion() + public function testEvictCollectionRegion(): void { - $ownerId = ['id'=>1]; - $className = State::class; - $association = 'cities'; - $cacheEntry = [ + $ownerId = ['id' => 1]; + $className = State::class; + $association = 'cities'; + $cacheEntry = [ ['id' => 11], ['id' => 12], ]; @@ -204,12 +204,12 @@ public function testEvictCollectionRegion() $this->assertFalse($this->cache->containsCollection(State::class, $association, 1)); } - public function testEvictCollectionRegions() + public function testEvictCollectionRegions(): void { - $ownerId = ['id'=>1]; - $className = State::class; - $association = 'cities'; - $cacheEntry = [ + $ownerId = ['id' => 1]; + $className = State::class; + $association = 'cities'; + $cacheEntry = [ ['id' => 11], ['id' => 12], ]; @@ -223,7 +223,7 @@ public function testEvictCollectionRegions() $this->assertFalse($this->cache->containsCollection(State::class, $association, 1)); } - public function testQueryCache() + public function testQueryCache(): void { $this->assertFalse($this->cache->containsQuery('foo')); @@ -245,19 +245,18 @@ public function testQueryCache() $this->assertSame($fooQueryCache, $this->cache->getQueryCache('foo')); } - public function testToIdentifierArrayShouldLookupForEntityIdentifier() + public function testToIdentifierArrayShouldLookupForEntityIdentifier(): void { $identifier = 123; $entity = new Country('Foo'); $metadata = $this->em->getClassMetadata(Country::class); - $method = new \ReflectionMethod($this->cache, 'toIdentifierArray'); - $property = new \ReflectionProperty($entity, 'id'); + $method = new ReflectionMethod($this->cache, 'toIdentifierArray'); + $property = new ReflectionProperty($entity, 'id'); $property->setAccessible(true); $method->setAccessible(true); $property->setValue($entity, $identifier); - $this->assertEquals(['id'=>$identifier], $method->invoke($this->cache, $metadata, $identifier)); + $this->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 cff757d66ac..164dd09c599 100644 --- a/tests/Doctrine/Tests/ORM/Cache/DefaultCollectionHydratorTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/DefaultCollectionHydratorTest.php @@ -1,10 +1,13 @@ enableSecondLevelCache(); parent::setUp(); @@ -33,31 +34,29 @@ protected function setUp() : void $this->structure = new DefaultCollectionHydrator($this->_em, $targetPersister); } - public function testImplementsCollectionEntryStructure() + public function testImplementsCollectionEntryStructure(): void { $this->assertInstanceOf(DefaultCollectionHydrator::class, $this->structure); } - public function testLoadCacheCollection() + public function testLoadCacheCollection(): void { - $targetRegion = $this->_em->getCache()->getEntityCacheRegion(City::class); - $entry = new CollectionCacheEntry( + $targetRegion = $this->_em->getCache()->getEntityCacheRegion(City::class); + $entry = new CollectionCacheEntry( [ - new EntityCacheKey(City::class, ['id'=>31]), - new EntityCacheKey(City::class, ['id'=>32]), + new EntityCacheKey(City::class, ['id' => 31]), + new EntityCacheKey(City::class, ['id' => 32]), ] ); - $targetRegion->put(new EntityCacheKey(City::class, ['id'=>31]), new EntityCacheEntry(City::class, ['id'=>31, 'name'=>'Foo'] - )); - $targetRegion->put(new EntityCacheKey(City::class, ['id'=>32]), new EntityCacheEntry(City::class, ['id'=>32, 'name'=>'Bar'] - )); + $targetRegion->put(new EntityCacheKey(City::class, ['id' => 31]), new EntityCacheEntry(City::class, ['id' => 31, 'name' => 'Foo'])); + $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()); - $list = $this->structure->loadCacheEntry($sourceClass, $key, $entry, $collection); + $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()); + $list = $this->structure->loadCacheEntry($sourceClass, $key, $entry, $collection); $this->assertNotNull($list); $this->assertCount(2, $list); @@ -78,5 +77,4 @@ public function testLoadCacheCollection() $this->assertEquals(UnitOfWork::STATE_MANAGED, $this->_em->getUnitOfWork()->getEntityState($collection[0])); $this->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 ca1ad990570..8e1835066c0 100644 --- a/tests/Doctrine/Tests/ORM/Cache/DefaultEntityHydratorTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/DefaultEntityHydratorTest.php @@ -1,5 +1,7 @@ structure = new DefaultEntityHydrator($this->em); } - public function testImplementsEntityEntryStructure() + public function testImplementsEntityEntryStructure(): void { $this->assertInstanceOf('\Doctrine\ORM\Cache\EntityHydrator', $this->structure); } - public function testCreateEntity() + public function testCreateEntity(): void { $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->name, ['id' => 1]); + $entry = new EntityCacheEntry($metadata->name, ['id' => 1, 'name' => 'Foo']); $entity = $this->structure->loadCacheEntry($metadata, $key, $entry); $this->assertInstanceOf($metadata->name, $entity); @@ -54,11 +54,11 @@ public function testCreateEntity() $this->assertEquals(UnitOfWork::STATE_MANAGED, $this->em->getUnitOfWork()->getEntityState($entity)); } - public function testLoadProxy() + public function testLoadProxy(): void { $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->name, ['id' => 1]); + $entry = new EntityCacheEntry($metadata->name, ['id' => 1, 'name' => 'Foo']); $proxy = $this->em->getReference($metadata->name, $key->identifier); $entity = $this->structure->loadCacheEntry($metadata, $key, $entry, $proxy); @@ -70,18 +70,18 @@ public function testLoadProxy() $this->assertEquals(UnitOfWork::STATE_MANAGED, $this->em->getUnitOfWork()->getEntityState($proxy)); } - public function testBuildCacheEntry() + public function testBuildCacheEntry(): void { $entity = new Country('Foo'); $uow = $this->em->getUnitOfWork(); - $data = ['id'=>1, 'name'=>'Foo']; + $data = ['id' => 1, 'name' => 'Foo']; $metadata = $this->em->getClassMetadata(Country::class); - $key = new EntityCacheKey($metadata->name, ['id'=>1]); + $key = new EntityCacheKey($metadata->name, ['id' => 1]); $entity->setId(1); $uow->registerManaged($entity, $key->identifier, $data); - $cache = $this->structure->buildCacheEntry($metadata, $key, $entity); + $cache = $this->structure->buildCacheEntry($metadata, $key, $entity); $this->assertInstanceOf(CacheEntry::class, $cache); $this->assertInstanceOf(EntityCacheEntry::class, $cache); @@ -90,26 +90,28 @@ public function testBuildCacheEntry() $this->assertArrayHasKey('name', $cache->data); $this->assertEquals( [ - 'id' => 1, - 'name' => 'Foo', - ], $cache->data); + 'id' => 1, + 'name' => 'Foo', + ], + $cache->data + ); } - public function testBuildCacheEntryAssociation() + public function testBuildCacheEntryAssociation(): void { - $country = new Country('Foo'); - $state = new State('Bat', $country); - $uow = $this->em->getUnitOfWork(); - $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]); + $country = new Country('Foo'); + $state = new State('Bat', $country); + $uow = $this->em->getUnitOfWork(); + $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]); $country->setId(11); $state->setId(12); - $uow->registerManaged($country, ['id'=>11], $countryData); - $uow->registerManaged($state, ['id'=>12], $stateData); + $uow->registerManaged($country, ['id' => 11], $countryData); + $uow->registerManaged($state, ['id' => 12], $stateData); $cache = $this->structure->buildCacheEntry($metadata, $key, $state); @@ -121,24 +123,26 @@ public function testBuildCacheEntryAssociation() $this->assertArrayHasKey('country', $cache->data); $this->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() + public function testBuildCacheEntryNonInitializedAssocProxy(): void { - $proxy = $this->em->getReference(Country::class, 11); - $entity = new State('Bat', $proxy); - $uow = $this->em->getUnitOfWork(); - $entityData = ['id'=>12, 'name'=>'Bar', 'country' => $proxy]; - $metadata = $this->em->getClassMetadata(State::class); - $key = new EntityCacheKey($metadata->name, ['id'=>11]); + $proxy = $this->em->getReference(Country::class, 11); + $entity = new State('Bat', $proxy); + $uow = $this->em->getUnitOfWork(); + $entityData = ['id' => 12, 'name' => 'Bar', 'country' => $proxy]; + $metadata = $this->em->getClassMetadata(State::class); + $key = new EntityCacheKey($metadata->name, ['id' => 11]); $entity->setId(12); - $uow->registerManaged($entity, ['id'=>12], $entityData); + $uow->registerManaged($entity, ['id' => 12], $entityData); $cache = $this->structure->buildCacheEntry($metadata, $key, $entity); @@ -150,24 +154,26 @@ public function testBuildCacheEntryNonInitializedAssocProxy() $this->assertArrayHasKey('country', $cache->data); $this->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() + public function testCacheEntryWithWrongIdentifierType(): void { - $proxy = $this->em->getReference(Country::class, 11); - $entity = new State('Bat', $proxy); - $uow = $this->em->getUnitOfWork(); - $entityData = ['id'=> 12, 'name'=>'Bar', 'country' => $proxy]; - $metadata = $this->em->getClassMetadata(State::class); - $key = new EntityCacheKey($metadata->name, ['id'=>'12']); + $proxy = $this->em->getReference(Country::class, 11); + $entity = new State('Bat', $proxy); + $uow = $this->em->getUnitOfWork(); + $entityData = ['id' => 12, 'name' => 'Bar', 'country' => $proxy]; + $metadata = $this->em->getClassMetadata(State::class); + $key = new EntityCacheKey($metadata->name, ['id' => '12']); $entity->setId(12); - $uow->registerManaged($entity, ['id'=>12], $entityData); + $uow->registerManaged($entity, ['id' => 12], $entityData); $cache = $this->structure->buildCacheEntry($metadata, $key, $entity); @@ -180,10 +186,11 @@ public function testCacheEntryWithWrongIdentifierType() $this->assertSame($entity->getId(), $cache->data['id']); $this->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 59c23dbf730..852c6b25eb0 100644 --- a/tests/Doctrine/Tests/ORM/Cache/DefaultQueryCacheTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/DefaultQueryCacheTest.php @@ -1,52 +1,51 @@ setCacheFactory($this->cacheFactory); } - public function testImplementQueryCache() + public function testImplementQueryCache(): void { $this->assertInstanceOf(QueryCache::class, $this->queryCache); } - public function testGetRegion() + public function testGetRegion(): void { $this->assertSame($this->region, $this->queryCache->getRegion()); } - public function testClearShouldEvictRegion() + public function testClearShouldEvictRegion(): void { $this->queryCache->clear(); @@ -80,7 +79,7 @@ public function testClearShouldEvictRegion() $this->assertCount(1, $this->region->calls['evictAll']); } - public function testPutBasicQueryResult() + public function testPutBasicQueryResult(): void { $result = []; $key = new QueryCacheKey('query.key1', 0); @@ -90,9 +89,9 @@ public function testPutBasicQueryResult() $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); + $result[] = $entity; $metadata->setFieldValue($entity, 'id', $i); $this->em->getUnitOfWork()->registerManaged($entity, ['id' => $i], ['name' => $name]); @@ -115,7 +114,7 @@ public function testPutBasicQueryResult() $this->assertInstanceOf(QueryCacheEntry::class, $this->region->calls['put'][4]['entry']); } - public function testPutToOneAssociationQueryResult() + public function testPutToOneAssociationQueryResult(): void { $result = []; $uow = $this->em->getUnitOfWork(); @@ -125,7 +124,7 @@ public function testPutToOneAssociationQueryResult() $stateClass = $this->em->getClassMetadata(State::class); $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']); for ($i = 0; $i < 4; $i++) { $state = new State("State $i"); @@ -133,7 +132,7 @@ public function testPutToOneAssociationQueryResult() $result[] = $city; $cityClass->setFieldValue($city, 'id', $i); - $stateClass->setFieldValue($state, 'id', $i*2); + $stateClass->setFieldValue($state, 'id', $i * 2); $uow->registerManaged($state, ['id' => $state->getId()], ['name' => $city->getName()]); $uow->registerManaged($city, ['id' => $city->getId()], ['name' => $city->getName(), 'state' => $state]); @@ -154,36 +153,33 @@ public function testPutToOneAssociationQueryResult() $this->assertInstanceOf(QueryCacheKey::class, $this->region->calls['put'][8]['key']); } - public function testPutToOneAssociation2LevelsQueryResult() + public function testPutToOneAssociation2LevelsQueryResult(): void { - $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); + $cityClass = $this->em->getClassMetadata(City::class); + $stateClass = $this->em->getClassMetadata(State::class); $countryClass = $this->em->getClassMetadata(Country::class); $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); + $country = new Country("Country $i"); + $state = new State("State $i", $country); + $city = new City("City $i", $state); $result[] = $city; $cityClass->setFieldValue($city, 'id', $i); - $stateClass->setFieldValue($state, 'id', $i*2); - $countryClass->setFieldValue($country, 'id', $i*3); + $stateClass->setFieldValue($state, 'id', $i * 2); + $countryClass->setFieldValue($country, 'id', $i * 3); $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]); } @@ -206,17 +202,16 @@ public function testPutToOneAssociation2LevelsQueryResult() $this->assertInstanceOf(QueryCacheKey::class, $this->region->calls['put'][12]['key']); } - public function testPutToOneAssociationNullQueryResult() + public function testPutToOneAssociationNullQueryResult(): void { - $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); + $cityClass = $this->em->getClassMetadata(City::class); $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']); for ($i = 0; $i < 4; $i++) { $city = new City("City $i", null); @@ -238,7 +233,7 @@ public function testPutToOneAssociationNullQueryResult() $this->assertInstanceOf(QueryCacheKey::class, $this->region->calls['put'][4]['key']); } - public function testPutToManyAssociationQueryResult() + public function testPutToManyAssociationQueryResult(): void { $result = []; $uow = $this->em->getUnitOfWork(); @@ -248,12 +243,12 @@ public function testPutToManyAssociationQueryResult() $stateClass = $this->em->getClassMetadata(State::class); $rsm->addRootEntityFromClassMetadata(State::class, 's'); - $rsm->addJoinedEntityFromClassMetadata(City::class, 'c', 's', 'cities', ['id'=>'c_id', 'name'=>'c_name']); + $rsm->addJoinedEntityFromClassMetadata(City::class, 'c', 's', 'cities', ['id' => 'c_id', 'name' => 'c_name']); for ($i = 0; $i < 4; $i++) { $state = new State("State $i"); - $city1 = new City("City 1", $state); - $city2 = new City("City 2", $state); + $city1 = new City('City 1', $state); + $city2 = new City('City 2', $state); $result[] = $state; $cityClass->setFieldValue($city1, 'id', $i + 11); @@ -263,12 +258,9 @@ public function testPutToManyAssociationQueryResult() $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)); @@ -276,20 +268,20 @@ public function testPutToManyAssociationQueryResult() $this->assertCount(13, $this->region->calls['put']); } - public function testGetBasicQueryResult() + public function testGetBasicQueryResult(): void { $rsm = new ResultSetMappingBuilder($this->em); $key = new QueryCacheKey('query.key1', 0); $entry = new QueryCacheEntry( [ ['identifier' => ['id' => 1]], - ['identifier' => ['id' => 2]] + ['identifier' => ['id' => 2]], ] ); $data = [ - ['id'=>1, 'name' => 'Foo'], - ['id'=>2, 'name' => 'Bar'] + ['id' => 1, 'name' => 'Foo'], + ['id' => 2, 'name' => 'Bar'], ]; $this->region->addReturn('get', $entry); @@ -298,7 +290,7 @@ public function testGetBasicQueryResult() 'getMultiple', [ new EntityCacheEntry(Country::class, $data[0]), - new EntityCacheEntry(Country::class, $data[1]) + new EntityCacheEntry(Country::class, $data[1]), ] ); @@ -315,20 +307,20 @@ public function testGetBasicQueryResult() $this->assertEquals('Bar', $result[1]->getName()); } - public function testGetWithAssociation() + public function testGetWithAssociation(): void { $rsm = new ResultSetMappingBuilder($this->em); $key = new QueryCacheKey('query.key1', 0); $entry = new QueryCacheEntry( [ ['identifier' => ['id' => 1]], - ['identifier' => ['id' => 2]] + ['identifier' => ['id' => 2]], ] ); $data = [ - ['id'=>1, 'name' => 'Foo'], - ['id'=>2, 'name' => 'Bar'] + ['id' => 1, 'name' => 'Foo'], + ['id' => 2, 'name' => 'Bar'], ]; $this->region->addReturn('get', $entry); @@ -337,7 +329,7 @@ public function testGetWithAssociation() 'getMultiple', [ new EntityCacheEntry(Country::class, $data[0]), - new EntityCacheEntry(Country::class, $data[1]) + new EntityCacheEntry(Country::class, $data[1]), ] ); @@ -354,7 +346,7 @@ public function testGetWithAssociation() $this->assertEquals('Bar', $result[1]->getName()); } - public function testGetWithAssociationCacheMiss() : void + public function testGetWithAssociationCacheMiss(): void { $rsm = new ResultSetMappingBuilder($this->em); $key = new QueryCacheKey('query.key1', 0); @@ -382,7 +374,7 @@ public function testGetWithAssociationCacheMiss() : void self::assertNull($result); } - public function testCancelPutResultIfEntityPutFails() + public function testCancelPutResultIfEntityPutFails(): void { $result = []; $key = new QueryCacheKey('query.key1', 0); @@ -392,9 +384,9 @@ public function testCancelPutResultIfEntityPutFails() $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); + $result[] = $entity; $metadata->setFieldValue($entity, 'id', $i); $this->em->getUnitOfWork()->registerManaged($entity, ['id' => $i], ['name' => $name]); @@ -407,7 +399,7 @@ public function testCancelPutResultIfEntityPutFails() $this->assertCount(1, $this->region->calls['put']); } - public function testCancelPutResultIfAssociationEntityPutFails() + public function testCancelPutResultIfAssociationEntityPutFails(): void { $result = []; $uow = $this->em->getUnitOfWork(); @@ -417,11 +409,10 @@ public function testCancelPutResultIfAssociationEntityPutFails() $stateClass = $this->em->getClassMetadata(State::class); $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); + $state = new State('State 1'); + $city = new City('City 2', $state); $result[] = $city; $cityClass->setFieldValue($city, 'id', 1); @@ -436,7 +427,7 @@ public function testCancelPutResultIfAssociationEntityPutFails() $this->assertFalse($this->queryCache->put($key, $rsm, $result)); } - public function testCancelPutToManyAssociationQueryResult() + public function testCancelPutToManyAssociationQueryResult(): void { $result = []; $uow = $this->em->getUnitOfWork(); @@ -446,11 +437,11 @@ public function testCancelPutToManyAssociationQueryResult() $stateClass = $this->em->getClassMetadata(State::class); $rsm->addRootEntityFromClassMetadata(State::class, 's'); - $rsm->addJoinedEntityFromClassMetadata(City::class, 'c', 's', 'cities', ['id'=>'c_id', 'name'=>'c_name']); + $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); + $state = new State('State'); + $city1 = new City('City 1', $state); + $city2 = new City('City 2', $state); $result[] = $state; $stateClass->setFieldValue($state, 'id', 1); @@ -462,8 +453,7 @@ public function testCancelPutToManyAssociationQueryResult() $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 @@ -473,14 +463,14 @@ public function testCancelPutToManyAssociationQueryResult() $this->assertCount(2, $this->region->calls['put']); } - public function testIgnoreCacheNonGetMode() + public function testIgnoreCacheNonGetMode(): void { $rsm = new ResultSetMappingBuilder($this->em); $key = new QueryCacheKey('query.key1', 0, Cache::MODE_PUT); $entry = new QueryCacheEntry( [ - ['identifier' => ['id' => 1]], - ['identifier' => ['id' => 2]] + ['identifier' => ['id' => 1]], + ['identifier' => ['id' => 2]], ] ); @@ -491,7 +481,7 @@ public function testIgnoreCacheNonGetMode() $this->assertNull($this->queryCache->get($key, $rsm)); } - public function testIgnoreCacheNonPutMode() + public function testIgnoreCacheNonPutMode(): void { $result = []; $rsm = new ResultSetMappingBuilder($this->em); @@ -501,9 +491,9 @@ public function testIgnoreCacheNonPutMode() $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); + $result[] = $entity; $metadata->setFieldValue($entity, 'id', $i); $this->em->getUnitOfWork()->registerManaged($entity, ['id' => $i], ['name' => $name]); @@ -512,19 +502,19 @@ public function testIgnoreCacheNonPutMode() $this->assertFalse($this->queryCache->put($key, $rsm, $result)); } - public function testGetShouldIgnoreOldQueryCacheEntryResult() + public function testGetShouldIgnoreOldQueryCacheEntryResult(): void { - $rsm = new ResultSetMappingBuilder($this->em); - $key = new QueryCacheKey('query.key1', 50); - $entry = new QueryCacheEntry( + $rsm = new ResultSetMappingBuilder($this->em); + $key = new QueryCacheKey('query.key1', 50); + $entry = new QueryCacheEntry( [ - ['identifier' => ['id' => 1]], - ['identifier' => ['id' => 2]] + ['identifier' => ['id' => 1]], + ['identifier' => ['id' => 2]], ] ); $entities = [ - ['id'=>1, 'name' => 'Foo'], - ['id'=>2, 'name' => 'Bar'] + ['id' => 1, 'name' => 'Foo'], + ['id' => 2, 'name' => 'Bar'], ]; $entry->time = microtime(true) - 100; @@ -535,7 +525,7 @@ public function testGetShouldIgnoreOldQueryCacheEntryResult() 'getMultiple', [ new EntityCacheEntry(Country::class, $entities[0]), - new EntityCacheEntry(Country::class, $entities[1]) + new EntityCacheEntry(Country::class, $entities[1]), ] ); @@ -544,20 +534,20 @@ public function testGetShouldIgnoreOldQueryCacheEntryResult() $this->assertNull($this->queryCache->get($key, $rsm)); } - public function testGetShouldIgnoreNonQueryCacheEntryResult() + public function testGetShouldIgnoreNonQueryCacheEntryResult(): void { $rsm = new ResultSetMappingBuilder($this->em); $key = new QueryCacheKey('query.key1', 0); - $entry = new \ArrayObject( + $entry = new ArrayObject( [ - ['identifier' => ['id' => 1]], - ['identifier' => ['id' => 2]] + ['identifier' => ['id' => 1]], + ['identifier' => ['id' => 2]], ] ); $data = [ - ['id'=>1, 'name' => 'Foo'], - ['id'=>2, 'name' => 'Bar'] + ['id' => 1, 'name' => 'Foo'], + ['id' => 2, 'name' => 'Bar'], ]; $this->region->addReturn('get', $entry); @@ -566,7 +556,7 @@ public function testGetShouldIgnoreNonQueryCacheEntryResult() 'getMultiple', [ new EntityCacheEntry(Country::class, $data[0]), - new EntityCacheEntry(Country::class, $data[1]) + new EntityCacheEntry(Country::class, $data[1]), ] ); @@ -575,14 +565,14 @@ public function testGetShouldIgnoreNonQueryCacheEntryResult() $this->assertNull($this->queryCache->get($key, $rsm)); } - public function testGetShouldIgnoreMissingEntityQueryCacheEntry() + public function testGetShouldIgnoreMissingEntityQueryCacheEntry(): void { $rsm = new ResultSetMappingBuilder($this->em); $key = new QueryCacheKey('query.key1', 0); $entry = new QueryCacheEntry( [ - ['identifier' => ['id' => 1]], - ['identifier' => ['id' => 2]] + ['identifier' => ['id' => 1]], + ['identifier' => ['id' => 2]], ] ); @@ -594,18 +584,18 @@ public function testGetShouldIgnoreMissingEntityQueryCacheEntry() $this->assertNull($this->queryCache->get($key, $rsm)); } - public function testGetAssociationValue() + public function testGetAssociationValue(): void { - $reflection = new \ReflectionMethod($this->queryCache, 'getAssociationValue'); + $reflection = new ReflectionMethod($this->queryCache, 'getAssociationValue'); $rsm = new ResultSetMappingBuilder($this->em); $key = new QueryCacheKey('query.key1', 0); $reflection->setAccessible(true); - $germany = new Country("Germany"); - $bavaria = new State("Bavaria", $germany); - $wurzburg = new City("Würzburg", $bavaria); - $munich = new City("Munich", $bavaria); + $germany = new Country('Germany'); + $bavaria = new State('Bavaria', $germany); + $wurzburg = new City('Würzburg', $bavaria); + $munich = new City('Munich', $bavaria); $bavaria->addCity($munich); $bavaria->addCity($wurzburg); @@ -617,20 +607,18 @@ public function testGetAssociationValue() $rsm->addRootEntityFromClassMetadata(State::class, 's'); $rsm->addJoinedEntityFromClassMetadata(City::class, 'c', 's', 'cities', [ 'id' => 'c_id', - 'name' => 'c_name' - ] - ); + 'name' => 'c_name', + ]); $rsm->addJoinedEntityFromClassMetadata(Restaurant::class, 'a', 'c', 'attractions', [ 'id' => 'a_id', - 'name' => 'a_name' - ] - ); + 'name' => 'a_name', + ]); $cities = $reflection->invoke($this->queryCache, $rsm, 'c', $bavaria); $attractions = $reflection->invoke($this->queryCache, $rsm, 'a', $bavaria); $this->assertCount(2, $cities); - $this->assertCount(2, $attractions); + $this->assertCount(2, $attractions); $this->assertInstanceOf(Collection::class, $cities); $this->assertInstanceOf(Collection::class, $attractions[0]); @@ -640,26 +628,26 @@ public function testGetAssociationValue() $this->assertCount(1, $attractions[1]); } - public function testScalarResultException() + public function testScalarResultException(): void { $this->expectException('Doctrine\ORM\Cache\CacheException'); $this->expectExceptionMessage('Second level cache does not support scalar results.'); - $result = []; - $key = new QueryCacheKey('query.key1', 0); - $rsm = new ResultSetMappingBuilder($this->em); + $result = []; + $key = new QueryCacheKey('query.key1', 0); + $rsm = new ResultSetMappingBuilder($this->em); $rsm->addScalarResult('id', 'u', 'integer'); $this->queryCache->put($key, $rsm, $result); } - public function testSupportMultipleRootEntitiesException() + public function testSupportMultipleRootEntitiesException(): void { $this->expectException('Doctrine\ORM\Cache\CacheException'); $this->expectExceptionMessage('Second level cache does not support multiple root entities.'); - $result = []; - $key = new QueryCacheKey('query.key1', 0); - $rsm = new ResultSetMappingBuilder($this->em); + $result = []; + $key = new QueryCacheKey('query.key1', 0); + $rsm = new ResultSetMappingBuilder($this->em); $rsm->addEntityResult(City::class, 'e1'); $rsm->addEntityResult(State::class, 'e2'); @@ -667,29 +655,28 @@ public function testSupportMultipleRootEntitiesException() $this->queryCache->put($key, $rsm, $result); } - public function testNotCacheableEntityException() + public function testNotCacheableEntityException(): void { $this->expectException('Doctrine\ORM\Cache\CacheException'); $this->expectExceptionMessage('Entity "Doctrine\Tests\Models\Generic\BooleanModel" not configured as part of the second-level cache.'); - $result = []; - $key = new QueryCacheKey('query.key1', 0); - $rsm = new ResultSetMappingBuilder($this->em); + $result = []; + $key = new QueryCacheKey('query.key1', 0); + $rsm = new ResultSetMappingBuilder($this->em); $rsm->addRootEntityFromClassMetadata(BooleanModel::class, 'c'); for ($i = 0; $i < 4; $i++) { $entity = new BooleanModel(); $boolean = ($i % 2 === 0); - $entity->id = $i; - $entity->booleanField = $boolean; - $result[] = $entity; + $entity->id = $i; + $entity->booleanField = $boolean; + $result[] = $entity; $this->em->getUnitOfWork()->registerManaged($entity, ['id' => $i], ['booleanField' => $boolean]); } $this->assertFalse($this->queryCache->put($key, $rsm, $result)); } - } class CacheFactoryDefaultQueryCacheTest extends Cache\DefaultCacheFactory diff --git a/tests/Doctrine/Tests/ORM/Cache/DefaultRegionTest.php b/tests/Doctrine/Tests/ORM/Cache/DefaultRegionTest.php index e50c2a55c3d..6562c2b3bda 100644 --- a/tests/Doctrine/Tests/ORM/Cache/DefaultRegionTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/DefaultRegionTest.php @@ -1,7 +1,10 @@ cache); } - public function testGetters() + public function testGetters(): void { $this->assertEquals('default.region.test', $this->region->getName()); $this->assertSame($this->cache, $this->region->getCache()); } - public function testSharedRegion() + public function testSharedRegion(): void { $cache = new SharedArrayCache(); $key = new CacheKeyMock('key'); @@ -49,7 +54,7 @@ public function testSharedRegion() $this->assertTrue($region2->contains($key)); } - public function testDoesNotModifyCacheNamespace() + public function testDoesNotModifyCacheNamespace(): void { $cache = new ArrayCache(); @@ -61,24 +66,24 @@ public function testDoesNotModifyCacheNamespace() $this->assertSame('foo', $cache->getNamespace()); } - public function testEvictAllWithGenericCacheThrowsUnsupportedException() + public function testEvictAllWithGenericCacheThrowsUnsupportedException(): void { - /* @var $cache \Doctrine\Common\Cache\Cache */ $cache = $this->createMock(Cache::class); + assert($cache instanceof Cache); $region = new DefaultRegion('foo', $cache); - $this->expectException(\BadMethodCallException::class); + $this->expectException(BadMethodCallException::class); $region->evictAll(); } - public function testGetMulti() + public function testGetMulti(): void { - $key1 = new CacheKeyMock('key.1'); + $key1 = new CacheKeyMock('key.1'); $value1 = new CacheEntryMock(['id' => 1, 'name' => 'bar']); - $key2 = new CacheKeyMock('key.2'); + $key2 = new CacheKeyMock('key.2'); $value2 = new CacheEntryMock(['id' => 2, 'name' => 'bar']); $this->assertFalse($this->region->contains($key1)); @@ -100,7 +105,7 @@ public function testGetMulti() * @test * @group GH7266 */ - public function corruptedDataDoesNotLeakIntoApplicationWhenGettingSingleEntry() : void + public function corruptedDataDoesNotLeakIntoApplicationWhenGettingSingleEntry(): void { $key1 = new CacheKeyMock('key.1'); $this->cache->save($this->region->getName() . '_' . $key1->hash, 'a-very-invalid-value'); @@ -113,7 +118,7 @@ public function corruptedDataDoesNotLeakIntoApplicationWhenGettingSingleEntry() * @test * @group GH7266 */ - public function corruptedDataDoesNotLeakIntoApplicationWhenGettingMultipleEntries() : void + public function corruptedDataDoesNotLeakIntoApplicationWhenGettingMultipleEntries(): void { $key1 = new CacheKeyMock('key.1'); $this->cache->save($this->region->getName() . '_' . $key1->hash, 'a-very-invalid-value'); @@ -137,9 +142,7 @@ public function createChild(): Cache { return new class ($this) extends CacheProvider { - /** - * @var ArrayCache - */ + /** @var ArrayCache */ private $parent; public function __construct(ArrayCache $parent) diff --git a/tests/Doctrine/Tests/ORM/Cache/FileLockRegionTest.php b/tests/Doctrine/Tests/ORM/Cache/FileLockRegionTest.php index f42b4f61c10..0c4449b2de3 100644 --- a/tests/Doctrine/Tests/ORM/Cache/FileLockRegionTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/FileLockRegionTest.php @@ -1,5 +1,7 @@ cleanTestDirectory($this->directory); } - /** - * @param \Doctrine\ORM\Cache\ConcurrentRegion $region - * @param \Doctrine\ORM\Cache\CacheKey $key - * - * @return string - */ - private function getFileName(ConcurrentRegion $region, CacheKey $key) + private function getFileName(ConcurrentRegion $region, CacheKey $key): string { - $reflection = new \ReflectionMethod($region, 'getLockFileName'); + $reflection = new ReflectionMethod($region, 'getLockFileName'); $reflection->setAccessible(true); @@ -52,23 +56,23 @@ private function getFileName(ConcurrentRegion $region, CacheKey $key) protected function createRegion() { - $this->directory = sys_get_temp_dir() . '/doctrine_lock_'. uniqid(); + $this->directory = sys_get_temp_dir() . '/doctrine_lock_' . uniqid(); $region = new DefaultRegion('concurren_region_test', $this->cache); return new FileLockRegion($region, $this->directory, 60); } - public function testGetRegionName() + public function testGetRegionName(): void { $this->assertEquals('concurren_region_test', $this->region->getName()); } - public function testLockAndUnlock() + public function testLockAndUnlock(): void { - $key = new CacheKeyMock('key'); - $entry = new CacheEntryMock(['foo' => 'bar']); - $file = $this->getFileName($this->region, $key); + $key = new CacheKeyMock('key'); + $entry = new CacheEntryMock(['foo' => 'bar']); + $file = $this->getFileName($this->region, $key); $this->assertFalse($this->region->contains($key)); $this->assertTrue($this->region->put($key, $entry)); @@ -88,11 +92,11 @@ public function testLockAndUnlock() $this->assertFileNotExists($file); } - public function testLockWithExistingLock() + public function testLockWithExistingLock(): void { - $key = new CacheKeyMock('key'); - $entry = new CacheEntryMock(['foo' => 'bar']); - $file = $this->getFileName($this->region, $key); + $key = new CacheKeyMock('key'); + $entry = new CacheEntryMock(['foo' => 'bar']); + $file = $this->getFileName($this->region, $key); $this->assertFalse($this->region->contains($key)); $this->assertTrue($this->region->put($key, $entry)); @@ -100,10 +104,10 @@ public function testLockWithExistingLock() file_put_contents($file, 'foo'); $this->assertFileExists($file); - $this->assertEquals('foo' , file_get_contents($file)); + $this->assertEquals('foo', file_get_contents($file)); $this->assertNull($this->region->lock($key)); - $this->assertEquals('foo' , file_get_contents($file)); + $this->assertEquals('foo', file_get_contents($file)); $this->assertFileExists($file); // should be not available @@ -111,11 +115,11 @@ public function testLockWithExistingLock() $this->assertNull($this->region->get($key)); } - public function testUnlockWithExistingLock() + public function testUnlockWithExistingLock(): void { - $key = new CacheKeyMock('key'); - $entry = new CacheEntryMock(['foo' => 'bar']); - $file = $this->getFileName($this->region, $key); + $key = new CacheKeyMock('key'); + $entry = new CacheEntryMock(['foo' => 'bar']); + $file = $this->getFileName($this->region, $key); $this->assertFalse($this->region->contains($key)); $this->assertTrue($this->region->put($key, $entry)); @@ -128,11 +132,11 @@ public function testUnlockWithExistingLock() // change the lock file_put_contents($file, 'foo'); $this->assertFileExists($file); - $this->assertEquals('foo' , file_get_contents($file)); + $this->assertEquals('foo', file_get_contents($file)); //try to unlock $this->assertFalse($this->region->unlock($key, $lock)); - $this->assertEquals('foo' , file_get_contents($file)); + $this->assertEquals('foo', file_get_contents($file)); $this->assertFileExists($file); // should be not available @@ -140,11 +144,11 @@ public function testUnlockWithExistingLock() $this->assertNull($this->region->get($key)); } - public function testPutWithExistingLock() + public function testPutWithExistingLock(): void { - $key = new CacheKeyMock('key'); - $entry = new CacheEntryMock(['foo' => 'bar']); - $file = $this->getFileName($this->region, $key); + $key = new CacheKeyMock('key'); + $entry = new CacheEntryMock(['foo' => 'bar']); + $file = $this->getFileName($this->region, $key); $this->assertFalse($this->region->contains($key)); $this->assertTrue($this->region->put($key, $entry)); @@ -153,21 +157,21 @@ public function testPutWithExistingLock() // create lock file_put_contents($file, 'foo'); $this->assertFileExists($file); - $this->assertEquals('foo' , file_get_contents($file)); + $this->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)); $this->assertFileExists($file); - $this->assertEquals('foo' , file_get_contents($file)); + $this->assertEquals('foo', file_get_contents($file)); } - public function testLockedEvict() + public function testLockedEvict(): void { - $key = new CacheKeyMock('key'); - $entry = new CacheEntryMock(['foo' => 'bar']); - $file = $this->getFileName($this->region, $key); + $key = new CacheKeyMock('key'); + $entry = new CacheEntryMock(['foo' => 'bar']); + $file = $this->getFileName($this->region, $key); $this->assertFalse($this->region->contains($key)); $this->assertTrue($this->region->put($key, $entry)); @@ -183,15 +187,15 @@ public function testLockedEvict() $this->assertFileNotExists($file); } - public function testLockedEvictAll() + public function testLockedEvictAll(): void { - $key1 = new CacheKeyMock('key1'); - $entry1 = new CacheEntryMock(['foo1' => 'bar1']); - $file1 = $this->getFileName($this->region, $key1); + $key1 = new CacheKeyMock('key1'); + $entry1 = new CacheEntryMock(['foo1' => 'bar1']); + $file1 = $this->getFileName($this->region, $key1); - $key2 = new CacheKeyMock('key2'); - $entry2 = new CacheEntryMock(['foo2' => 'bar2']); - $file2 = $this->getFileName($this->region, $key2); + $key2 = new CacheKeyMock('key2'); + $entry2 = new CacheEntryMock(['foo2' => 'bar2']); + $file2 = $this->getFileName($this->region, $key2); $this->assertFalse($this->region->contains($key1)); $this->assertTrue($this->region->put($key1, $entry1)); @@ -219,12 +223,12 @@ public function testLockedEvictAll() $this->assertFalse($this->region->contains($key2)); } - public function testLockLifetime() + public function testLockLifetime(): void { - $key = new CacheKeyMock('key'); - $entry = new CacheEntryMock(['foo' => 'bar']); - $file = $this->getFileName($this->region, $key); - $property = new \ReflectionProperty($this->region, 'lockLifetime'); + $key = new CacheKeyMock('key'); + $entry = new CacheEntryMock(['foo' => 'bar']); + $file = $this->getFileName($this->region, $key); + $property = new ReflectionProperty($this->region, 'lockLifetime'); $property->setAccessible(true); $property->setValue($this->region, -10); @@ -247,15 +251,16 @@ public function testLockLifetime() * @group 1072 * @group DDC-3191 */ - public function testHandlesScanErrorsGracefullyOnEvictAll() + public function testHandlesScanErrorsGracefullyOnEvictAll(): void { $region = $this->createRegion(); - $reflectionDirectory = new \ReflectionProperty($region, 'directory'); + $reflectionDirectory = new ReflectionProperty($region, 'directory'); $reflectionDirectory->setAccessible(true); $reflectionDirectory->setValue($region, str_repeat('a', 10000)); - set_error_handler(function () {}, E_WARNING); + set_error_handler(static function (): void { + }, E_WARNING); $this->assertTrue($region->evictAll()); restore_error_handler(); } @@ -263,11 +268,11 @@ public function testHandlesScanErrorsGracefullyOnEvictAll() /** * @param string|null $path directory to clean */ - private function cleanTestDirectory($path) + private function cleanTestDirectory(?string $path): void { $path = $path ?: $this->directory; - if ( ! is_dir($path)) { + if (! is_dir($path)) { return; } diff --git a/tests/Doctrine/Tests/ORM/Cache/MultiGetRegionTest.php b/tests/Doctrine/Tests/ORM/Cache/MultiGetRegionTest.php index 5f45de47148..b8bc33951da 100644 --- a/tests/Doctrine/Tests/ORM/Cache/MultiGetRegionTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/MultiGetRegionTest.php @@ -1,15 +1,14 @@ - */ class MultiGetRegionTest extends AbstractRegionTest { protected function createRegion() @@ -17,12 +16,12 @@ protected function createRegion() return new DefaultMultiGetRegion('default.region.test', $this->cache); } - public function testGetMulti() + public function testGetMulti(): void { - $key1 = new CacheKeyMock('key.1'); + $key1 = new CacheKeyMock('key.1'); $value1 = new CacheEntryMock(['id' => 1, 'name' => 'bar']); - $key2 = new CacheKeyMock('key.2'); + $key2 = new CacheKeyMock('key.2'); $value2 = new CacheEntryMock(['id' => 2, 'name' => 'bar']); $this->assertFalse($this->region->contains($key1)); @@ -44,7 +43,7 @@ public function testGetMulti() * @test * @group GH7266 */ - public function corruptedDataDoesNotLeakIntoApplication() : void + public function corruptedDataDoesNotLeakIntoApplication(): void { $key1 = new CacheKeyMock('key.1'); $this->cache->save($this->region->getName() . '_' . $key1->hash, 'a-very-invalid-value'); diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/AbstractCollectionPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/AbstractCollectionPersisterTest.php index 69bd7497f26..7acad44fcb2 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/AbstractCollectionPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/AbstractCollectionPersisterTest.php @@ -1,42 +1,35 @@ getSharedSecondLevelCacheDriverImpl()->flushAll(); $this->enableSecondLevelCache(); parent::setUp(); - $this->em = $this->_getTestEntityManager(); - $this->region = $this->createRegion(); - $this->collectionPersister = $this->getMockBuilder(CollectionPersister::class) + $this->em = $this->_getTestEntityManager(); + $this->region = $this->createRegion(); + $this->collectionPersister = $this->getMockBuilder(CollectionPersister::class) ->setMethods($this->collectionPersisterMockMethods) ->getMock(); } - /** - * @return \Doctrine\ORM\Cache\Region - */ - protected function createRegion() + protected function createRegion(): Region { return $this->getMockBuilder(Region::class) ->setMethods($this->regionMockMethods) ->getMock(); } - /** - * @return \Doctrine\ORM\PersistentCollection - */ - protected function createCollection($owner, $assoc = null, $class = null, $elements = null) + protected function createCollection($owner, $assoc = null, $class = null, $elements = null): PersistentCollection { $em = $this->em; $class = $class ?: $this->em->getClassMetadata(State::class); $assoc = $assoc ?: $class->associationMappings['cities']; - $coll = new PersistentCollection($em, $class, $elements ?: new ArrayCollection); + $coll = new PersistentCollection($em, $class, $elements ?: new ArrayCollection()); $coll->setOwner($owner, $assoc); $coll->setInitialized(true); @@ -120,7 +100,7 @@ protected function createPersisterDefault() return $this->createPersister($this->em, $this->collectionPersister, $this->region, $assoc); } - public function testImplementsEntityPersister() + public function testImplementsEntityPersister(): void { $persister = $this->createPersisterDefault(); @@ -129,13 +109,13 @@ public function testImplementsEntityPersister() $this->assertInstanceOf(CachedCollectionPersister::class, $persister); } - public function testInvokeDelete() + public function testInvokeDelete(): void { - $entity = new State("Foo"); + $entity = new State('Foo'); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $this->collectionPersister->expects($this->once()) ->method('delete') @@ -144,15 +124,15 @@ public function testInvokeDelete() $this->assertNull($persister->delete($collection)); } - public function testInvokeUpdate() + public function testInvokeUpdate(): void { - $entity = new State("Foo"); + $entity = new State('Foo'); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); $collection->setDirty(true); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $this->collectionPersister->expects($this->once()) ->method('update') @@ -161,13 +141,13 @@ public function testInvokeUpdate() $this->assertNull($persister->update($collection)); } - public function testInvokeCount() + public function testInvokeCount(): void { - $entity = new State("Foo"); + $entity = new State('Foo'); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $this->collectionPersister->expects($this->once()) ->method('count') @@ -177,47 +157,47 @@ public function testInvokeCount() $this->assertEquals(0, $persister->count($collection)); } - public function testInvokeSlice() + public function testInvokeSlice(): void { - $entity = new State("Foo"); + $entity = new State('Foo'); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); $slice = $this->createCollection($entity); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $this->collectionPersister->expects($this->once()) ->method('slice') ->with($this->equalTo($collection), $this->equalTo(1), $this->equalTo(2)) ->will($this->returnValue($slice)); - $this->assertEquals($slice, $persister->slice($collection, 1 , 2)); + $this->assertEquals($slice, $persister->slice($collection, 1, 2)); } - public function testInvokeContains() + public function testInvokeContains(): void { - $entity = new State("Foo"); - $element = new State("Bar"); + $entity = new State('Foo'); + $element = new State('Bar'); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $this->collectionPersister->expects($this->once()) ->method('contains') ->with($this->equalTo($collection), $this->equalTo($element)) ->will($this->returnValue(false)); - $this->assertFalse($persister->contains($collection,$element)); + $this->assertFalse($persister->contains($collection, $element)); } - public function testInvokeContainsKey() + public function testInvokeContainsKey(): void { - $entity = new State("Foo"); + $entity = new State('Foo'); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $this->collectionPersister->expects($this->once()) ->method('containsKey') @@ -227,14 +207,14 @@ public function testInvokeContainsKey() $this->assertFalse($persister->containsKey($collection, 0)); } - public function testInvokeGet() + public function testInvokeGet(): void { - $entity = new State("Foo"); - $element = new State("Bar"); + $entity = new State('Foo'); + $element = new State('Bar'); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $this->collectionPersister->expects($this->once()) ->method('get') diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersisterTest.php index bd65c20777f..3b70f774ad6 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersisterTest.php @@ -1,11 +1,13 @@ getMockBuilder(ConcurrentRegion::class) ->setMethods($this->regionMockMethods) ->getMock(); } - public function testDeleteShouldLockItem() + public function testDeleteShouldLockItem(): void { - $entity = new State("Foo"); + $entity = new State('Foo'); $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $key = new CollectionCacheKey(State::class, 'cities', ['id'=>1]); + $key = new CollectionCacheKey(State::class, 'cities', ['id' => 1]); $this->region->expects($this->once()) ->method('lock') ->with($this->equalTo($key)) ->will($this->returnValue($lock)); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $persister->delete($collection); } - public function testUpdateShouldLockItem() + public function testUpdateShouldLockItem(): void { - $entity = new State("Foo"); + $entity = new State('Foo'); $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $key = new CollectionCacheKey(State::class, 'cities', ['id'=>1]); + $key = new CollectionCacheKey(State::class, 'cities', ['id' => 1]); $this->region->expects($this->once()) ->method('lock') ->with($this->equalTo($key)) ->will($this->returnValue($lock)); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $persister->update($collection); } - public function testUpdateTransactionRollBackShouldEvictItem() + public function testUpdateTransactionRollBackShouldEvictItem(): void { - $entity = new State("Foo"); + $entity = new State('Foo'); $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $key = new CollectionCacheKey(State::class, 'cities', ['id'=>1]); + $key = new CollectionCacheKey(State::class, 'cities', ['id' => 1]); $this->region->expects($this->once()) ->method('lock') @@ -100,19 +100,19 @@ public function testUpdateTransactionRollBackShouldEvictItem() ->with($this->equalTo($key)) ->will($this->returnValue($lock)); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $persister->update($collection); $persister->afterTransactionRolledBack(); } - public function testDeleteTransactionRollBackShouldEvictItem() + public function testDeleteTransactionRollBackShouldEvictItem(): void { - $entity = new State("Foo"); + $entity = new State('Foo'); $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $key = new CollectionCacheKey(State::class, 'cities', ['id'=>1]); + $key = new CollectionCacheKey(State::class, 'cities', ['id' => 1]); $this->region->expects($this->once()) ->method('lock') @@ -123,20 +123,20 @@ public function testDeleteTransactionRollBackShouldEvictItem() ->method('evict') ->with($this->equalTo($key)); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $persister->delete($collection); $persister->afterTransactionRolledBack(); } - public function testTransactionRollBackDeleteShouldClearQueue() + public function testTransactionRollBackDeleteShouldClearQueue(): void { - $entity = new State("Foo"); + $entity = new State('Foo'); $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $key = new CollectionCacheKey(State::class, 'cities', ['id'=>1]); - $property = new \ReflectionProperty(ReadWriteCachedCollectionPersister::class, 'queuedCache'); + $key = new CollectionCacheKey(State::class, 'cities', ['id' => 1]); + $property = new ReflectionProperty(ReadWriteCachedCollectionPersister::class, 'queuedCache'); $property->setAccessible(true); @@ -149,7 +149,7 @@ public function testTransactionRollBackDeleteShouldClearQueue() ->method('evict') ->with($this->equalTo($key)); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $persister->delete($collection); @@ -160,14 +160,14 @@ public function testTransactionRollBackDeleteShouldClearQueue() $this->assertCount(0, $property->getValue($persister)); } - public function testTransactionRollBackUpdateShouldClearQueue() + public function testTransactionRollBackUpdateShouldClearQueue(): void { - $entity = new State("Foo"); + $entity = new State('Foo'); $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $key = new CollectionCacheKey(State::class, 'cities', ['id'=>1]); - $property = new \ReflectionProperty(ReadWriteCachedCollectionPersister::class, 'queuedCache'); + $key = new CollectionCacheKey(State::class, 'cities', ['id' => 1]); + $property = new ReflectionProperty(ReadWriteCachedCollectionPersister::class, 'queuedCache'); $property->setAccessible(true); @@ -180,7 +180,7 @@ public function testTransactionRollBackUpdateShouldClearQueue() ->method('evict') ->with($this->equalTo($key)); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $persister->update($collection); @@ -191,14 +191,14 @@ public function testTransactionRollBackUpdateShouldClearQueue() $this->assertCount(0, $property->getValue($persister)); } - public function testTransactionRollCommitDeleteShouldClearQueue() + public function testTransactionRollCommitDeleteShouldClearQueue(): void { - $entity = new State("Foo"); + $entity = new State('Foo'); $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $key = new CollectionCacheKey(State::class, 'cities', ['id'=>1]); - $property = new \ReflectionProperty(ReadWriteCachedCollectionPersister::class, 'queuedCache'); + $key = new CollectionCacheKey(State::class, 'cities', ['id' => 1]); + $property = new ReflectionProperty(ReadWriteCachedCollectionPersister::class, 'queuedCache'); $property->setAccessible(true); @@ -211,7 +211,7 @@ public function testTransactionRollCommitDeleteShouldClearQueue() ->method('evict') ->with($this->equalTo($key)); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $persister->delete($collection); @@ -222,14 +222,14 @@ public function testTransactionRollCommitDeleteShouldClearQueue() $this->assertCount(0, $property->getValue($persister)); } - public function testTransactionRollCommitUpdateShouldClearQueue() + public function testTransactionRollCommitUpdateShouldClearQueue(): void { - $entity = new State("Foo"); + $entity = new State('Foo'); $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $key = new CollectionCacheKey(State::class, 'cities', ['id'=>1]); - $property = new \ReflectionProperty(ReadWriteCachedCollectionPersister::class, 'queuedCache'); + $key = new CollectionCacheKey(State::class, 'cities', ['id' => 1]); + $property = new ReflectionProperty(ReadWriteCachedCollectionPersister::class, 'queuedCache'); $property->setAccessible(true); @@ -242,7 +242,7 @@ public function testTransactionRollCommitUpdateShouldClearQueue() ->method('evict') ->with($this->equalTo($key)); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $persister->update($collection); @@ -253,13 +253,13 @@ public function testTransactionRollCommitUpdateShouldClearQueue() $this->assertCount(0, $property->getValue($persister)); } - public function testDeleteLockFailureShouldIgnoreQueue() + public function testDeleteLockFailureShouldIgnoreQueue(): void { - $entity = new State("Foo"); + $entity = new State('Foo'); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $key = new CollectionCacheKey(State::class, 'cities', ['id'=>1]); - $property = new \ReflectionProperty(ReadWriteCachedCollectionPersister::class, 'queuedCache'); + $key = new CollectionCacheKey(State::class, 'cities', ['id' => 1]); + $property = new ReflectionProperty(ReadWriteCachedCollectionPersister::class, 'queuedCache'); $property->setAccessible(true); @@ -272,19 +272,19 @@ public function testDeleteLockFailureShouldIgnoreQueue() ->method('delete') ->with($this->equalTo($collection)); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $persister->delete($collection); $this->assertCount(0, $property->getValue($persister)); } - public function testUpdateLockFailureShouldIgnoreQueue() + public function testUpdateLockFailureShouldIgnoreQueue(): void { - $entity = new State("Foo"); + $entity = new State('Foo'); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $key = new CollectionCacheKey(State::class, 'cities', ['id'=>1]); - $property = new \ReflectionProperty(ReadWriteCachedCollectionPersister::class, 'queuedCache'); + $key = new CollectionCacheKey(State::class, 'cities', ['id' => 1]); + $property = new ReflectionProperty(ReadWriteCachedCollectionPersister::class, 'queuedCache'); $property->setAccessible(true); @@ -297,7 +297,7 @@ public function testUpdateLockFailureShouldIgnoreQueue() ->method('update') ->with($this->equalTo($collection)); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $persister->update($collection); $this->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 23c74027780..104c92bcabe 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/AbstractEntityPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/AbstractEntityPersisterTest.php @@ -1,10 +1,13 @@ getSharedSecondLevelCacheDriverImpl()->flushAll(); $this->enableSecondLevelCache(); @@ -56,23 +45,17 @@ protected function setUp() : void $this->entityPersister = $this->createMock(EntityPersister::class); } - /** - * @return \Doctrine\ORM\Cache\Region - */ - protected function createRegion() + protected function createRegion(): Region { return $this->createMock(Region::class); } - /** - * @return \Doctrine\ORM\Cache\Persister\AbstractEntityPersister - */ - protected function createPersisterDefault() + protected function createPersisterDefault(): \Doctrine\ORM\Cache\Persister\AbstractEntityPersister { return $this->createPersister($this->em, $this->entityPersister, $this->region, $this->em->getClassMetadata(Country::class)); } - public function testImplementsEntityPersister() + public function testImplementsEntityPersister(): void { $persister = $this->createPersisterDefault(); @@ -81,10 +64,10 @@ public function testImplementsEntityPersister() $this->assertInstanceOf(CachedEntityPersister::class, $persister); } - public function testInvokeAddInsert() + public function testInvokeAddInsert(): void { $persister = $this->createPersisterDefault(); - $entity = new Country("Foo"); + $entity = new Country('Foo'); $this->entityPersister->expects($this->once()) ->method('addInsert') @@ -93,10 +76,10 @@ public function testInvokeAddInsert() $this->assertNull($persister->addInsert($entity)); } - public function testInvokeGetInserts() + public function testInvokeGetInserts(): void { $persister = $this->createPersisterDefault(); - $entity = new Country("Foo"); + $entity = new Country('Foo'); $this->entityPersister->expects($this->once()) ->method('getInserts') @@ -105,23 +88,28 @@ public function testInvokeGetInserts() $this->assertEquals([$entity], $persister->getInserts()); } - public function testInvokeGetSelectSQL() + public function testInvokeGetSelectSQL(): void { $persister = $this->createPersisterDefault(); $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([0]), $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] + ['name' => 'Foo'], + [0], + 1, + 2, + 3, + [4] )); } - public function testInvokeGetInsertSQL() + public function testInvokeGetInsertSQL(): void { $persister = $this->createPersisterDefault(); @@ -132,19 +120,19 @@ public function testInvokeGetInsertSQL() $this->assertEquals('INSERT INTO foo (?)', $persister->getInsertSQL()); } - public function testInvokeExpandParameters() + public function testInvokeExpandParameters(): void { $persister = $this->createPersisterDefault(); $this->entityPersister->expects($this->once()) ->method('expandParameters') - ->with($this->equalTo(['name'=>'Foo'])) - ->will($this->returnValue(['name'=>'Foo'])); + ->with($this->equalTo(['name' => 'Foo'])) + ->will($this->returnValue(['name' => 'Foo'])); - $this->assertEquals(['name'=>'Foo'], $persister->expandParameters(['name'=>'Foo'])); + $this->assertEquals(['name' => 'Foo'], $persister->expandParameters(['name' => 'Foo'])); } - public function testInvokeExpandCriteriaParameters() + public function testInvokeExpandCriteriaParameters(): void { $persister = $this->createPersisterDefault(); $criteria = new Criteria(); @@ -152,12 +140,12 @@ public function testInvokeExpandCriteriaParameters() $this->entityPersister->expects($this->once()) ->method('expandCriteriaParameters') ->with($this->equalTo($criteria)) - ->will($this->returnValue(['name'=>'Foo'])); + ->will($this->returnValue(['name' => 'Foo'])); - $this->assertEquals(['name'=>'Foo'], $persister->expandCriteriaParameters($criteria)); + $this->assertEquals(['name' => 'Foo'], $persister->expandCriteriaParameters($criteria)); } - public function testInvokeSelectConditionStatementSQL() + public function testInvokeSelectConditionStatementSQL(): void { $persister = $this->createPersisterDefault(); @@ -169,7 +157,7 @@ public function testInvokeSelectConditionStatementSQL() $this->assertEquals('name = 1', $persister->getSelectConditionStatementSQL('id', 1, [], '=')); } - public function testInvokeExecuteInserts() + public function testInvokeExecuteInserts(): void { $persister = $this->createPersisterDefault(); @@ -180,35 +168,35 @@ public function testInvokeExecuteInserts() $this->assertEquals(['id' => 1], $persister->executeInserts()); } - public function testInvokeUpdate() + public function testInvokeUpdate(): void { $persister = $this->createPersisterDefault(); - $entity = new Country("Foo"); + $entity = new Country('Foo'); $this->entityPersister->expects($this->once()) ->method('update') ->with($this->equalTo($entity)); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $this->assertNull($persister->update($entity)); } - public function testInvokeDelete() + public function testInvokeDelete(): void { $persister = $this->createPersisterDefault(); - $entity = new Country("Foo"); + $entity = new Country('Foo'); $this->entityPersister->expects($this->once()) ->method('delete') ->with($this->equalTo($entity)); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $this->assertNull($persister->delete($entity)); } - public function testInvokeGetOwningTable() + public function testInvokeGetOwningTable(): void { $persister = $this->createPersisterDefault(); @@ -220,10 +208,10 @@ public function testInvokeGetOwningTable() $this->assertEquals('t', $persister->getOwningTable('name')); } - public function testInvokeLoad() + public function testInvokeLoad(): void { $persister = $this->createPersisterDefault(); - $entity = new Country("Foo"); + $entity = new Country('Foo'); $this->entityPersister->expects($this->once()) ->method('load') @@ -237,15 +225,15 @@ public function testInvokeLoad() $this->assertEquals($entity, $persister->load(['id' => 1], $entity, [0], [1], 2, 3, [4])); } - public function testInvokeLoadAll() + public function testInvokeLoadAll(): void { $rsm = new ResultSetMappingBuilder($this->em); $persister = $this->createPersisterDefault(); - $entity = new Country("Foo"); + $entity = new Country('Foo'); $rsm->addEntityResult(Country::class, 'c'); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $this->entityPersister->expects($this->once()) ->method('loadAll') @@ -259,10 +247,10 @@ public function testInvokeLoadAll() $this->assertEquals([$entity], $persister->loadAll(['id' => 1], [0], 1, 2)); } - public function testInvokeLoadById() + public function testInvokeLoadById(): void { $persister = $this->createPersisterDefault(); - $entity = new Country("Foo"); + $entity = new Country('Foo'); $this->entityPersister->expects($this->once()) ->method('loadById') @@ -272,10 +260,10 @@ public function testInvokeLoadById() $this->assertEquals($entity, $persister->loadById(['id' => 1], $entity)); } - public function testInvokeLoadOneToOneEntity() + public function testInvokeLoadOneToOneEntity(): void { $persister = $this->createPersisterDefault(); - $entity = new Country("Foo"); + $entity = new Country('Foo'); $this->entityPersister->expects($this->once()) ->method('loadOneToOneEntity') @@ -285,10 +273,10 @@ public function testInvokeLoadOneToOneEntity() $this->assertEquals($entity, $persister->loadOneToOneEntity([], 'foo', ['id' => 11])); } - public function testInvokeRefresh() + public function testInvokeRefresh(): void { $persister = $this->createPersisterDefault(); - $entity = new Country("Foo"); + $entity = new Country('Foo'); $this->entityPersister->expects($this->once()) ->method('refresh') @@ -298,14 +286,14 @@ public function testInvokeRefresh() $this->assertNull($persister->refresh(['id' => 1], $entity), 0); } - public function testInvokeLoadCriteria() + public function testInvokeLoadCriteria(): void { $rsm = new ResultSetMappingBuilder($this->em); $persister = $this->createPersisterDefault(); - $entity = new Country("Foo"); + $entity = new Country('Foo'); $criteria = new Criteria(); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $rsm->addEntityResult(Country::class, 'c'); $this->entityPersister->expects($this->once()) @@ -320,39 +308,39 @@ public function testInvokeLoadCriteria() $this->assertEquals([$entity], $persister->loadCriteria($criteria)); } - public function testInvokeGetManyToManyCollection() + public function testInvokeGetManyToManyCollection(): void { $persister = $this->createPersisterDefault(); - $entity = new Country("Foo"); + $entity = new Country('Foo'); $this->entityPersister->expects($this->once()) ->method('getManyToManyCollection') ->with($this->equalTo([]), $this->equalTo('Foo'), $this->equalTo(1), $this->equalTo(2)) ->will($this->returnValue([$entity])); - $this->assertEquals([$entity], $persister->getManyToManyCollection([], 'Foo', 1 ,2)); + $this->assertEquals([$entity], $persister->getManyToManyCollection([], 'Foo', 1, 2)); } - public function testInvokeGetOneToManyCollection() + public function testInvokeGetOneToManyCollection(): void { $persister = $this->createPersisterDefault(); - $entity = new Country("Foo"); + $entity = new Country('Foo'); $this->entityPersister->expects($this->once()) ->method('getOneToManyCollection') ->with($this->equalTo([]), $this->equalTo('Foo'), $this->equalTo(1), $this->equalTo(2)) ->will($this->returnValue([$entity])); - $this->assertEquals([$entity], $persister->getOneToManyCollection([], 'Foo', 1 ,2)); + $this->assertEquals([$entity], $persister->getOneToManyCollection([], 'Foo', 1, 2)); } - public function testInvokeLoadManyToManyCollection() + public function testInvokeLoadManyToManyCollection(): void { $mapping = $this->em->getClassMetadata(Country::class); $assoc = ['type' => 1]; $coll = new PersistentCollection($this->em, $mapping, new ArrayCollection()); $persister = $this->createPersisterDefault(); - $entity = new Country("Foo"); + $entity = new Country('Foo'); $this->entityPersister->expects($this->once()) ->method('loadManyToManyCollection') @@ -362,13 +350,13 @@ public function testInvokeLoadManyToManyCollection() $this->assertEquals([$entity], $persister->loadManyToManyCollection($assoc, 'Foo', $coll)); } - public function testInvokeLoadOneToManyCollection() + public function testInvokeLoadOneToManyCollection(): void { $mapping = $this->em->getClassMetadata(Country::class); $assoc = ['type' => 1]; $coll = new PersistentCollection($this->em, $mapping, new ArrayCollection()); $persister = $this->createPersisterDefault(); - $entity = new Country("Foo"); + $entity = new Country('Foo'); $this->entityPersister->expects($this->once()) ->method('loadOneToManyCollection') @@ -378,7 +366,7 @@ public function testInvokeLoadOneToManyCollection() $this->assertEquals([$entity], $persister->loadOneToManyCollection($assoc, 'Foo', $coll)); } - public function testInvokeLock() + public function testInvokeLock(): void { $identifier = ['id' => 1]; $persister = $this->createPersisterDefault(); @@ -390,9 +378,9 @@ public function testInvokeLock() $this->assertNull($persister->lock($identifier, 1)); } - public function testInvokeExists() + public function testInvokeExists(): void { - $entity = new Country("Foo"); + $entity = new Country('Foo'); $persister = $this->createPersisterDefault(); $this->entityPersister->expects($this->once()) diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersisterTest.php index 0f1e67b0f63..f73c11b328e 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersisterTest.php @@ -1,5 +1,7 @@ createPersisterDefault(); - $property = new \ReflectionProperty($persister, 'queuedCache'); + $property = new ReflectionProperty($persister, 'queuedCache'); $property->setAccessible(true); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $persister->update($entity); $persister->delete($entity); @@ -44,13 +47,13 @@ public function testTransactionRollBackShouldClearQueue() $this->assertCount(0, $property->getValue($persister)); } - public function testInsertTransactionCommitShouldPutCache() + public function testInsertTransactionCommitShouldPutCache(): void { - $entity = new Country("Foo"); + $entity = new Country('Foo'); $persister = $this->createPersisterDefault(); - $key = new EntityCacheKey(Country::class, ['id'=>1]); - $entry = new EntityCacheEntry(Country::class, ['id'=>1, 'name'=>'Foo']); - $property = new \ReflectionProperty($persister, 'queuedCache'); + $key = new EntityCacheKey(Country::class, ['id' => 1]); + $entry = new EntityCacheEntry(Country::class, ['id' => 1, 'name' => 'Foo']); + $property = new ReflectionProperty($persister, 'queuedCache'); $property->setAccessible(true); @@ -69,7 +72,7 @@ public function testInsertTransactionCommitShouldPutCache() $this->entityPersister->expects($this->once()) ->method('executeInserts'); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $persister->addInsert($entity); $persister->executeInserts(); @@ -81,13 +84,13 @@ public function testInsertTransactionCommitShouldPutCache() $this->assertCount(0, $property->getValue($persister)); } - public function testUpdateTransactionCommitShouldPutCache() + public function testUpdateTransactionCommitShouldPutCache(): void { - $entity = new Country("Foo"); + $entity = new Country('Foo'); $persister = $this->createPersisterDefault(); - $key = new EntityCacheKey(Country::class, ['id'=>1]); - $entry = new EntityCacheEntry(Country::class, ['id'=>1, 'name'=>'Foo']); - $property = new \ReflectionProperty($persister, 'queuedCache'); + $key = new EntityCacheKey(Country::class, ['id' => 1]); + $entry = new EntityCacheEntry(Country::class, ['id' => 1, 'name' => 'Foo']); + $property = new ReflectionProperty($persister, 'queuedCache'); $property->setAccessible(true); @@ -99,7 +102,7 @@ public function testUpdateTransactionCommitShouldPutCache() ->method('update') ->with($this->equalTo($entity)); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $persister->update($entity); @@ -110,12 +113,12 @@ public function testUpdateTransactionCommitShouldPutCache() $this->assertCount(0, $property->getValue($persister)); } - public function testDeleteTransactionCommitShouldEvictCache() + public function testDeleteTransactionCommitShouldEvictCache(): void { - $entity = new Country("Foo"); + $entity = new Country('Foo'); $persister = $this->createPersisterDefault(); - $key = new EntityCacheKey(Country::class, ['id'=>1]); - $property = new \ReflectionProperty($persister, 'queuedCache'); + $key = new EntityCacheKey(Country::class, ['id' => 1]); + $property = new ReflectionProperty($persister, 'queuedCache'); $property->setAccessible(true); @@ -127,7 +130,7 @@ public function testDeleteTransactionCommitShouldEvictCache() ->method('delete') ->with($this->equalTo($entity)); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $persister->delete($entity); diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadOnlyCachedEntityPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadOnlyCachedEntityPersisterTest.php index 2ab1e69cfbc..8cfdd42b289 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadOnlyCachedEntityPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadOnlyCachedEntityPersisterTest.php @@ -1,13 +1,15 @@ expectException('Doctrine\ORM\Cache\CacheException'); $this->expectExceptionMessage('Cannot update a readonly entity "Doctrine\Tests\Models\Cache\Country"'); $persister = $this->createPersisterDefault(); - $entity = new Country("Foo"); + $entity = new Country('Foo'); $persister->update($entity); } diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersisterTest.php index ee9d1433393..78fe89c5158 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersisterTest.php @@ -1,16 +1,19 @@ createMock(ConcurrentRegion::class); } - public function testDeleteShouldLockItem() + public function testDeleteShouldLockItem(): void { - $entity = new Country("Foo"); + $entity = new Country('Foo'); $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); - $key = new EntityCacheKey(Country::class, ['id'=>1]); + $key = new EntityCacheKey(Country::class, ['id' => 1]); $this->region->expects($this->once()) ->method('lock') ->with($this->equalTo($key)) ->will($this->returnValue($lock)); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $persister->delete($entity); } - public function testUpdateShouldLockItem() + public function testUpdateShouldLockItem(): void { - $entity = new Country("Foo"); + $entity = new Country('Foo'); $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); - $key = new EntityCacheKey(Country::class, ['id'=>1]); + $key = new EntityCacheKey(Country::class, ['id' => 1]); $this->region->expects($this->once()) ->method('lock') ->with($this->equalTo($key)) ->will($this->returnValue($lock)); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $persister->update($entity); } - public function testUpdateTransactionRollBackShouldEvictItem() + public function testUpdateTransactionRollBackShouldEvictItem(): void { - $entity = new Country("Foo"); + $entity = new Country('Foo'); $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); - $key = new EntityCacheKey(Country::class, ['id'=>1]); + $key = new EntityCacheKey(Country::class, ['id' => 1]); $this->region->expects($this->once()) ->method('lock') @@ -84,18 +84,18 @@ public function testUpdateTransactionRollBackShouldEvictItem() ->with($this->equalTo($key)) ->will($this->returnValue($lock)); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $persister->update($entity); $persister->afterTransactionRolledBack(); } - public function testDeleteTransactionRollBackShouldEvictItem() + public function testDeleteTransactionRollBackShouldEvictItem(): void { - $entity = new Country("Foo"); + $entity = new Country('Foo'); $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); - $key = new EntityCacheKey(Country::class, ['id'=>1]); + $key = new EntityCacheKey(Country::class, ['id' => 1]); $this->region->expects($this->once()) ->method('lock') @@ -106,19 +106,19 @@ public function testDeleteTransactionRollBackShouldEvictItem() ->method('evict') ->with($this->equalTo($key)); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $persister->delete($entity); $persister->afterTransactionRolledBack(); } - public function testTransactionRollBackShouldClearQueue() + public function testTransactionRollBackShouldClearQueue(): void { - $entity = new Country("Foo"); + $entity = new Country('Foo'); $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); - $key = new EntityCacheKey(Country::class, ['id'=>1]); - $property = new \ReflectionProperty(ReadWriteCachedEntityPersister::class, 'queuedCache'); + $key = new EntityCacheKey(Country::class, ['id' => 1]); + $property = new ReflectionProperty(ReadWriteCachedEntityPersister::class, 'queuedCache'); $property->setAccessible(true); @@ -131,7 +131,7 @@ public function testTransactionRollBackShouldClearQueue() ->method('evict') ->with($this->equalTo($key)); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $persister->update($entity); $persister->delete($entity); @@ -143,13 +143,13 @@ public function testTransactionRollBackShouldClearQueue() $this->assertCount(0, $property->getValue($persister)); } - public function testTransactionCommitShouldClearQueue() + public function testTransactionCommitShouldClearQueue(): void { - $entity = new Country("Foo"); + $entity = new Country('Foo'); $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); - $key = new EntityCacheKey(Country::class, ['id'=>1]); - $property = new \ReflectionProperty(ReadWriteCachedEntityPersister::class, 'queuedCache'); + $key = new EntityCacheKey(Country::class, ['id' => 1]); + $property = new ReflectionProperty(ReadWriteCachedEntityPersister::class, 'queuedCache'); $property->setAccessible(true); @@ -162,7 +162,7 @@ public function testTransactionCommitShouldClearQueue() ->method('evict') ->with($this->equalTo($key)); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $persister->update($entity); $persister->delete($entity); @@ -174,12 +174,12 @@ public function testTransactionCommitShouldClearQueue() $this->assertCount(0, $property->getValue($persister)); } - public function testDeleteLockFailureShouldIgnoreQueue() + public function testDeleteLockFailureShouldIgnoreQueue(): void { - $entity = new Country("Foo"); + $entity = new Country('Foo'); $persister = $this->createPersisterDefault(); - $key = new EntityCacheKey(Country::class, ['id'=>1]); - $property = new \ReflectionProperty(ReadWriteCachedEntityPersister::class, 'queuedCache'); + $key = new EntityCacheKey(Country::class, ['id' => 1]); + $property = new ReflectionProperty(ReadWriteCachedEntityPersister::class, 'queuedCache'); $property->setAccessible(true); @@ -192,18 +192,18 @@ public function testDeleteLockFailureShouldIgnoreQueue() ->method('delete') ->with($this->equalTo($entity)); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $persister->delete($entity); $this->assertCount(0, $property->getValue($persister)); } - public function testUpdateLockFailureShouldIgnoreQueue() + public function testUpdateLockFailureShouldIgnoreQueue(): void { - $entity = new Country("Foo"); + $entity = new Country('Foo'); $persister = $this->createPersisterDefault(); - $key = new EntityCacheKey(Country::class, ['id'=>1]); - $property = new \ReflectionProperty(ReadWriteCachedEntityPersister::class, 'queuedCache'); + $key = new EntityCacheKey(Country::class, ['id' => 1]); + $property = new ReflectionProperty(ReadWriteCachedEntityPersister::class, 'queuedCache'); $property->setAccessible(true); @@ -216,7 +216,7 @@ public function testUpdateLockFailureShouldIgnoreQueue() ->method('update') ->with($this->equalTo($entity)); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => 1], ['id' => 1, 'name' => 'Foo']); $persister->update($entity); $this->assertCount(0, $property->getValue($persister)); diff --git a/tests/Doctrine/Tests/ORM/Cache/StatisticsCacheLoggerTest.php b/tests/Doctrine/Tests/ORM/Cache/StatisticsCacheLoggerTest.php index f38767ac349..cfa8a3b4010 100644 --- a/tests/Doctrine/Tests/ORM/Cache/StatisticsCacheLoggerTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/StatisticsCacheLoggerTest.php @@ -1,32 +1,32 @@ logger = new StatisticsCacheLogger(); } - public function testEntityCache() + public function testEntityCache(): void { $name = 'my_entity_region'; $key = new EntityCacheKey(State::class, ['id' => 1]); @@ -43,7 +43,7 @@ public function testEntityCache() $this->assertEquals(1, $this->logger->getRegionMissCount($name)); } - public function testCollectionCache() + public function testCollectionCache(): void { $name = 'my_collection_region'; $key = new CollectionCacheKey(State::class, 'cities', ['id' => 1]); @@ -60,7 +60,7 @@ public function testCollectionCache() $this->assertEquals(1, $this->logger->getRegionMissCount($name)); } - public function testQueryCache() + public function testQueryCache(): void { $name = 'my_query_region'; $key = new QueryCacheKey('my_query_hash'); @@ -77,15 +77,15 @@ public function testQueryCache() $this->assertEquals(1, $this->logger->getRegionMissCount($name)); } - public function testMultipleCaches() + public function testMultipleCaches(): void { $coolRegion = 'my_collection_region'; $entityRegion = 'my_entity_region'; $queryRegion = 'my_query_region'; - $coolKey = new CollectionCacheKey(State::class, 'cities', ['id' => 1]); - $entityKey = new EntityCacheKey(State::class, ['id' => 1]); - $queryKey = new QueryCacheKey('my_query_hash'); + $coolKey = new CollectionCacheKey(State::class, 'cities', ['id' => 1]); + $entityKey = new EntityCacheKey(State::class, ['id' => 1]); + $queryKey = new QueryCacheKey('my_query_hash'); $this->logger->queryCacheHit($queryRegion, $queryKey); $this->logger->queryCachePut($queryRegion, $queryKey); diff --git a/tests/Doctrine/Tests/ORM/CommitOrderCalculatorTest.php b/tests/Doctrine/Tests/ORM/CommitOrderCalculatorTest.php index 6b149cd2ced..c263bc5b7b6 100644 --- a/tests/Doctrine/Tests/ORM/CommitOrderCalculatorTest.php +++ b/tests/Doctrine/Tests/ORM/CommitOrderCalculatorTest.php @@ -1,5 +1,7 @@ _calc = new CommitOrderCalculator(); } - public function testCommitOrdering1() + public function testCommitOrdering1(): void { $class1 = new ClassMetadata(NodeClass1::class); $class2 = new ClassMetadata(NodeClass2::class); @@ -49,7 +51,7 @@ public function testCommitOrdering1() $this->assertSame($correctOrder, $sorted); } - public function testCommitOrdering2() + public function testCommitOrdering2(): void { $class1 = new ClassMetadata(NodeClass1::class); $class2 = new ClassMetadata(NodeClass2::class); @@ -68,7 +70,7 @@ public function testCommitOrdering2() $this->assertSame($correctOrder, $sorted); } - public function testCommitOrdering3() + public function testCommitOrdering3(): void { // this test corresponds to the GH7259Test::testPersistFileBeforeVersion functional test $class1 = new ClassMetadata(NodeClass1::class); @@ -102,8 +104,18 @@ public function testCommitOrdering3() } } -class NodeClass1 {} -class NodeClass2 {} -class NodeClass3 {} -class NodeClass4 {} -class NodeClass5 {} +class NodeClass1 +{ +} +class NodeClass2 +{ +} +class NodeClass3 +{ +} +class NodeClass4 +{ +} +class NodeClass5 +{ +} diff --git a/tests/Doctrine/Tests/ORM/ConfigurationTest.php b/tests/Doctrine/Tests/ORM/ConfigurationTest.php index 13096dcc15a..4ec7145bb97 100644 --- a/tests/Doctrine/Tests/ORM/ConfigurationTest.php +++ b/tests/Doctrine/Tests/ORM/ConfigurationTest.php @@ -1,14 +1,16 @@ */ class ConfigurationTest extends TestCase { - /** - * @var Configuration - */ + /** @var Configuration */ private $configuration; - protected function setUp() : void + protected function setUp(): void { parent::setUp(); $this->configuration = new Configuration(); } - public function testSetGetProxyDir() + public function testSetGetProxyDir(): void { $this->assertSame(null, $this->configuration->getProxyDir()); // defaults @@ -44,7 +43,7 @@ public function testSetGetProxyDir() $this->assertSame(__DIR__, $this->configuration->getProxyDir()); } - public function testSetGetAutoGenerateProxyClasses() + public function testSetGetAutoGenerateProxyClasses(): void { $this->assertSame(AbstractProxyFactory::AUTOGENERATE_ALWAYS, $this->configuration->getAutoGenerateProxyClasses()); // defaults @@ -58,7 +57,7 @@ public function testSetGetAutoGenerateProxyClasses() $this->assertSame(AbstractProxyFactory::AUTOGENERATE_FILE_NOT_EXISTS, $this->configuration->getAutoGenerateProxyClasses()); } - public function testSetGetProxyNamespace() + public function testSetGetProxyNamespace(): void { $this->assertSame(null, $this->configuration->getProxyNamespace()); // defaults @@ -66,7 +65,7 @@ public function testSetGetProxyNamespace() $this->assertSame(__NAMESPACE__, $this->configuration->getProxyNamespace()); } - public function testSetGetMetadataDriverImpl() + public function testSetGetMetadataDriverImpl(): void { $this->assertSame(null, $this->configuration->getMetadataDriverImpl()); // defaults @@ -75,29 +74,29 @@ public function testSetGetMetadataDriverImpl() $this->assertSame($metadataDriver, $this->configuration->getMetadataDriverImpl()); } - public function testNewDefaultAnnotationDriver() + public function testNewDefaultAnnotationDriver(): void { - $paths = [__DIR__]; + $paths = [__DIR__]; $reflectionClass = new ReflectionClass(ConfigurationTestAnnotationReaderChecker::class); $annotationDriver = $this->configuration->newDefaultAnnotationDriver($paths, false); - $reader = $annotationDriver->getReader(); - $annotation = $reader->getMethodAnnotation( + $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( + $reader = $annotationDriver->getReader(); + $annotation = $reader->getMethodAnnotation( $reflectionClass->getMethod('simpleAnnotationMethod'), AnnotationNamespace\PrePersist::class ); $this->assertInstanceOf(AnnotationNamespace\PrePersist::class, $annotation); } - public function testSetGetEntityNamespace() + public function testSetGetEntityNamespace(): void { $this->configuration->addEntityNamespace('TestNamespace', __NAMESPACE__); $this->assertSame(__NAMESPACE__, $this->configuration->getEntityNamespace('TestNamespace')); @@ -108,7 +107,7 @@ public function testSetGetEntityNamespace() $this->configuration->getEntityNamespace('NonExistingNamespace'); } - public function testSetGetQueryCacheImpl() + public function testSetGetQueryCacheImpl(): void { $this->assertSame(null, $this->configuration->getQueryCacheImpl()); // defaults $queryCacheImpl = $this->createMock(Cache::class); @@ -116,7 +115,7 @@ public function testSetGetQueryCacheImpl() $this->assertSame($queryCacheImpl, $this->configuration->getQueryCacheImpl()); } - public function testSetGetHydrationCacheImpl() + public function testSetGetHydrationCacheImpl(): void { $this->assertSame(null, $this->configuration->getHydrationCacheImpl()); // defaults $queryCacheImpl = $this->createMock(Cache::class); @@ -124,7 +123,7 @@ public function testSetGetHydrationCacheImpl() $this->assertSame($queryCacheImpl, $this->configuration->getHydrationCacheImpl()); } - public function testSetGetMetadataCacheImpl() + public function testSetGetMetadataCacheImpl(): void { $this->assertSame(null, $this->configuration->getMetadataCacheImpl()); // defaults $queryCacheImpl = $this->createMock(Cache::class); @@ -132,7 +131,7 @@ public function testSetGetMetadataCacheImpl() $this->assertSame($queryCacheImpl, $this->configuration->getMetadataCacheImpl()); } - public function testAddGetNamedQuery() + public function testAddGetNamedQuery(): void { $dql = 'SELECT u FROM User u'; $this->configuration->addNamedQuery('QueryName', $dql); @@ -142,7 +141,7 @@ public function testAddGetNamedQuery() $this->configuration->getNamedQuery('NonExistingQuery'); } - public function testAddGetNamedNativeQuery() + public function testAddGetNamedNativeQuery(): void { $sql = 'SELECT * FROM user'; $rsm = $this->createMock(ResultSetMapping::class); @@ -160,22 +159,22 @@ public function testAddGetNamedNativeQuery() * * @param string $skipCache Do not configure a cache of this type, either "query" or "metadata". */ - protected function setProductionSettings($skipCache = false) + protected function setProductionSettings(string $skipCache = false): void { $this->configuration->setAutoGenerateProxyClasses(AbstractProxyFactory::AUTOGENERATE_NEVER); $cache = $this->createMock(Cache::class); - if ('query' !== $skipCache) { + if ($skipCache !== 'query') { $this->configuration->setQueryCacheImpl($cache); } - if ('metadata' !== $skipCache) { + if ($skipCache !== 'metadata') { $this->configuration->setMetadataCacheImpl($cache); } } - public function testEnsureProductionSettings() + public function testEnsureProductionSettings(): void { $this->setProductionSettings(); $this->configuration->ensureProductionSettings(); @@ -183,7 +182,7 @@ public function testEnsureProductionSettings() $this->addToAssertionCount(1); } - public function testEnsureProductionSettingsQueryCache() + public function testEnsureProductionSettingsQueryCache(): void { $this->setProductionSettings('query'); @@ -193,7 +192,7 @@ public function testEnsureProductionSettingsQueryCache() $this->configuration->ensureProductionSettings(); } - public function testEnsureProductionSettingsMetadataCache() + public function testEnsureProductionSettingsMetadataCache(): void { $this->setProductionSettings('metadata'); @@ -203,7 +202,7 @@ public function testEnsureProductionSettingsMetadataCache() $this->configuration->ensureProductionSettings(); } - public function testEnsureProductionSettingsQueryArrayCache() + public function testEnsureProductionSettingsQueryArrayCache(): void { $this->setProductionSettings(); $this->configuration->setQueryCacheImpl(new ArrayCache()); @@ -214,7 +213,7 @@ public function testEnsureProductionSettingsQueryArrayCache() $this->configuration->ensureProductionSettings(); } - public function testEnsureProductionSettingsMetadataArrayCache() + public function testEnsureProductionSettingsMetadataArrayCache(): void { $this->setProductionSettings(); $this->configuration->setMetadataCacheImpl(new ArrayCache()); @@ -225,7 +224,7 @@ public function testEnsureProductionSettingsMetadataArrayCache() $this->configuration->ensureProductionSettings(); } - public function testEnsureProductionSettingsAutoGenerateProxyClassesAlways() + public function testEnsureProductionSettingsAutoGenerateProxyClassesAlways(): void { $this->setProductionSettings(); $this->configuration->setAutoGenerateProxyClasses(AbstractProxyFactory::AUTOGENERATE_ALWAYS); @@ -236,7 +235,7 @@ public function testEnsureProductionSettingsAutoGenerateProxyClassesAlways() $this->configuration->ensureProductionSettings(); } - public function testEnsureProductionSettingsAutoGenerateProxyClassesFileNotExists() + public function testEnsureProductionSettingsAutoGenerateProxyClassesFileNotExists(): void { $this->setProductionSettings(); $this->configuration->setAutoGenerateProxyClasses(AbstractProxyFactory::AUTOGENERATE_FILE_NOT_EXISTS); @@ -247,7 +246,7 @@ public function testEnsureProductionSettingsAutoGenerateProxyClassesFileNotExist $this->configuration->ensureProductionSettings(); } - public function testEnsureProductionSettingsAutoGenerateProxyClassesEval() + public function testEnsureProductionSettingsAutoGenerateProxyClassesEval(): void { $this->setProductionSettings(); $this->configuration->setAutoGenerateProxyClasses(AbstractProxyFactory::AUTOGENERATE_EVAL); @@ -258,79 +257,77 @@ public function testEnsureProductionSettingsAutoGenerateProxyClassesEval() $this->configuration->ensureProductionSettings(); } - public function testAddGetCustomStringFunction() + public function testAddGetCustomStringFunction(): void { - $this->configuration->addCustomStringFunction('FunctionName', __CLASS__); - $this->assertSame(__CLASS__, $this->configuration->getCustomStringFunction('FunctionName')); + $this->configuration->addCustomStringFunction('FunctionName', self::class); + $this->assertSame(self::class, $this->configuration->getCustomStringFunction('FunctionName')); $this->assertSame(null, $this->configuration->getCustomStringFunction('NonExistingFunction')); - $this->configuration->setCustomStringFunctions(['OtherFunctionName' => __CLASS__]); - $this->assertSame(__CLASS__, $this->configuration->getCustomStringFunction('OtherFunctionName')); + $this->configuration->setCustomStringFunctions(['OtherFunctionName' => self::class]); + $this->assertSame(self::class, $this->configuration->getCustomStringFunction('OtherFunctionName')); } - public function testAddGetCustomNumericFunction() + public function testAddGetCustomNumericFunction(): void { - $this->configuration->addCustomNumericFunction('FunctionName', __CLASS__); - $this->assertSame(__CLASS__, $this->configuration->getCustomNumericFunction('FunctionName')); + $this->configuration->addCustomNumericFunction('FunctionName', self::class); + $this->assertSame(self::class, $this->configuration->getCustomNumericFunction('FunctionName')); $this->assertSame(null, $this->configuration->getCustomNumericFunction('NonExistingFunction')); - $this->configuration->setCustomNumericFunctions(['OtherFunctionName' => __CLASS__]); - $this->assertSame(__CLASS__, $this->configuration->getCustomNumericFunction('OtherFunctionName')); + $this->configuration->setCustomNumericFunctions(['OtherFunctionName' => self::class]); + $this->assertSame(self::class, $this->configuration->getCustomNumericFunction('OtherFunctionName')); } - public function testAddGetCustomDatetimeFunction() + public function testAddGetCustomDatetimeFunction(): void { - $this->configuration->addCustomDatetimeFunction('FunctionName', __CLASS__); - $this->assertSame(__CLASS__, $this->configuration->getCustomDatetimeFunction('FunctionName')); + $this->configuration->addCustomDatetimeFunction('FunctionName', self::class); + $this->assertSame(self::class, $this->configuration->getCustomDatetimeFunction('FunctionName')); $this->assertSame(null, $this->configuration->getCustomDatetimeFunction('NonExistingFunction')); - $this->configuration->setCustomDatetimeFunctions(['OtherFunctionName' => __CLASS__]); - $this->assertSame(__CLASS__, $this->configuration->getCustomDatetimeFunction('OtherFunctionName')); + $this->configuration->setCustomDatetimeFunctions(['OtherFunctionName' => self::class]); + $this->assertSame(self::class, $this->configuration->getCustomDatetimeFunction('OtherFunctionName')); } - public function testAddGetCustomHydrationMode() + public function testAddGetCustomHydrationMode(): void { $this->assertSame(null, $this->configuration->getCustomHydrationMode('NonExisting')); - $this->configuration->addCustomHydrationMode('HydrationModeName', __CLASS__); - $this->assertSame(__CLASS__, $this->configuration->getCustomHydrationMode('HydrationModeName')); + $this->configuration->addCustomHydrationMode('HydrationModeName', self::class); + $this->assertSame(self::class, $this->configuration->getCustomHydrationMode('HydrationModeName')); } - public function testSetCustomHydrationModes() + public function testSetCustomHydrationModes(): void { - $this->configuration->addCustomHydrationMode('HydrationModeName', __CLASS__); - $this->assertSame(__CLASS__, $this->configuration->getCustomHydrationMode('HydrationModeName')); + $this->configuration->addCustomHydrationMode('HydrationModeName', self::class); + $this->assertSame(self::class, $this->configuration->getCustomHydrationMode('HydrationModeName')); $this->configuration->setCustomHydrationModes( - [ - 'AnotherHydrationModeName' => __CLASS__ - ] + ['AnotherHydrationModeName' => self::class] ); $this->assertNull($this->configuration->getCustomHydrationMode('HydrationModeName')); - $this->assertSame(__CLASS__, $this->configuration->getCustomHydrationMode('AnotherHydrationModeName')); + $this->assertSame(self::class, $this->configuration->getCustomHydrationMode('AnotherHydrationModeName')); } - public function testSetGetClassMetadataFactoryName() + public function testSetGetClassMetadataFactoryName(): void { $this->assertSame(AnnotationNamespace\ClassMetadataFactory::class, $this->configuration->getClassMetadataFactoryName()); - $this->configuration->setClassMetadataFactoryName(__CLASS__); - $this->assertSame(__CLASS__, $this->configuration->getClassMetadataFactoryName()); + $this->configuration->setClassMetadataFactoryName(self::class); + $this->assertSame(self::class, $this->configuration->getClassMetadataFactoryName()); } - public function testAddGetFilters() + public function testAddGetFilters(): void { $this->assertSame(null, $this->configuration->getFilterClassName('NonExistingFilter')); - $this->configuration->addFilter('FilterName', __CLASS__); - $this->assertSame(__CLASS__, $this->configuration->getFilterClassName('FilterName')); + $this->configuration->addFilter('FilterName', self::class); + $this->assertSame(self::class, $this->configuration->getFilterClassName('FilterName')); } - public function setDefaultRepositoryClassName() + public function setDefaultRepositoryClassName(): void { $this->assertSame(EntityRepository::class, $this->configuration->getDefaultRepositoryClassName()); $this->configuration->setDefaultRepositoryClassName(DDC753CustomRepository::class); $this->assertSame(DDC753CustomRepository::class, $this->configuration->getDefaultRepositoryClassName()); $this->expectException(ORMException::class); - $this->configuration->setDefaultRepositoryClassName(__CLASS__); + $this->configuration->setDefaultRepositoryClassName(self::class); } - public function testSetGetNamingStrategy() + public function testSetGetNamingStrategy(): void { $this->assertInstanceOf(NamingStrategy::class, $this->configuration->getNamingStrategy()); $namingStrategy = $this->createMock(NamingStrategy::class); @@ -338,7 +335,7 @@ public function testSetGetNamingStrategy() $this->assertSame($namingStrategy, $this->configuration->getNamingStrategy()); } - public function testSetGetQuoteStrategy() + public function testSetGetQuoteStrategy(): void { $this->assertInstanceOf(QuoteStrategy::class, $this->configuration->getQuoteStrategy()); $quoteStrategy = $this->createMock(QuoteStrategy::class); @@ -349,7 +346,7 @@ public function testSetGetQuoteStrategy() /** * @group DDC-1955 */ - public function testSetGetEntityListenerResolver() + public function testSetGetEntityListenerResolver(): void { $this->assertInstanceOf(EntityListenerResolver::class, $this->configuration->getEntityListenerResolver()); $this->assertInstanceOf(AnnotationNamespace\DefaultEntityListenerResolver::class, $this->configuration->getEntityListenerResolver()); @@ -361,7 +358,7 @@ public function testSetGetEntityListenerResolver() /** * @group DDC-2183 */ - public function testSetGetSecondLevelCacheConfig() + public function testSetGetSecondLevelCacheConfig(): void { $mockClass = $this->createMock(CacheConfiguration::class); @@ -374,12 +371,12 @@ public function testSetGetSecondLevelCacheConfig() class ConfigurationTestAnnotationReaderChecker { /** @PrePersist */ - public function simpleAnnotationMethod() + public function simpleAnnotationMethod(): void { } /** @AnnotationNamespace\PrePersist */ - public function namespacedAnnotationMethod() + public function namespacedAnnotationMethod(): void { } } diff --git a/tests/Doctrine/Tests/ORM/Decorator/EntityManagerDecoratorTest.php b/tests/Doctrine/Tests/ORM/Decorator/EntityManagerDecoratorTest.php index cacf4b4ccec..59fda7b3b00 100644 --- a/tests/Doctrine/Tests/ORM/Decorator/EntityManagerDecoratorTest.php +++ b/tests/Doctrine/Tests/ORM/Decorator/EntityManagerDecoratorTest.php @@ -1,5 +1,7 @@ ignoreDeprecationMessage('The Doctrine\Common\Persistence\ObjectManagerDecorator class is deprecated since doctrine/persistence 1.3 and will be removed in 2.0. Use \Doctrine\Persistence\ObjectManagerDecorator instead.'); } - protected function setUp() : void + protected function setUp(): void { $this->wrapped = $this->createMock(EntityManagerInterface::class); } public function getMethodParameters() { - $class = new \ReflectionClass(EntityManagerInterface::class); + $class = new ReflectionClass(EntityManagerInterface::class); $methods = []; foreach ($class->getMethods() as $method) { - if ($method->isConstructor() || $method->isStatic() || !$method->isPublic()) { + if ($method->isConstructor() || $method->isStatic() || ! $method->isPublic()) { continue; } @@ -60,7 +65,7 @@ public function getMethodParameters() return $methods; } - private function getParameters(\ReflectionMethod $method) + private function getParameters(ReflectionMethod $method) { /** Special case EntityManager::createNativeQuery() */ if ($method->getName() === 'createNativeQuery') { @@ -75,7 +80,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') ?: []]; } @@ -85,9 +90,9 @@ private function getParameters(\ReflectionMethod $method) /** * @dataProvider getMethodParameters */ - public function testAllMethodCallsAreDelegatedToTheWrappedInstance($method, array $parameters) + public function testAllMethodCallsAreDelegatedToTheWrappedInstance($method, array $parameters): void { - $return = !in_array($method, self::VOID_METHODS) ? 'INNER VALUE FROM ' . $method : null; + $return = ! in_array($method, self::VOID_METHODS) ? 'INNER VALUE FROM ' . $method : null; $this->wrapped->expects($this->once()) ->method($method) @@ -101,6 +106,7 @@ public function testAllMethodCallsAreDelegatedToTheWrappedInstance($method, arra if (in_array($method, ['copy', 'merge', 'detach', 'getHydrator'], true)) { $this->assertHasDeprecationMessages(); + return; } diff --git a/tests/Doctrine/Tests/ORM/Entity/ConstructorTest.php b/tests/Doctrine/Tests/ORM/Entity/ConstructorTest.php index 117525eca32..f691b9492e0 100644 --- a/tests/Doctrine/Tests/ORM/Entity/ConstructorTest.php +++ b/tests/Doctrine/Tests/ORM/Entity/ConstructorTest.php @@ -1,15 +1,17 @@ assertEquals("romanb", $entity->username); + $entity = new ConstructorTestEntity1('romanb'); + $this->assertEquals('romanb', $entity->username); } } @@ -25,4 +27,3 @@ public function __construct($username = null) } } } - diff --git a/tests/Doctrine/Tests/ORM/EntityManagerTest.php b/tests/Doctrine/Tests/ORM/EntityManagerTest.php index e932ad82ea8..68fcff8e3f4 100644 --- a/tests/Doctrine/Tests/ORM/EntityManagerTest.php +++ b/tests/Doctrine/Tests/ORM/EntityManagerTest.php @@ -1,7 +1,10 @@ _em = $this->_getTestEntityManager(); @@ -40,46 +48,46 @@ protected function setUp() : void /** * @group DDC-899 */ - public function testIsOpen() + public function testIsOpen(): void { $this->assertTrue($this->_em->isOpen()); $this->_em->close(); $this->assertFalse($this->_em->isOpen()); } - public function testGetConnection() + public function testGetConnection(): void { $this->assertInstanceOf(Connection::class, $this->_em->getConnection()); } - public function testGetMetadataFactory() + public function testGetMetadataFactory(): void { $this->assertInstanceOf(ClassMetadataFactory::class, $this->_em->getMetadataFactory()); } - public function testGetConfiguration() + public function testGetConfiguration(): void { $this->assertInstanceOf(Configuration::class, $this->_em->getConfiguration()); } - public function testGetUnitOfWork() + public function testGetUnitOfWork(): void { $this->assertInstanceOf(UnitOfWork::class, $this->_em->getUnitOfWork()); } - public function testGetProxyFactory() + public function testGetProxyFactory(): void { $this->assertInstanceOf(ProxyFactory::class, $this->_em->getProxyFactory()); } - public function testGetEventManager() + public function testGetEventManager(): void { $this->assertInstanceOf(EventManager::class, $this->_em->getEventManager()); } - public function testCreateNativeQuery() + public function testCreateNativeQuery(): void { - $rsm = new ResultSetMapping(); + $rsm = new ResultSetMapping(); $query = $this->_em->createNativeQuery('SELECT foo', $rsm); $this->assertSame('SELECT foo', $query->getSql()); @@ -88,7 +96,7 @@ public function testCreateNativeQuery() /** * @covers \Doctrine\ORM\EntityManager::createNamedNativeQuery */ - public function testCreateNamedNativeQuery() + public function testCreateNamedNativeQuery(): void { $rsm = new ResultSetMapping(); $this->_em->getConfiguration()->addNamedNativeQuery('foo', 'SELECT foo', $rsm); @@ -98,14 +106,14 @@ public function testCreateNamedNativeQuery() $this->assertInstanceOf(NativeQuery::class, $query); } - public function testCreateQueryBuilder() + public function testCreateQueryBuilder(): void { $this->assertInstanceOf(QueryBuilder::class, $this->_em->createQueryBuilder()); } - public function testCreateQueryBuilderAliasValid() + public function testCreateQueryBuilderAliasValid(): void { - $q = $this->_em->createQueryBuilder() + $q = $this->_em->createQueryBuilder() ->select('u')->from(CmsUser::class, 'u'); $q2 = clone $q; @@ -117,12 +125,12 @@ public function testCreateQueryBuilderAliasValid() $this->assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', $q3->getQuery()->getDql()); } - public function testCreateQuery_DqlIsOptional() + public function testCreateQuery_DqlIsOptional(): void { $this->assertInstanceOf(Query::class, $this->_em->createQuery()); } - public function testGetPartialReference() + public function testGetPartialReference(): void { $user = $this->_em->getPartialReference(CmsUser::class, 42); $this->assertTrue($this->_em->contains($user)); @@ -130,7 +138,7 @@ public function testGetPartialReference() $this->assertNull($user->getName()); } - public function testCreateQuery() + public function testCreateQuery(): void { $q = $this->_em->createQuery('SELECT 1'); $this->assertInstanceOf(Query::class, $q); @@ -140,7 +148,7 @@ public function testCreateQuery() /** * @covers Doctrine\ORM\EntityManager::createNamedQuery */ - public function testCreateNamedQuery() + public function testCreateNamedQuery(): void { $this->_em->getConfiguration()->addNamedQuery('foo', 'SELECT 1'); @@ -149,28 +157,29 @@ public function testCreateNamedQuery() $this->assertEquals('SELECT 1', $query->getDql()); } - static public function dataMethodsAffectedByNoObjectArguments() + public static function dataMethodsAffectedByNoObjectArguments() { return [ ['persist'], ['remove'], ['merge'], ['refresh'], - ['detach'] + ['detach'], ]; } /** * @dataProvider dataMethodsAffectedByNoObjectArguments */ - public function testThrowsExceptionOnNonObjectValues($methodName) { + public function testThrowsExceptionOnNonObjectValues($methodName): void + { $this->expectException(ORMInvalidArgumentException::class); $this->expectExceptionMessage('EntityManager#' . $methodName . '() expects parameter 1 to be an entity object, NULL given.'); $this->_em->$methodName(null); } - static public function dataAffectedByErrorIfClosedException() + public static function dataAffectedByErrorIfClosedException() { return [ ['flush'], @@ -183,37 +192,36 @@ static public function dataAffectedByErrorIfClosedException() /** * @dataProvider dataAffectedByErrorIfClosedException - * @param string $methodName */ - public function testAffectedByErrorIfClosedException($methodName) + public function testAffectedByErrorIfClosedException(string $methodName): void { $this->expectException(ORMException::class); $this->expectExceptionMessage('closed'); $this->_em->close(); - $this->_em->$methodName(new \stdClass()); + $this->_em->$methodName(new stdClass()); } /** * @group DDC-1125 */ - public function testTransactionalAcceptsReturn() + public function testTransactionalAcceptsReturn(): void { - $return = $this->_em->transactional(function ($em) { + $return = $this->_em->transactional(static function ($em) { return 'foo'; }); $this->assertEquals('foo', $return); } - public function testTransactionalAcceptsVariousCallables() + public function testTransactionalAcceptsVariousCallables(): void { $this->assertSame('callback', $this->_em->transactional([$this, 'transactionalCallback'])); } - public function testTransactionalThrowsInvalidArgumentExceptionIfNonCallablePassed() + public function testTransactionalThrowsInvalidArgumentExceptionIfNonCallablePassed(): void { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Expected argument of type "callable", got "object"'); $this->_em->transactional($this); @@ -222,12 +230,13 @@ public function testTransactionalThrowsInvalidArgumentExceptionIfNonCallablePass public function transactionalCallback($em) { $this->assertSame($this->_em, $em); + return 'callback'; } - public function testCreateInvalidConnection() + public function testCreateInvalidConnection(): void { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid $connection argument of type integer given: "1".'); $config = new Configuration(); @@ -238,17 +247,17 @@ public function testCreateInvalidConnection() /** * @group #5796 */ - public function testTransactionalReThrowsThrowables() + public function testTransactionalReThrowsThrowables(): void { try { - $this->_em->transactional(function () { - (function (array $value) { + $this->_em->transactional(static function (): void { + (static function (array $value): void { // this only serves as an IIFE that throws a `TypeError` })(null); }); self::fail('TypeError expected to be thrown'); - } catch (\TypeError $ignored) { + } catch (TypeError $ignored) { self::assertFalse($this->_em->isOpen()); } } @@ -256,7 +265,7 @@ public function testTransactionalReThrowsThrowables() /** * @group 6017 */ - public function testClearManagerWithObject() + public function testClearManagerWithObject(): void { $entity = new Country(456, 'United Kingdom'); @@ -268,7 +277,7 @@ public function testClearManagerWithObject() /** * @group 6017 */ - public function testClearManagerWithUnknownEntityName() + public function testClearManagerWithUnknownEntityName(): void { $this->expectException(MappingException::class); @@ -278,7 +287,7 @@ public function testClearManagerWithUnknownEntityName() /** * @group 6017 */ - public function testClearManagerWithProxyClassName() + public function testClearManagerWithProxyClassName(): void { $proxy = $this->_em->getReference(Country::class, ['id' => random_int(457, 100000)]); @@ -296,7 +305,7 @@ public function testClearManagerWithProxyClassName() /** * @group 6017 */ - public function testClearManagerWithNullValue() + public function testClearManagerWithNullValue(): void { $entity = new Country(456, 'United Kingdom'); @@ -309,7 +318,7 @@ public function testClearManagerWithNullValue() $this->assertFalse($this->_em->contains($entity)); } - public function testDeprecatedClearWithArguments() : void + public function testDeprecatedClearWithArguments(): void { $entity = new Country(456, 'United Kingdom'); $this->_em->persist($entity); @@ -318,7 +327,7 @@ public function testDeprecatedClearWithArguments() : void $this->_em->clear(Country::class); } - public function testDeprecatedFlushWithArguments() : void + public function testDeprecatedFlushWithArguments(): void { $entity = new Country(456, 'United Kingdom'); $this->_em->persist($entity); @@ -327,7 +336,7 @@ public function testDeprecatedFlushWithArguments() : void $this->_em->flush($entity); } - public function testDeprecatedMerge() : void + public function testDeprecatedMerge(): void { $entity = new Country(456, 'United Kingdom'); $this->_em->persist($entity); @@ -336,7 +345,7 @@ public function testDeprecatedMerge() : void $this->_em->merge($entity); } - public function testDeprecatedDetach() : void + public function testDeprecatedDetach(): void { $entity = new Country(456, 'United Kingdom'); $this->_em->persist($entity); @@ -345,7 +354,7 @@ public function testDeprecatedDetach() : void $this->_em->detach($entity); } - public function testDeprecatedCopy() : void + public function testDeprecatedCopy(): void { $entity = new Country(456, 'United Kingdom'); $this->_em->persist($entity); @@ -353,7 +362,7 @@ public function testDeprecatedCopy() : void try { $this->expectDeprecationMessageSame('Method Doctrine\ORM\EntityManager::copy() is deprecated and will be removed in Doctrine ORM 3.0.'); $this->_em->copy($entity); - } catch (\BadMethodCallException $e) { + } catch (BadMethodCallException $e) { // do nothing } } diff --git a/tests/Doctrine/Tests/ORM/EntityNotFoundExceptionTest.php b/tests/Doctrine/Tests/ORM/EntityNotFoundExceptionTest.php index ec1cfbfc99c..3a8f6dd5c9a 100644 --- a/tests/Doctrine/Tests/ORM/EntityNotFoundExceptionTest.php +++ b/tests/Doctrine/Tests/ORM/EntityNotFoundExceptionTest.php @@ -1,5 +1,7 @@ createMock(ObjectManager::class); + assert($objectManager instanceof ObjectManager); $args = new OnClassMetadataNotFoundEventArgs('foo', $objectManager); @@ -26,8 +30,8 @@ public function testEventArgsMutability() $this->assertNull($args->getFoundMetadata()); - /** @var ClassMetadata $metadata */ $metadata = $this->createMock(ClassMetadata::class); + assert($metadata instanceof ClassMetadata); $args->setFoundMetadata($metadata); diff --git a/tests/Doctrine/Tests/ORM/Functional/AbstractManyToManyAssociationTestCase.php b/tests/Doctrine/Tests/ORM/Functional/AbstractManyToManyAssociationTestCase.php index 26445c1417a..2b58602daad 100644 --- a/tests/Doctrine/Tests/ORM/Functional/AbstractManyToManyAssociationTestCase.php +++ b/tests/Doctrine/Tests/ORM/Functional/AbstractManyToManyAssociationTestCase.php @@ -1,10 +1,14 @@ assertEquals(1, $this->_countForeignKeys($firstId, $secondId)); } - public function assertForeignKeysNotContain($firstId, $secondId) + public function assertForeignKeysNotContain($firstId, $secondId): void { $this->assertEquals(0, $this->_countForeignKeys($firstId, $secondId)); } @@ -31,12 +35,13 @@ protected function _countForeignKeys($firstId, $secondId) FROM {$this->_table} WHERE {$this->_firstField} = ? AND {$this->_secondField} = ? - ", [$firstId, $secondId] - )->fetchAll()); + ", [$firstId, $secondId])->fetchAll()); } public function assertCollectionEquals(Collection $first, Collection $second) { - return $first->forAll(function($k, $e) use($second) { return $second->contains($e); }); + return $first->forAll(static function ($k, $e) use ($second) { + return $second->contains($e); + }); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/AdvancedAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/AdvancedAssociationTest.php index b3bcc7ffc27..64ab4d792df 100644 --- a/tests/Doctrine/Tests/ORM/Functional/AdvancedAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/AdvancedAssociationTest.php @@ -1,50 +1,55 @@ _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) + $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) { + } catch (Exception $e) { // Swallow all exceptions. We do not test the schema tool here. } } - public function testIssue() + public function testIssue(): void { //setup - $phrase = new Phrase; + $phrase = new Phrase(); $phrase->setPhrase('lalala'); - $type = new PhraseType; + $type = new PhraseType(); $type->setType('nonsense'); $type->setAbbreviation('non'); - $def1 = new Definition; + $def1 = new Definition(); $def1->setDefinition('def1'); - $def2 = new Definition; + $def2 = new Definition(); $def2->setDefinition('def2'); $phrase->setType($type); @@ -65,8 +70,8 @@ public function testIssue() $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"); - $res = $query->getResult(); + $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()); @@ -79,8 +84,8 @@ public function testIssue() $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"); - $res = $query->getResult(); + $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()); @@ -89,7 +94,7 @@ public function testIssue() $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]); @@ -97,8 +102,8 @@ public function testIssue() $this->_em->clear(); // test4 - lazy-loading after DQL query - $query = $this->_em->createQuery("SELECT p FROM Doctrine\Tests\ORM\Functional\Phrase p"); - $res = $query->getResult(); + $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)); @@ -111,9 +116,9 @@ public function testIssue() IterableTester::assertResultsAreTheSame($query); } - public function testManyToMany() + public function testManyToMany(): void { - $lemma = new Lemma; + $lemma = new Lemma(); $lemma->setLemma('abu'); $type = new Type(); @@ -127,8 +132,8 @@ public function testManyToMany() $this->_em->flush(); // test5 ManyToMany - $query = $this->_em->createQuery("SELECT l FROM Doctrine\Tests\ORM\Functional\Lemma l"); - $res = $query->getResult(); + $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]); @@ -143,79 +148,65 @@ public function testManyToMany() * @Entity * @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 +{ + public const CLASS_NAME = self::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(); + } + + public function getId(): int + { + return $this->id; + } + + public function setLemma(string $lemma): void + { + $this->lemma = $lemma; + } + + public function getLemma(): string + { + return $this->lemma; + } + + /** * @param kateglo\application\models\Type $type - * @return void */ - public function addType(Type $type){ - if (!$this->types->contains($type)) { + public function addType(Type $type): void + { + if (! $this->types->contains($type)) { $this->types[] = $type; $type->addLemma($this); } } /** - * * @param kateglo\application\models\Type $type - * @return void */ - public function removeType(Type $type) + public function removeType(Type $type): void { $removed = $this->sources->removeElement($type); if ($removed !== null) { @@ -223,11 +214,7 @@ public function removeType(Type $type) } } - /** - * - * @return kateglo\application\helpers\collections\ArrayCollection - */ - public function getTypes() + public function getTypes(): kateglo\application\helpers\collections\ArrayCollection { return $this->types; } @@ -237,124 +224,96 @@ public function getTypes() * @Entity * @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 +{ + public const CLASS_NAME = self::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(); + } + + public function getId(): int + { + return $this->id; + } + + public function setType(string $type): void + { + $this->type = $type; + } + + public function getType(): string + { + return $this->type; + } + + public function setAbbreviation(string $abbreviation): void + { + $this->abbreviation = $abbreviation; + } + + public function getAbbreviation(): string + { + return $this->abbreviation; + } + + /** + * @param kateglo\application\models\Lemma $lemma + */ + public function addLemma(Lemma $lemma): void + { + if (! $this->lemmas->contains($lemma)) { + $this->lemmas[] = $lemma; + $lemma->addType($this); + } + } + + /** + * @param kateglo\application\models\Lemma $lemma + */ + public function removeLEmma(Lemma $lemma): void + { + $removed = $this->lemmas->removeElement($lemma); + if ($removed !== null) { + $removed->removeType($this); + } + } + public function getCategories(): kateglo\application\helpers\collections\ArrayCollection + { + return $this->categories; + } } @@ -362,9 +321,9 @@ public function getCategories() * @Entity * @Table(name="phrase") */ -class Phrase { - - const CLASS_NAME = __CLASS__; +class Phrase +{ + public const CLASS_NAME = self::class; /** * @Id @@ -373,9 +332,7 @@ class Phrase { */ private $id; - /** - * @Column(type="string", name="phrase_name", unique=true, length=255) - */ + /** @Column(type="string", name="phrase_name", unique=true, length=255) */ private $phrase; /** @@ -384,69 +341,47 @@ class Phrase { */ private $type; - /** - * @OneToMany(targetEntity="Definition", mappedBy="phrase", cascade={"persist"}) - */ + /** @OneToMany(targetEntity="Definition", mappedBy="phrase", cascade={"persist"}) */ private $definitions; - public function __construct() { - $this->definitions = new ArrayCollection; + public function __construct() + { + $this->definitions = new ArrayCollection(); } - /** - * - * @param Definition $definition - * @return void - */ - public function addDefinition(Definition $definition){ + public function addDefinition(Definition $definition): void + { $this->definitions[] = $definition; $definition->setPhrase($this); } - /** - * @return int - */ - public function getId(){ + public function getId(): int + { return $this->id; } - /** - * @param string $phrase - * @return void - */ - public function setPhrase($phrase){ + public function setPhrase(string $phrase): void + { $this->phrase = $phrase; } - /** - * @return string - */ - public function getPhrase(){ + public function getPhrase(): string + { return $this->phrase; } - /** - * - * @param PhraseType $type - * @return void - */ - public function setType(PhraseType $type){ + public function setType(PhraseType $type): void + { $this->type = $type; } - /** - * - * @return PhraseType - */ - public function getType(){ + public function getType(): PhraseType + { return $this->type; } - /** - * - * @return ArrayCollection - */ - public function getDefinitions(){ + public function getDefinitions(): ArrayCollection + { return $this->definitions; } } @@ -455,9 +390,9 @@ public function getDefinitions(){ * @Entity * @Table(name="phrase_type") */ -class PhraseType { - - const CLASS_NAME = __CLASS__; +class PhraseType +{ + public const CLASS_NAME = self::class; /** * @Id @@ -466,87 +401,63 @@ class PhraseType { */ private $id; - /** - * @Column(type="string", name="phrase_type_name", unique=true) - */ + /** @Column(type="string", name="phrase_type_name", unique=true) */ private $type; - /** - * @Column(type="string", name="phrase_type_abbreviation", unique=true) - */ + /** @Column(type="string", name="phrase_type_abbreviation", unique=true) */ private $abbreviation; - /** - * @OneToMany(targetEntity="Phrase", mappedBy="type") - */ + /** @OneToMany(targetEntity="Phrase", mappedBy="type") */ private $phrases; - public function __construct() { - $this->phrases = new ArrayCollection; + public function __construct() + { + $this->phrases = new ArrayCollection(); } - /** - * @return int - */ - public function getId(){ + public function getId(): int + { return $this->id; } - /** - * @param string $type - * @return void - */ - public function setType($type){ + public function setType(string $type): void + { $this->type = $type; } - /** - * @return string - */ - public function getType(){ + public function getType(): string + { return $this->type; } - /** - * @param string $abbreviation - * @return void - */ - public function setAbbreviation($abbreviation){ + public function setAbbreviation(string $abbreviation): void + { $this->abbreviation = $abbreviation; } - /** - * @return string - */ - public function getAbbreviation(){ + public function getAbbreviation(): string + { return $this->abbreviation; } - /** - * @param ArrayCollection $phrases - * @return void - */ - public function setPhrases($phrases){ + public function setPhrases(ArrayCollection $phrases): void + { $this->phrases = $phrases; } - /** - * - * @return ArrayCollection - */ - public function getPhrases(){ + public function getPhrases(): ArrayCollection + { return $this->phrases; } - } /** * @Entity * @Table(name="definition") */ -class Definition { - - const CLASS_NAME = __CLASS__; +class Definition +{ + public const CLASS_NAME = self::class; /** * @Id @@ -561,54 +472,41 @@ class Definition { */ private $phrase; - /** - * @Column(type="text", name="definition_text") - */ + /** @Column(type="text", name="definition_text") */ private $definition; - /** - * @return int - */ - public function getId(){ + public function getId(): int + { return $this->id; } - /** - * @param Phrase $phrase - * @return void - */ - public function setPhrase(Phrase $phrase){ + public function setPhrase(Phrase $phrase): void + { $this->phrase = $phrase; } - /** - * @return Phrase - */ - public function getPhrase(){ + public function getPhrase(): Phrase + { return $this->phrase; } - public function removePhrase() { + public function removePhrase(): void + { if ($this->phrase !== null) { - /*@var $phrase kateglo\application\models\Phrase */ $phrase = $this->phrase; + assert($phrase instanceof kateglo\application\models\Phrase); $this->phrase = null; $phrase->removeDefinition($this); } } - /** - * @param string $definition - * @return void - */ - public function setDefinition($definition){ + public function setDefinition(string $definition): void + { $this->definition = $definition; } - /** - * @return string - */ - public function getDefinition(){ + public function getDefinition(): string + { return $this->definition; } } diff --git a/tests/Doctrine/Tests/ORM/Functional/AdvancedDqlQueryTest.php b/tests/Doctrine/Tests/ORM/Functional/AdvancedDqlQueryTest.php index dee98d876d3..b04dd011769 100644 --- a/tests/Doctrine/Tests/ORM/Functional/AdvancedDqlQueryTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/AdvancedDqlQueryTest.php @@ -1,22 +1,23 @@ */ class AdvancedDqlQueryTest extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { $this->useModelSet('company'); parent::setUp(); @@ -24,10 +25,10 @@ protected function setUp() : void $this->generateFixture(); } - public function testAggregateWithHavingClause() + public function testAggregateWithHavingClause(): void { - $dql = 'SELECT p.department, AVG(p.salary) AS avgSalary '. - 'FROM Doctrine\Tests\Models\Company\CompanyEmployee p '. + $dql = 'SELECT p.department, AVG(p.salary) AS avgSalary ' . + '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(); @@ -39,7 +40,7 @@ public function testAggregateWithHavingClause() $this->assertEquals(600000, $result[1]['avgSalary']); } - public function testCommentsInDQL() + public function testCommentsInDQL(): void { //same test than testAggregateWithHavingClause but with comments into the DQL $dql = "SELECT p.department, AVG(p.salary) AS avgSalary -- comment end of line @@ -57,10 +58,10 @@ public function testCommentsInDQL() $this->assertEquals(600000, $result[1]['avgSalary']); } - public function testUnnamedScalarResultsAreOneBased() + public function testUnnamedScalarResultsAreOneBased(): void { - $dql = 'SELECT p.department, AVG(p.salary) '. - 'FROM Doctrine\Tests\Models\Company\CompanyEmployee p '. + $dql = 'SELECT p.department, AVG(p.salary) ' . + '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(); @@ -70,7 +71,7 @@ public function testUnnamedScalarResultsAreOneBased() $this->assertEquals(600000, $result[1][1]); } - public function testOrderByResultVariableCollectionSize() + public function testOrderByResultVariableCollectionSize(): void { $dql = 'SELECT p.name, size(p.friends) AS friends ' . 'FROM Doctrine\Tests\Models\Company\CompanyPerson p ' . @@ -81,7 +82,7 @@ public function testOrderByResultVariableCollectionSize() $this->assertEquals(4, count($result)); - $this->assertEquals("Jonathan W.", $result[0]['name']); + $this->assertEquals('Jonathan W.', $result[0]['name']); $this->assertEquals(3, $result[0]['friends']); $this->assertEquals('Guilherme B.', $result[1]['name']); @@ -94,7 +95,7 @@ public function testOrderByResultVariableCollectionSize() $this->assertEquals(1, $result[3]['friends']); } - public function testOrderBySimpleCaseExpression() : void + public function testOrderBySimpleCaseExpression(): void { $dql = <<<'DQL' SELECT p.name @@ -117,7 +118,7 @@ public function testOrderBySimpleCaseExpression() : void self::assertEquals('Jonathan W.', $result[3]['name']); } - public function testOrderByGeneralCaseExpression() : void + public function testOrderByGeneralCaseExpression(): void { $dql = <<<'DQL' SELECT p.name @@ -140,7 +141,7 @@ public function testOrderByGeneralCaseExpression() : void self::assertEquals('Jonathan W.', $result[3]['name']); } - public function testIsNullAssociation() + public function testIsNullAssociation(): void { $dql = 'SELECT p FROM Doctrine\Tests\Models\Company\CompanyPerson p ' . 'WHERE p.spouse IS NULL'; @@ -159,7 +160,7 @@ public function testIsNullAssociation() IterableTester::assertResultsAreTheSame($query); } - public function testSelectSubselect() + public function testSelectSubselect(): void { $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'; @@ -167,14 +168,14 @@ public function testSelectSubselect() $result = $query->getArrayResult(); $this->assertEquals(1, count($result)); - $this->assertEquals("Caramba", $result[0]['brandName']); + $this->assertEquals('Caramba', $result[0]['brandName']); $this->_em->clear(); IterableTester::assertResultsAreTheSame($query); } - public function testInSubselect() + public function testInSubselect(): void { $dql = <<_em->createQuery($dql)->execute(); @@ -220,18 +221,18 @@ public function testUpdateAs() IterableTester::assertResultsAreTheSame($query); } - public function testDeleteAs() + public function testDeleteAs(): void { $dql = 'DELETE Doctrine\Tests\Models\Company\CompanyEmployee AS p'; $this->_em->createQuery($dql)->getResult(); - $dql = 'SELECT count(p) FROM Doctrine\Tests\Models\Company\CompanyEmployee p'; + $dql = 'SELECT count(p) FROM Doctrine\Tests\Models\Company\CompanyEmployee p'; $result = $this->_em->createQuery($dql)->getSingleScalarResult(); $this->assertEquals(0, $result); } - public function generateFixture() + public function generateFixture(): void { $car = new CompanyCar('Caramba'); diff --git a/tests/Doctrine/Tests/ORM/Functional/BasicFunctionalTest.php b/tests/Doctrine/Tests/ORM/Functional/BasicFunctionalTest.php index a928e18b34b..de42a6f5983 100644 --- a/tests/Doctrine/Tests/ORM/Functional/BasicFunctionalTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/BasicFunctionalTest.php @@ -1,5 +1,7 @@ useModelSet('cms'); parent::setUp(); } - public function testBasicUnitsOfWorkWithOneToManyAssociation() + public function testBasicUnitsOfWorkWithOneToManyAssociation(): void { // Create - $user = new CmsUser; - $user->name = 'Roman'; + $user = new CmsUser(); + $user->name = 'Roman'; $user->username = 'romanb'; - $user->status = 'developer'; + $user->status = 'developer'; $this->_em->persist($user); $this->_em->flush(); @@ -48,8 +56,8 @@ public function testBasicUnitsOfWorkWithOneToManyAssociation() $this->assertTrue($user === $user2); // Add a phonenumber - $ph = new CmsPhonenumber; - $ph->phonenumber = "12345"; + $ph = new CmsPhonenumber(); + $ph->phonenumber = '12345'; $user->addPhonenumber($ph); $this->_em->flush(); $this->assertTrue($this->_em->contains($ph)); @@ -61,8 +69,8 @@ public function testBasicUnitsOfWorkWithOneToManyAssociation() $this->assertEquals('guilherme', $user->name); // Add another phonenumber - $ph2 = new CmsPhonenumber; - $ph2->phonenumber = "6789"; + $ph2 = new CmsPhonenumber(); + $ph2->phonenumber = '6789'; $user->addPhonenumber($ph2); $this->_em->flush(); $this->assertTrue($this->_em->contains($ph2)); @@ -81,17 +89,17 @@ public function testBasicUnitsOfWorkWithOneToManyAssociation() $this->assertEquals(UnitOfWork::STATE_NEW, $this->_em->getUnitOfWork()->getEntityState($ph2)); } - public function testOneToManyAssociationModification() + public function testOneToManyAssociationModification(): void { - $user = new CmsUser; - $user->name = 'Roman'; + $user = new CmsUser(); + $user->name = 'Roman'; $user->username = 'romanb'; - $user->status = 'developer'; + $user->status = 'developer'; - $ph1 = new CmsPhonenumber; - $ph1->phonenumber = "0301234"; - $ph2 = new CmsPhonenumber; - $ph2->phonenumber = "987654321"; + $ph1 = new CmsPhonenumber(); + $ph1->phonenumber = '0301234'; + $ph2 = new CmsPhonenumber(); + $ph2->phonenumber = '987654321'; $user->addPhonenumber($ph1); $user->addPhonenumber($ph2); @@ -109,18 +117,18 @@ public function testOneToManyAssociationModification() $this->assertNull($ph1->user); } - public function testBasicOneToOne() + public function testBasicOneToOne(): void { //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $user = new CmsUser; - $user->name = 'Roman'; + $user = new CmsUser(); + $user->name = 'Roman'; $user->username = 'romanb'; - $user->status = 'developer'; + $user->status = 'developer'; - $address = new CmsAddress; + $address = new CmsAddress(); $address->country = 'Germany'; - $address->city = 'Berlin'; - $address->zip = '12345'; + $address->city = 'Berlin'; + $address->zip = '12345'; $user->address = $address; // inverse side $address->user = $user; // owning side! @@ -130,7 +138,8 @@ public function testBasicOneToOne() // Check that the foreign key has been set $userId = $this->_em->getConnection()->executeQuery( - "SELECT user_id FROM cms_addresses WHERE id=?", [$address->id] + 'SELECT user_id FROM cms_addresses WHERE id=?', + [$address->id] )->fetchColumn(); $this->assertTrue(is_numeric($userId)); @@ -148,22 +157,22 @@ public function testBasicOneToOne() /** * @group DDC-1230 */ - public function testRemove() + public function testRemove(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; - $this->assertEquals(UnitOfWork::STATE_NEW, $this->_em->getUnitOfWork()->getEntityState($user), "State should be UnitOfWork::STATE_NEW"); + $this->assertEquals(UnitOfWork::STATE_NEW, $this->_em->getUnitOfWork()->getEntityState($user), 'State should be UnitOfWork::STATE_NEW'); $this->_em->persist($user); - $this->assertEquals(UnitOfWork::STATE_MANAGED, $this->_em->getUnitOfWork()->getEntityState($user), "State should be UnitOfWork::STATE_MANAGED"); + $this->assertEquals(UnitOfWork::STATE_MANAGED, $this->_em->getUnitOfWork()->getEntityState($user), 'State should be UnitOfWork::STATE_MANAGED'); $this->_em->remove($user); - $this->assertEquals(UnitOfWork::STATE_NEW, $this->_em->getUnitOfWork()->getEntityState($user), "State should be UnitOfWork::STATE_NEW"); + $this->assertEquals(UnitOfWork::STATE_NEW, $this->_em->getUnitOfWork()->getEntityState($user), 'State should be UnitOfWork::STATE_NEW'); $this->_em->persist($user); $this->_em->flush(); @@ -171,23 +180,23 @@ public function testRemove() $this->_em->remove($user); - $this->assertEquals(UnitOfWork::STATE_REMOVED, $this->_em->getUnitOfWork()->getEntityState($user), "State should be UnitOfWork::STATE_REMOVED"); + $this->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"); + $this->assertEquals(UnitOfWork::STATE_NEW, $this->_em->getUnitOfWork()->getEntityState($user), 'State should be UnitOfWork::STATE_NEW'); $this->assertNull($this->_em->find(CmsUser::class, $id)); } - public function testOneToManyOrphanRemoval() + public function testOneToManyOrphanRemoval(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; - for ($i=0; $i<3; ++$i) { - $phone = new CmsPhonenumber; + for ($i = 0; $i < 3; ++$i) { + $phone = new CmsPhonenumber(); $phone->phonenumber = 100 + $i; $user->addPhonenumber($phone); } @@ -202,25 +211,25 @@ public function testOneToManyOrphanRemoval() $this->_em->flush(); // Check that there are just 2 phonenumbers left - $count = $this->_em->getConnection()->fetchColumn("SELECT COUNT(*) FROM cms_phonenumbers"); + $count = $this->_em->getConnection()->fetchColumn('SELECT COUNT(*) FROM cms_phonenumbers'); $this->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->assertEquals(0, $this->_em->getConnection()->fetchColumn('select count(*) from cms_phonenumbers')); } - public function testBasicQuery() + public function testBasicQuery(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; $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(); @@ -252,32 +261,32 @@ public function testBasicQuery() $this->assertEquals('developer', $usersScalar[0]['u_status']); } - public function testBasicOneToManyInnerJoin() + public function testBasicOneToManyInnerJoin(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; $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)); } - public function testBasicOneToManyLeftJoin() + public function testBasicOneToManyLeftJoin(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; $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(); @@ -290,12 +299,12 @@ public function testBasicOneToManyLeftJoin() $this->assertEquals(0, $users[0]->phonenumbers->count()); } - public function testBasicRefresh() + public function testBasicRefresh(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; $this->_em->persist($user); $this->_em->flush(); @@ -310,21 +319,21 @@ public function testBasicRefresh() /** * @group DDC-833 */ - public function testRefreshResetsCollection() + public function testRefreshResetsCollection(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; // Add a phonenumber - $ph1 = new CmsPhonenumber; - $ph1->phonenumber = "12345"; + $ph1 = new CmsPhonenumber(); + $ph1->phonenumber = '12345'; $user->addPhonenumber($ph1); // Add a phonenumber - $ph2 = new CmsPhonenumber; - $ph2->phonenumber = "54321"; + $ph2 = new CmsPhonenumber(); + $ph2->phonenumber = '54321'; $this->_em->persist($user); $this->_em->persist($ph1); @@ -342,21 +351,21 @@ public function testRefreshResetsCollection() /** * @group DDC-833 */ - public function testDqlRefreshResetsCollection() + public function testDqlRefreshResetsCollection(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; // Add a phonenumber - $ph1 = new CmsPhonenumber; - $ph1->phonenumber = "12345"; + $ph1 = new CmsPhonenumber(); + $ph1->phonenumber = '12345'; $user->addPhonenumber($ph1); // Add a phonenumber - $ph2 = new CmsPhonenumber; - $ph2->phonenumber = "54321"; + $ph2 = new CmsPhonenumber(); + $ph2->phonenumber = '54321'; $this->_em->persist($user); $this->_em->persist($ph1); @@ -366,7 +375,7 @@ public function testDqlRefreshResetsCollection() $user->addPhonenumber($ph2); $this->assertEquals(2, count($user->phonenumbers)); - $dql = "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1"; + $dql = 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1'; $user = $this->_em->createQuery($dql) ->setParameter(1, $user->id) ->setHint(Query::HINT_REFRESH, true) @@ -378,21 +387,21 @@ public function testDqlRefreshResetsCollection() /** * @group DDC-833 */ - public function testCreateEntityOfProxy() + public function testCreateEntityOfProxy(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; // Add a phonenumber - $ph1 = new CmsPhonenumber; - $ph1->phonenumber = "12345"; + $ph1 = new CmsPhonenumber(); + $ph1->phonenumber = '12345'; $user->addPhonenumber($ph1); // Add a phonenumber - $ph2 = new CmsPhonenumber; - $ph2->phonenumber = "54321"; + $ph2 = new CmsPhonenumber(); + $ph2->phonenumber = '54321'; $this->_em->persist($user); $this->_em->persist($ph1); @@ -401,9 +410,9 @@ public function testCreateEntityOfProxy() $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"; + $dql = 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1'; $user = $this->_em->createQuery($dql) ->setParameter(1, $userId) ->getSingleResult(); @@ -411,15 +420,15 @@ public function testCreateEntityOfProxy() $this->assertEquals(1, count($user->phonenumbers)); } - public function testAddToCollectionDoesNotInitialize() + public function testAddToCollectionDoesNotInitialize(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; - for ($i=0; $i<3; ++$i) { - $phone = new CmsPhonenumber; + for ($i = 0; $i < 3; ++$i) { + $phone = new CmsPhonenumber(); $phone->phonenumber = 100 + $i; $user->addPhonenumber($phone); } @@ -436,7 +445,7 @@ public function testAddToCollectionDoesNotInitialize() $this->assertFalse($gblanco->getPhonenumbers()->isInitialized()); - $newPhone = new CmsPhonenumber; + $newPhone = new CmsPhonenumber(); $newPhone->phonenumber = 555; $gblanco->addPhonenumber($newPhone); @@ -446,20 +455,20 @@ public function testAddToCollectionDoesNotInitialize() $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 testInitializeCollectionWithNewObjectsRetainsNewObjects() + public function testInitializeCollectionWithNewObjectsRetainsNewObjects(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; - for ($i=0; $i<3; ++$i) { - $phone = new CmsPhonenumber; + for ($i = 0; $i < 3; ++$i) { + $phone = new CmsPhonenumber(); $phone->phonenumber = 100 + $i; $user->addPhonenumber($phone); } @@ -476,7 +485,7 @@ public function testInitializeCollectionWithNewObjectsRetainsNewObjects() $this->assertFalse($gblanco->getPhonenumbers()->isInitialized()); - $newPhone = new CmsPhonenumber; + $newPhone = new CmsPhonenumber(); $newPhone->phonenumber = 555; $gblanco->addPhonenumber($newPhone); @@ -487,23 +496,23 @@ public function testInitializeCollectionWithNewObjectsRetainsNewObjects() $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() + public function testSetSetAssociationWithGetReference(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; $this->_em->persist($user); - $address = new CmsAddress; + $address = new CmsAddress(); $address->country = 'Germany'; - $address->city = 'Berlin'; - $address->zip = '12345'; + $address->city = 'Berlin'; + $address->zip = '12345'; $this->_em->persist($address); $this->_em->flush(); @@ -522,24 +531,23 @@ public function testSetSetAssociationWithGetReference() $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'"); + $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()); - } - public function testOneToManyCascadeRemove() + public function testOneToManyCascadeRemove(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; - for ($i=0; $i<3; ++$i) { - $phone = new CmsPhonenumber; + for ($i = 0; $i < 3; ++$i) { + $phone = new CmsPhonenumber(); $phone->phonenumber = 100 + $i; $user->addPhonenumber($phone); } @@ -548,7 +556,7 @@ public function testOneToManyCascadeRemove() $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); @@ -557,26 +565,28 @@ public function testOneToManyCascadeRemove() $this->_em->clear(); $this->assertEquals(0, $this->_em->createQuery( - "select count(p.phonenumber) from Doctrine\Tests\Models\CMS\CmsPhonenumber p") + 'select count(p.phonenumber) from Doctrine\Tests\Models\CMS\CmsPhonenumber p' + ) ->getSingleScalarResult()); $this->assertEquals(0, $this->_em->createQuery( - "select count(u.id) from Doctrine\Tests\Models\CMS\CmsUser u") + 'select count(u.id) from Doctrine\Tests\Models\CMS\CmsUser u' + ) ->getSingleScalarResult()); } - public function testTextColumnSaveAndRetrieve() + public function testTextColumnSaveAndRetrieve(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; $this->_em->persist($user); - $article = new CmsArticle(); - $article->text = "Lorem ipsum dolor sunt."; - $article->topic = "A Test Article!"; + $article = new CmsArticle(); + $article->text = 'Lorem ipsum dolor sunt.'; + $article->topic = 'A Test Article!'; $article->setAuthor($user); $this->_em->persist($article); @@ -588,38 +598,38 @@ public function testTextColumnSaveAndRetrieve() // 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); + $this->assertEquals('Lorem ipsum dolor sunt.', $articleNew->text); $this->assertNotSame($article, $articleNew); - $articleNew->text = "Lorem ipsum dolor sunt. And stuff!"; + $articleNew->text = 'Lorem ipsum dolor sunt. And stuff!'; $this->_em->flush(); $this->_em->clear(); $articleNew = $this->_em->find(CmsArticle::class, $articleId); - $this->assertEquals("Lorem ipsum dolor sunt. And stuff!", $articleNew->text); + $this->assertEquals('Lorem ipsum dolor sunt. And stuff!', $articleNew->text); $this->assertTrue($this->_em->contains($articleNew)); } - public function testFlushDoesNotIssueUnnecessaryUpdates() + public function testFlushDoesNotIssueUnnecessaryUpdates(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; - $address = new CmsAddress; + $address = new CmsAddress(); $address->country = 'Germany'; - $address->city = 'Berlin'; - $address->zip = '12345'; + $address->city = 'Berlin'; + $address->zip = '12345'; $address->user = $user; $user->address = $address; - $article = new CmsArticle(); - $article->text = "Lorem ipsum dolor sunt."; - $article->topic = "A Test Article!"; + $article = new CmsArticle(); + $article->text = 'Lorem ipsum dolor sunt.'; + $article->topic = 'A Test Article!'; $article->setAuthor($user); $this->_em->persist($article); @@ -636,7 +646,7 @@ public function testFlushDoesNotIssueUnnecessaryUpdates() $this->assertEquals(1, count($user2->articles)); $this->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); @@ -646,12 +656,12 @@ public function testFlushDoesNotIssueUnnecessaryUpdates() $this->_em->getConnection()->getConfiguration()->setSQLLogger($oldLogger); } - public function testRemoveEntityByReference() + public function testRemoveEntityByReference(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); @@ -664,33 +674,33 @@ public function testRemoveEntityByReference() $this->_em->flush(); $this->_em->clear(); - $this->assertEquals(0, $this->_em->getConnection()->fetchColumn("select count(*) from cms_users")); + $this->assertEquals(0, $this->_em->getConnection()->fetchColumn('select count(*) from cms_users')); //$this->_em->getConnection()->getConfiguration()->setSQLLogger(null); } - public function testQueryEntityByReference() + public function testQueryEntityByReference(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; - $address = new CmsAddress; + $address = new CmsAddress(); $address->country = 'Germany'; - $address->city = 'Berlin'; - $address->zip = '12345'; + $address->city = 'Berlin'; + $address->zip = '12345'; $user->setAddress($address); - $this->_em->transactional(function($em) use($user) { + $this->_em->transactional(static function ($em) use ($user): void { $em->persist($user); }); $this->_em->clear(); //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $userRef = $this->_em->getReference(CmsUser::class, $user->getId()); + $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(); @@ -703,54 +713,54 @@ public function testQueryEntityByReference() $this->assertEquals('12345', $address2->zip); } - public function testOneToOneNullUpdate() + public function testOneToOneNullUpdate(): void { - $user = new CmsUser(); - $user->username = "beberlei"; - $user->name = "Benjamin E."; - $user->status = 'active'; - - $address = new CmsAddress(); - $address->city = "Bonn"; - $address->zip = "12354"; - $address->country = "Germany"; - $address->street = "somestreet"; - $address->user = $user; + $user = new CmsUser(); + $user->username = 'beberlei'; + $user->name = 'Benjamin E.'; + $user->status = 'active'; + + $address = new CmsAddress(); + $address->city = 'Bonn'; + $address->zip = '12354'; + $address->country = 'Germany'; + $address->street = 'somestreet'; + $address->user = $user; $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)); + $this->assertEquals(1, $this->_em->getConnection()->fetchColumn('select 1 from cms_addresses where user_id = ' . $user->id)); $address->user = null; $this->_em->flush(); - $this->assertNotEquals(1, $this->_em->getConnection()->fetchColumn("select 1 from cms_addresses where user_id = ".$user->id)); + $this->assertNotEquals(1, $this->_em->getConnection()->fetchColumn('select 1 from cms_addresses where user_id = ' . $user->id)); } /** * @group DDC-600 * @group DDC-455 */ - public function testNewAssociatedEntityDuringFlushThrowsException() + public function testNewAssociatedEntityDuringFlushThrowsException(): void { - $user = new CmsUser(); - $user->username = "beberlei"; - $user->name = "Benjamin E."; - $user->status = 'active'; - - $address = new CmsAddress(); - $address->city = "Bonn"; - $address->zip = "12354"; - $address->country = "Germany"; - $address->street = "somestreet"; - $address->user = $user; + $user = new CmsUser(); + $user->username = 'beberlei'; + $user->name = 'Benjamin E.'; + $user->status = 'active'; + + $address = new CmsAddress(); + $address->city = 'Bonn'; + $address->zip = '12354'; + $address->country = 'Germany'; + $address->street = 'somestreet'; + $address->user = $user; $this->_em->persist($address); // flushing without persisting $user should raise an exception - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->_em->flush(); } @@ -758,32 +768,32 @@ public function testNewAssociatedEntityDuringFlushThrowsException() * @group DDC-600 * @group DDC-455 */ - public function testNewAssociatedEntityDuringFlushThrowsException2() + public function testNewAssociatedEntityDuringFlushThrowsException2(): void { - $user = new CmsUser(); - $user->username = "beberlei"; - $user->name = "Benjamin E."; - $user->status = 'active'; - - $address = new CmsAddress(); - $address->city = "Bonn"; - $address->zip = "12354"; - $address->country = "Germany"; - $address->street = "somestreet"; - $address->user = $user; + $user = new CmsUser(); + $user->username = 'beberlei'; + $user->name = 'Benjamin E.'; + $user->status = 'active'; + + $address = new CmsAddress(); + $address->city = 'Bonn'; + $address->zip = '12354'; + $address->country = 'Germany'; + $address->street = 'somestreet'; + $address->user = $user; $this->_em->persist($address); $this->_em->persist($user); $this->_em->flush(); - $u2 = new CmsUser; - $u2->username = "beberlei"; - $u2->name = "Benjamin E."; - $u2->status = 'inactive'; + $u2 = new CmsUser(); + $u2->username = 'beberlei'; + $u2->name = 'Benjamin E.'; + $u2->status = 'inactive'; $address->user = $u2; // flushing without persisting $u2 should raise an exception - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->_em->flush(); } @@ -791,38 +801,38 @@ public function testNewAssociatedEntityDuringFlushThrowsException2() * @group DDC-600 * @group DDC-455 */ - public function testNewAssociatedEntityDuringFlushThrowsException3() + public function testNewAssociatedEntityDuringFlushThrowsException3(): void { - $art = new CmsArticle(); + $art = new CmsArticle(); $art->topic = 'topic'; - $art->text = 'the text'; + $art->text = 'the text'; - $com = new CmsComment(); + $com = new CmsComment(); $com->topic = 'Good'; - $com->text = 'Really good!'; + $com->text = 'Really good!'; $art->addComment($com); $this->_em->persist($art); // flushing without persisting $com should raise an exception - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->_em->flush(); } - public function testOneToOneOrphanRemoval() + public function testOneToOneOrphanRemoval(): void { - $user = new CmsUser(); - $user->username = "beberlei"; - $user->name = "Benjamin E."; - $user->status = 'active'; - - $address = new CmsAddress(); - $address->city = "Bonn"; - $address->zip = "12354"; - $address->country = "Germany"; - $address->street = "somestreet"; - $address->user = $user; - $user->address = $address; + $user = new CmsUser(); + $user->username = 'beberlei'; + $user->name = 'Benjamin E.'; + $user->status = 'active'; + + $address = new CmsAddress(); + $address->city = 'Bonn'; + $address->zip = '12354'; + $address->country = 'Germany'; + $address->street = 'somestreet'; + $address->user = $user; + $user->address = $address; $this->_em->persist($address); $this->_em->persist($user); @@ -833,37 +843,37 @@ public function testOneToOneOrphanRemoval() $this->_em->flush(); - $this->assertEquals(0, $this->_em->getConnection()->fetchColumn("select count(*) from cms_addresses")); + $this->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->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(); - $newAddress = new CmsAddress(); - $newAddress->city = "NewBonn"; - $newAddress->zip = "12354"; - $newAddress->country = "NewGermany"; - $newAddress->street = "somenewstreet"; - $newAddress->user = $user; - $user->address = $newAddress; + $newAddress = new CmsAddress(); + $newAddress->city = 'NewBonn'; + $newAddress->zip = '12354'; + $newAddress->country = 'NewGermany'; + $newAddress->street = 'somenewstreet'; + $newAddress->user = $user; + $user->address = $newAddress; $this->_em->flush(); - $this->assertEquals(1, $this->_em->getConnection()->fetchColumn("select count(*) from cms_addresses")); + $this->assertEquals(1, $this->_em->getConnection()->fetchColumn('select count(*) from cms_addresses')); } - public function testGetPartialReferenceToUpdateObjectWithoutLoadingIt() + public function testGetPartialReferenceToUpdateObjectWithoutLoadingIt(): void { - $user = new CmsUser(); - $user->username = "beberlei"; - $user->name = "Benjamin E."; - $user->status = 'active'; + $user = new CmsUser(); + $user->username = 'beberlei'; + $user->name = 'Benjamin E.'; + $user->status = 'active'; $this->_em->persist($user); $this->_em->flush(); $userId = $user->id; @@ -881,12 +891,12 @@ public function testGetPartialReferenceToUpdateObjectWithoutLoadingIt() $this->assertEquals('Benjamin E.', $this->_em->find(get_class($user), $userId)->name); } - public function testMergePersistsNewEntities() + public function testMergePersistsNewEntities(): void { - $user = new CmsUser(); - $user->username = "beberlei"; - $user->name = "Benjamin E."; - $user->status = 'active'; + $user = new CmsUser(); + $user->username = 'beberlei'; + $user->name = 'Benjamin E.'; + $user->status = 'active'; $managedUser = $this->_em->merge($user); $this->assertEquals('beberlei', $managedUser->username); @@ -905,13 +915,13 @@ public function testMergePersistsNewEntities() $this->assertHasDeprecationMessages(); } - public function testMergeNonPersistedProperties() + public function testMergeNonPersistedProperties(): void { - $user = new CmsUser(); - $user->username = "beberlei"; - $user->name = "Benjamin E."; - $user->status = 'active'; - $user->nonPersistedProperty = 'test'; + $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); @@ -933,13 +943,13 @@ public function testMergeNonPersistedProperties() $this->assertHasDeprecationMessages(); } - public function testMergeThrowsExceptionIfEntityWithGeneratedIdentifierDoesNotExist() + public function testMergeThrowsExceptionIfEntityWithGeneratedIdentifierDoesNotExist(): void { - $user = new CmsUser(); - $user->username = "beberlei"; - $user->name = "Benjamin E."; - $user->status = 'active'; - $user->id = 42; + $user = new CmsUser(); + $user->username = 'beberlei'; + $user->name = 'Benjamin E.'; + $user->status = 'active'; + $user->id = 42; $this->expectException(EntityNotFoundException::class); $this->_em->merge($user); @@ -949,15 +959,15 @@ public function testMergeThrowsExceptionIfEntityWithGeneratedIdentifierDoesNotEx /** * @group DDC-634 */ - public function testOneToOneMergeSetNull() + public function testOneToOneMergeSetNull(): void { - $user = new CmsUser(); - $user->username = "beberlei"; - $user->name = "Benjamin E."; - $user->status = 'active'; + $user = new CmsUser(); + $user->username = 'beberlei'; + $user->name = 'Benjamin E.'; + $user->status = 'active'; - $ph = new CmsPhonenumber(); - $ph->phonenumber = "12345"; + $ph = new CmsPhonenumber(); + $ph->phonenumber = '12345'; $user->addPhonenumber($ph); $this->_em->persist($user); @@ -966,7 +976,7 @@ public function testOneToOneMergeSetNull() $this->_em->clear(); - $ph->user = null; + $ph->user = null; $managedPh = $this->_em->merge($ph); $this->_em->flush(); @@ -979,59 +989,59 @@ public function testOneToOneMergeSetNull() /** * @group DDC-952 */ - public function testManyToOneFetchModeQuery() + public function testManyToOneFetchModeQuery(): void { - $user = new CmsUser(); - $user->username = "beberlei"; - $user->name = "Benjamin E."; - $user->status = 'active'; + $user = new CmsUser(); + $user->username = 'beberlei'; + $user->name = 'Benjamin E.'; + $user->status = 'active'; - $article = new CmsArticle(); - $article->topic = "foo"; - $article->text = "bar"; - $article->user = $user; + $article = new CmsArticle(); + $article->topic = 'foo'; + $article->text = 'bar'; + $article->user = $user; $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"; + $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()); + $this->assertInstanceOf(Proxy::class, $article->user, 'It IS a proxy, ...'); + $this->assertTrue($article->user->__isInitialized__, '...but its initialized!'); + $this->assertEquals($qc + 2, $this->getCurrentQueryCount()); } /** * @group DDC-1278 */ - public function testClearWithEntityName() + public function testClearWithEntityName(): void { - $user = new CmsUser; - $user->name = 'Dominik'; + $user = new CmsUser(); + $user->name = 'Dominik'; $user->username = 'domnikl'; - $user->status = 'developer'; + $user->status = 'developer'; - $address = new CmsAddress(); - $address->city = "Springfield"; - $address->zip = "12354"; - $address->country = "Germany"; - $address->street = "Foo Street"; - $address->user = $user; - $user->address = $address; + $address = new CmsAddress(); + $address->city = 'Springfield'; + $address->zip = '12354'; + $address->country = 'Germany'; + $address->street = 'Foo Street'; + $address->user = $user; + $user->address = $address; - $article1 = new CmsArticle(); + $article1 = new CmsArticle(); $article1->topic = 'Foo'; - $article1->text = 'Foo Text'; + $article1->text = 'Foo Text'; - $article2 = new CmsArticle(); + $article2 = new CmsArticle(); $article2->topic = 'Bar'; - $article2->text = 'Bar Text'; + $article2->text = 'Bar Text'; $user->addArticle($article1); $user->addArticle($article2); @@ -1056,19 +1066,19 @@ public function testClearWithEntityName() $this->assertEquals(UnitOfWork::STATE_DETACHED, $unitOfWork->getEntityState($address)); } - public function testFlushManyExplicitEntities() + public function testFlushManyExplicitEntities(): void { - $userA = new CmsUser; + $userA = new CmsUser(); $userA->username = 'UserA'; - $userA->name = 'UserA'; + $userA->name = 'UserA'; - $userB = new CmsUser; + $userB = new CmsUser(); $userB->username = 'UserB'; - $userB->name = 'UserB'; + $userB->name = 'UserB'; - $userC = new CmsUser; + $userC = new CmsUser(); $userC->username = 'UserC'; - $userC->name = 'UserC'; + $userC->name = 'UserC'; $this->_em->persist($userA); $this->_em->persist($userB); @@ -1091,12 +1101,12 @@ public function testFlushManyExplicitEntities() /** * @group DDC-720 */ - public function testFlushSingleManagedEntity() + public function testFlushSingleManagedEntity(): void { - $user = new CmsUser; - $user->name = 'Dominik'; + $user = new CmsUser(); + $user->name = 'Dominik'; $user->username = 'domnikl'; - $user->status = 'developer'; + $user->status = 'developer'; $this->_em->persist($user); $this->_em->flush(); @@ -1113,14 +1123,14 @@ public function testFlushSingleManagedEntity() /** * @group DDC-720 */ - public function testFlushSingleUnmanagedEntity() + public function testFlushSingleUnmanagedEntity(): void { - $user = new CmsUser; - $user->name = 'Dominik'; + $user = new CmsUser(); + $user->name = 'Dominik'; $user->username = 'domnikl'; - $user->status = 'developer'; + $user->status = 'developer'; - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Entity has to be managed or scheduled for removal for single computation'); $this->_em->flush($user); @@ -1129,79 +1139,79 @@ public function testFlushSingleUnmanagedEntity() /** * @group DDC-720 */ - public function testFlushSingleAndNewEntity() + public function testFlushSingleAndNewEntity(): void { - $user = new CmsUser; - $user->name = 'Dominik'; + $user = new CmsUser(); + $user->name = 'Dominik'; $user->username = 'domnikl'; - $user->status = 'developer'; + $user->status = 'developer'; $this->_em->persist($user); $this->_em->flush(); - $otherUser = new CmsUser; - $otherUser->name = 'Dominik2'; + $otherUser = new CmsUser(); + $otherUser->name = 'Dominik2'; $otherUser->username = 'domnikl2'; - $otherUser->status = 'developer'; + $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"); + $this->assertTrue($this->_em->contains($otherUser), 'Other user is contained in EntityManager'); + $this->assertTrue($otherUser->id > 0, 'other user has an id'); $this->assertHasDeprecationMessages(); } /** * @group DDC-720 */ - public function testFlushAndCascadePersist() + public function testFlushAndCascadePersist(): void { - $user = new CmsUser; - $user->name = 'Dominik'; + $user = new CmsUser(); + $user->name = 'Dominik'; $user->username = 'domnikl'; - $user->status = 'developer'; + $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; + $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"); + $this->assertTrue($this->_em->contains($address), 'Other user is contained in EntityManager'); + $this->assertTrue($address->id > 0, 'other user has an id'); $this->assertHasDeprecationMessages(); } /** * @group DDC-720 */ - public function testFlushSingleAndNoCascade() + public function testFlushSingleAndNoCascade(): void { - $user = new CmsUser; - $user->name = 'Dominik'; + $user = new CmsUser(); + $user->name = 'Dominik'; $user->username = 'domnikl'; - $user->status = 'developer'; + $user->status = 'developer'; $this->_em->persist($user); $this->_em->flush(); - $article1 = new CmsArticle(); - $article1->topic = 'Foo'; - $article1->text = 'Foo Text'; + $article1 = new CmsArticle(); + $article1->topic = 'Foo'; + $article1->text = 'Foo Text'; $article1->author = $user; $user->articles[] = $article1; - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage("A new entity was found through the relationship 'Doctrine\Tests\Models\CMS\CmsUser#articles'"); $this->_em->flush($user); @@ -1212,12 +1222,12 @@ public function testFlushSingleAndNoCascade() * @group DDC-1612 * @group DDC-2267 */ - public function testFlushSingleNewEntityThenRemove() + public function testFlushSingleNewEntityThenRemove(): void { - $user = new CmsUser; - $user->name = 'Dominik'; + $user = new CmsUser(); + $user->name = 'Dominik'; $user->username = 'domnikl'; - $user->status = 'developer'; + $user->status = 'developer'; $this->_em->persist($user); $this->_em->flush($user); @@ -1235,12 +1245,12 @@ public function testFlushSingleNewEntityThenRemove() /** * @group DDC-720 */ - public function testProxyIsIgnored() + public function testProxyIsIgnored(): void { - $user = new CmsUser; - $user->name = 'Dominik'; + $user = new CmsUser(); + $user->name = 'Dominik'; $user->username = 'domnikl'; - $user->status = 'developer'; + $user->status = 'developer'; $this->_em->persist($user); $this->_em->flush(); @@ -1248,39 +1258,39 @@ public function testProxyIsIgnored() $user = $this->_em->getReference(get_class($user), $user->id); - $otherUser = new CmsUser; - $otherUser->name = 'Dominik2'; + $otherUser = new CmsUser(); + $otherUser->name = 'Dominik2'; $otherUser->username = 'domnikl2'; - $otherUser->status = 'developer'; + $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"); + $this->assertTrue($this->_em->contains($otherUser), 'Other user is contained in EntityManager'); + $this->assertTrue($otherUser->id > 0, 'other user has an id'); $this->assertHasDeprecationMessages(); } /** * @group DDC-720 */ - public function testFlushSingleSaveOnlySingle() + public function testFlushSingleSaveOnlySingle(): void { - $user = new CmsUser; - $user->name = 'Dominik'; + $user = new CmsUser(); + $user->name = 'Dominik'; $user->username = 'domnikl'; - $user->status = 'developer'; + $user->status = 'developer'; $this->_em->persist($user); - $user2 = new CmsUser; - $user2->name = 'Dominik'; + $user2 = new CmsUser(); + $user2->name = 'Dominik'; $user2->username = 'domnikl2'; - $user2->status = 'developer'; + $user2->status = 'developer'; $this->_em->persist($user2); $this->_em->flush(); - $user->status = 'admin'; + $user->status = 'admin'; $user2->status = 'admin'; $this->_em->flush($user); @@ -1294,13 +1304,13 @@ public function testFlushSingleSaveOnlySingle() /** * @group DDC-1585 */ - public function testWrongAssociationInstance() + public function testWrongAssociationInstance(): void { - $user = new CmsUser; - $user->name = 'Dominik'; + $user = new CmsUser(); + $user->name = 'Dominik'; $user->username = 'domnikl'; - $user->status = 'developer'; - $user->address = $user; + $user->status = 'developer'; + $user->address = $user; $this->expectException(ORMInvalidArgumentException::class); $this->expectExceptionMessage( diff --git a/tests/Doctrine/Tests/ORM/Functional/CascadeRemoveOrderTest.php b/tests/Doctrine/Tests/ORM/Functional/CascadeRemoveOrderTest.php index da7f6bcc25f..79c444f1bcf 100644 --- a/tests/Doctrine/Tests/ORM/Functional/CascadeRemoveOrderTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/CascadeRemoveOrderTest.php @@ -1,5 +1,7 @@ _em->find(CascadeRemoveOrderEntityG::class, $eG->getId())); } - public function testMany() + public function testMany(): void { $eO = new CascadeRemoveOrderEntityO(); $eG1 = new CascadeRemoveOrderEntityG($eO); @@ -101,7 +103,6 @@ class CascadeRemoveOrderEntityO */ private $oneToManyG; - public function __construct() { $this->oneToManyG = new ArrayCollection(); @@ -112,7 +113,7 @@ public function getId() return $this->id; } - public function setOneToOneG(CascadeRemoveOrderEntityG $eG) + public function setOneToOneG(CascadeRemoveOrderEntityG $eG): void { $this->oneToOneG = $eG; } @@ -122,7 +123,7 @@ public function getOneToOneG() return $this->oneToOneG; } - public function addOneToManyG(CascadeRemoveOrderEntityG $eG) + public function addOneToManyG(CascadeRemoveOrderEntityG $eG): void { $this->oneToManyG->add($eG); } @@ -152,10 +153,10 @@ class CascadeRemoveOrderEntityG */ private $ownerO; - public function __construct(CascadeRemoveOrderEntityO $eO, $position=1) + public function __construct(CascadeRemoveOrderEntityO $eO, $position = 1) { $this->position = $position; - $this->ownerO= $eO; + $this->ownerO = $eO; $this->ownerO->addOneToManyG($this); } diff --git a/tests/Doctrine/Tests/ORM/Functional/ClassTableInheritanceTest.php b/tests/Doctrine/Tests/ORM/Functional/ClassTableInheritanceTest.php index cfdda20fe69..660a1a02006 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ClassTableInheritanceTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ClassTableInheritanceTest.php @@ -1,7 +1,10 @@ useModelSet('company'); parent::setUp(); } - public function testCRUD() + public function testCRUD(): void { - $person = new CompanyPerson; + $person = new CompanyPerson(); $person->setName('Roman S. Borschel'); $this->_em->persist($person); - $employee = new CompanyEmployee; + $employee = new CompanyEmployee(); $employee->setName('Roman S. Borschel'); $employee->setSalary(100000); $employee->setDepartment('IT'); @@ -89,7 +95,7 @@ public function testCRUD() $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); @@ -97,14 +103,14 @@ public function testCRUD() $numUpdated = $query->execute(); $this->assertEquals(1, $numUpdated); - $query = $this->_em->createQuery('delete from ' . CompanyPerson::class . ' p'); + $query = $this->_em->createQuery('delete from ' . CompanyPerson::class . ' p'); $numDeleted = $query->execute(); $this->assertEquals(2, $numDeleted); } - public function testMultiLevelUpdateAndFind() + public function testMultiLevelUpdateAndFind(): void { - $manager = new CompanyManager; + $manager = new CompanyManager(); $manager->setName('Roman S. Borschel'); $manager->setSalary(100000); $manager->setDepartment('IT'); @@ -129,9 +135,9 @@ public function testMultiLevelUpdateAndFind() $this->assertTrue(is_numeric($manager->getId())); } - public function testFindOnBaseClass() + public function testFindOnBaseClass(): void { - $manager = new CompanyManager; + $manager = new CompanyManager(); $manager->setName('Roman S. Borschel'); $manager->setSalary(100000); $manager->setDepartment('IT'); @@ -150,15 +156,15 @@ public function testFindOnBaseClass() $this->assertTrue(is_numeric($person->getId())); } - public function testSelfReferencingOneToOne() + public function testSelfReferencingOneToOne(): void { - $manager = new CompanyManager; + $manager = new CompanyManager(); $manager->setName('John Smith'); $manager->setSalary(100000); $manager->setDepartment('IT'); $manager->setTitle('CTO'); - $wife = new CompanyPerson; + $wife = new CompanyPerson(); $wife->setName('Mary Smith'); $wife->setSpouse($manager); @@ -185,12 +191,12 @@ public function testSelfReferencingOneToOne() IterableTester::assertResultsAreTheSame($query); } - public function testSelfReferencingManyToMany() + public function testSelfReferencingManyToMany(): void { - $person1 = new CompanyPerson; + $person1 = new CompanyPerson(); $person1->setName('Roman'); - $person2 = new CompanyPerson; + $person2 = new CompanyPerson(); $person2->setName('Jonathan'); $person1->addFriend($person2); @@ -198,7 +204,6 @@ public function testSelfReferencingManyToMany() $this->assertCount(1, $person1->getFriends()); $this->assertCount(1, $person2->getFriends()); - $this->_em->persist($person1); $this->_em->persist($person2); @@ -218,13 +223,13 @@ public function testSelfReferencingManyToMany() $this->assertEquals('Jonathan', $friends[0]->getName()); } - public function testLazyLoading1() + public function testLazyLoading1(): void { - $org = new CompanyOrganization; - $event1 = new CompanyAuction; + $org = new CompanyOrganization(); + $event1 = new CompanyAuction(); $event1->setData('auction'); $org->addEvent($event1); - $event2 = new CompanyRaffle; + $event2 = new CompanyRaffle(); $event2->setData('raffle'); $org->addEvent($event2); @@ -261,10 +266,10 @@ public function testLazyLoading1() IterableTester::assertResultsAreTheSame($q); } - public function testLazyLoading2() + public function testLazyLoading2(): void { - $org = new CompanyOrganization; - $event1 = new CompanyAuction; + $org = new CompanyOrganization(); + $event1 = new CompanyAuction(); $event1->setData('auction'); $org->setMainEvent($event1); @@ -277,7 +282,7 @@ public function testLazyLoading2() $result = $q->getResult(); $this->assertCount(1, $result); - $this->assertInstanceOf(CompanyAuction::class, $result[0], sprintf("Is of class %s", get_class($result[0]))); + $this->assertInstanceOf(CompanyAuction::class, $result[0], sprintf('Is of class %s', get_class($result[0]))); $this->_em->clear(); @@ -306,7 +311,7 @@ public function testLazyLoading2() /** * @group DDC-368 */ - public function testBulkUpdateIssueDDC368() + public function testBulkUpdateIssueDDC368(): void { $this->_em->createQuery('UPDATE ' . CompanyEmployee::class . ' AS p SET p.salary = 1') ->execute(); @@ -324,10 +329,10 @@ public function testBulkUpdateIssueDDC368() /** * @group DDC-1341 */ - public function testBulkUpdateNonScalarParameterDDC1341() + public function testBulkUpdateNonScalarParameterDDC1341(): void { $this->_em->createQuery('UPDATE ' . CompanyEmployee::class . ' AS p SET p.startDate = ?0 WHERE p.department = ?1') - ->setParameter(0, new \DateTime()) + ->setParameter(0, new DateTime()) ->setParameter(1, 'IT') ->execute(); @@ -337,7 +342,7 @@ public function testBulkUpdateNonScalarParameterDDC1341() /** * @group DDC-130 */ - public function testDeleteJoinTableRecords() + public function testDeleteJoinTableRecords(): void { $employee1 = new CompanyEmployee(); $employee1->setName('gblanco'); @@ -366,7 +371,7 @@ public function testDeleteJoinTableRecords() /** * @group DDC-728 */ - public function testQueryForInheritedSingleValuedAssociation() + public function testQueryForInheritedSingleValuedAssociation(): void { $manager = new CompanyManager(); $manager->setName('gblanco'); @@ -395,7 +400,7 @@ public function testQueryForInheritedSingleValuedAssociation() /** * @group DDC-817 */ - public function testFindByAssociation() + public function testFindByAssociation(): void { $manager = new CompanyManager(); $manager->setName('gblanco'); @@ -413,12 +418,12 @@ public function testFindByAssociation() $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()); - $repos = $this->_em->getRepository(CompanyPerson::class); + $repos = $this->_em->getRepository(CompanyPerson::class); $pmanager = $repos->findOneBy(['spouse' => $person->getId()]); $this->assertEquals($manager->getId(), $pmanager->getId()); @@ -427,7 +432,7 @@ public function testFindByAssociation() /** * @group DDC-834 */ - public function testGetReferenceEntityWithSubclasses() + public function testGetReferenceEntityWithSubclasses(): void { $manager = new CompanyManager(); $manager->setName('gblanco'); @@ -440,19 +445,19 @@ public function testGetReferenceEntityWithSubclasses() $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->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->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."); + $this->assertInstanceOf(Proxy::class, $ref, 'A proxy can be generated only if no subclasses exists for the requested reference.'); } /** * @group DDC-992 */ - public function testGetSubClassManyToManyCollection() + public function testGetSubClassManyToManyCollection(): void { $manager = new CompanyManager(); $manager->setName('gblanco'); @@ -478,7 +483,7 @@ public function testGetSubClassManyToManyCollection() /** * @group DDC-1777 */ - public function testExistsSubclass() + public function testExistsSubclass(): void { $manager = new CompanyManager(); $manager->setName('gblanco'); @@ -497,7 +502,7 @@ public function testExistsSubclass() /** * @group DDC-1637 */ - public function testMatching() + public function testMatching(): void { $manager = new CompanyManager(); $manager->setName('gblanco'); @@ -509,13 +514,13 @@ public function testMatching() $this->_em->flush(); $repository = $this->_em->getRepository(CompanyEmployee::class); - $users = $repository->matching(new Criteria( + $users = $repository->matching(new Criteria( Criteria::expr()->eq('department', 'IT') )); $this->assertCount(1, $users); $repository = $this->_em->getRepository(CompanyManager::class); - $users = $repository->matching(new Criteria( + $users = $repository->matching(new Criteria( Criteria::expr()->eq('department', 'IT') )); $this->assertCount(1, $users); diff --git a/tests/Doctrine/Tests/ORM/Functional/ClassTableInheritanceTest2.php b/tests/Doctrine/Tests/ORM/Functional/ClassTableInheritanceTest2.php index 5fac480bd31..5b58197dc6a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ClassTableInheritanceTest2.php +++ b/tests/Doctrine/Tests/ORM/Functional/ClassTableInheritanceTest2.php @@ -1,40 +1,45 @@ _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) { + } catch (Exception $ignored) { // Swallow all exceptions. We do not test the schema tool here. } } - public function testOneToOneAssocToBaseTypeBidirectional() + public function testOneToOneAssocToBaseTypeBidirectional(): void { - $child = new CTIChild; + $child = new CTIChild(); $child->setData('hello'); - $related = new CTIRelated; + $related = new CTIRelated(); $related->setCTIParent($child); $this->_em->persist($related); @@ -55,11 +60,11 @@ public function testOneToOneAssocToBaseTypeBidirectional() $this->assertSame($related2, $related2->getCTIParent()->getRelated()); } - public function testManyToManyToCTIHierarchy() + public function testManyToManyToCTIHierarchy(): void { //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger()); - $mmrel = new CTIRelated2; - $child = new CTIChild; + $mmrel = new CTIRelated2(); + $child = new CTIChild(); $child->setData('child'); $mmrel->addCTIChild($child); @@ -83,25 +88,29 @@ public function testManyToManyToCTIHierarchy() * @DiscriminatorColumn(name="type", type="string") * @DiscriminatorMap({"parent" = "CTIParent", "child" = "CTIChild"}) */ -class CTIParent { +class CTIParent +{ /** - * @Id @Column(type="integer") - * @GeneratedValue(strategy="AUTO") - */ + * @Id @Column(type="integer") + * @GeneratedValue(strategy="AUTO") + */ private $id; /** @OneToOne(targetEntity="CTIRelated", mappedBy="ctiParent") */ private $related; - public function getId() { + public function getId() + { return $this->id; } - public function getRelated() { + public function getRelated() + { return $this->related; } - public function setRelated($related) { + public function setRelated($related): void + { $this->related = $related; $related->setCTIParent($this); } @@ -110,24 +119,25 @@ public function setRelated($related) { /** * @Entity @Table(name="cti_children") */ -class CTIChild extends CTIParent { - /** - * @Column(type="string") - */ +class CTIChild extends CTIParent +{ + /** @Column(type="string") */ private $data; - public function getData() { + public function getData() + { return $this->data; } - public function setData($data) { + public function setData($data): void + { $this->data = $data; } - } /** @Entity */ -class CTIRelated { +class CTIRelated +{ /** * @Id @Column(type="integer") * @GeneratedValue(strategy="AUTO") @@ -140,15 +150,18 @@ class CTIRelated { */ private $ctiParent; - public function getId() { + public function getId() + { return $this->id; } - public function getCTIParent() { + public function getCTIParent() + { return $this->ctiParent; } - public function setCTIParent($ctiParent) { + public function setCTIParent($ctiParent): void + { $this->ctiParent = $ctiParent; } } @@ -161,7 +174,6 @@ class CTIRelated2 /** @ManyToMany(targetEntity="CTIChild") */ private $ctiChildren; - public function __construct() { $this->ctiChildren = new ArrayCollection(); @@ -172,7 +184,7 @@ public function getId() return $this->id; } - public function addCTIChild(CTIChild $child) + public function addCTIChild(CTIChild $child): void { $this->ctiChildren->add($child); } diff --git a/tests/Doctrine/Tests/ORM/Functional/ClearEventTest.php b/tests/Doctrine/Tests/ORM/Functional/ClearEventTest.php index 8c234c0f3f3..5ab08b9e05f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ClearEventTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ClearEventTest.php @@ -1,5 +1,7 @@ */ class ClearEventTest extends OrmFunctionalTestCase { - public function testEventIsCalledOnClear() + public function testEventIsCalledOnClear(): void { - $listener = new OnClearListener; + $listener = new OnClearListener(); $this->_em->getEventManager()->addEventListener(Events::onClear, $listener); $this->_em->clear(); @@ -28,7 +28,7 @@ class OnClearListener { public $called = false; - public function onClear(OnClearEventArgs $args) + public function onClear(OnClearEventArgs $args): void { $this->called = true; } diff --git a/tests/Doctrine/Tests/ORM/Functional/CompositePrimaryKeyTest.php b/tests/Doctrine/Tests/ORM/Functional/CompositePrimaryKeyTest.php index a1c6fc43493..175cfbf4f70 100644 --- a/tests/Doctrine/Tests/ORM/Functional/CompositePrimaryKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/CompositePrimaryKeyTest.php @@ -1,29 +1,34 @@ useModelSet('navigation'); parent::setUp(); } - public function putGermanysBrandenburderTor() + public function putGermanysBrandenburderTor(): void { - $country = new NavCountry("Germany"); + $country = new NavCountry('Germany'); $this->_em->persist($country); - $poi = new NavPointOfInterest(100, 200, "Brandenburger Tor", $country); + $poi = new NavPointOfInterest(100, 200, 'Brandenburger Tor', $country); $this->_em->persist($poi); $this->_em->flush(); $this->_em->clear(); @@ -33,7 +38,7 @@ public function putTripAroundEurope() { $poi = $this->_em->find(NavPointOfInterest::class, ['lat' => 100, 'long' => 200]); - $tour = new NavTour("Trip around Europe"); + $tour = new NavTour('Trip around Europe'); $tour->addPointOfInterest($poi); $this->_em->persist($tour); @@ -43,7 +48,7 @@ public function putTripAroundEurope() return $tour; } - public function testPersistCompositePkEntity() + public function testPersistCompositePkEntity(): void { $this->putGermanysBrandenburderTor(); @@ -58,12 +63,12 @@ public function testPersistCompositePkEntity() /** * @group DDC-1651 */ - public function testSetParameterCompositeKeyObject() + public function testSetParameterCompositeKeyObject(): void { $this->putGermanysBrandenburderTor(); - $poi = $this->_em->find(NavPointOfInterest::class, ['lat' => 100, 'long' => 200]); - $photo = new NavPhotos($poi, "asdf"); + $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(); @@ -76,12 +81,12 @@ public function testSetParameterCompositeKeyObject() $sql = $this->_em->createQuery($dql)->getSQL(); } - public function testIdentityFunctionWithCompositePrimaryKey() + public function testIdentityFunctionWithCompositePrimaryKey(): void { $this->putGermanysBrandenburderTor(); - $poi = $this->_em->find(NavPointOfInterest::class, ['lat' => 100, 'long' => 200]); - $photo = new NavPhotos($poi, "asdf"); + $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(); @@ -99,7 +104,7 @@ public function testIdentityFunctionWithCompositePrimaryKey() IterableTester::assertResultsAreTheSame($query); } - public function testManyToManyCompositeRelation() + public function testManyToManyCompositeRelation(): void { $this->putGermanysBrandenburderTor(); $tour = $this->putTripAroundEurope(); @@ -109,12 +114,12 @@ public function testManyToManyCompositeRelation() $this->assertEquals(1, count($tour->getPointOfInterests())); } - public function testCompositeDqlEagerFetching() + public function testCompositeDqlEagerFetching(): void { $this->putGermanysBrandenburderTor(); $this->putTripAroundEurope(); - $dql = 'SELECT t, p, c FROM Doctrine\Tests\Models\Navigation\NavTour t ' . + $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(); @@ -129,14 +134,14 @@ public function testCompositeDqlEagerFetching() $this->assertEquals('Brandenburger Tor', $pois[0]->getName()); } - public function testCompositeCollectionMemberExpression() + public function testCompositeCollectionMemberExpression(): void { $this->markTestSkipped('How to test this?'); $this->putGermanysBrandenburderTor(); $this->putTripAroundEurope(); - $dql = 'SELECT t FROM Doctrine\Tests\Models\Navigation\NavTour t, Doctrine\Tests\Models\Navigation\NavPointOfInterest p ' . + $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(); @@ -148,7 +153,7 @@ public function testCompositeCollectionMemberExpression() IterableTester::assertResultsAreTheSame($query); } - public function testSpecifyUnknownIdentifierPrimaryKeyFails() + public function testSpecifyUnknownIdentifierPrimaryKeyFails(): void { $this->expectException(ORMException::class); $this->expectExceptionMessage('The identifier long is missing for a query of Doctrine\Tests\Models\Navigation\NavPointOfInterest'); @@ -156,25 +161,24 @@ public function testSpecifyUnknownIdentifierPrimaryKeyFails() $poi = $this->_em->find(NavPointOfInterest::class, ['key1' => 100]); } - public function testUnrecognizedIdentifierFieldsOnGetReference() + public function testUnrecognizedIdentifierFieldsOnGetReference(): void { $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]); } /** * @group DDC-1939 */ - public function testDeleteCompositePersistentCollection() + public function testDeleteCompositePersistentCollection(): void { $this->putGermanysBrandenburderTor(); $poi = $this->_em->find(NavPointOfInterest::class, ['lat' => 100, 'long' => 200]); - $poi->addVisitor(new NavUser("test1")); - $poi->addVisitor(new NavUser("test2")); + $poi->addVisitor(new NavUser('test1')); + $poi->addVisitor(new NavUser('test2')); $this->_em->flush(); diff --git a/tests/Doctrine/Tests/ORM/Functional/CompositePrimaryKeyWithAssociationsTest.php b/tests/Doctrine/Tests/ORM/Functional/CompositePrimaryKeyWithAssociationsTest.php index a335ed464fd..9a14da279e6 100644 --- a/tests/Doctrine/Tests/ORM/Functional/CompositePrimaryKeyWithAssociationsTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/CompositePrimaryKeyWithAssociationsTest.php @@ -1,31 +1,33 @@ useModelSet('geonames'); parent::setUp(); - $it = new Country("IT", "Italy"); + $it = new Country('IT', 'Italy'); $this->_em->persist($it); $this->_em->flush(); - $admin1 = new Admin1(1, "Rome", $it); + $admin1 = new Admin1(1, 'Rome', $it); $this->_em->persist($admin1); $this->_em->flush(); - $name1 = new Admin1AlternateName(1, "Roma", $admin1); - $name2 = new Admin1AlternateName(2, "Rome", $admin1); + $name1 = new Admin1AlternateName(1, 'Roma', $admin1); + $name2 = new Admin1AlternateName(2, 'Rome', $admin1); $admin1->names[] = $name1; $admin1->names[] = $name2; @@ -39,7 +41,7 @@ protected function setUp() : void $this->_em->clear(); } - public function testFindByAbleToGetCompositeEntitiesWithMixedTypeIdentifiers() + public function testFindByAbleToGetCompositeEntitiesWithMixedTypeIdentifiers(): void { $admin1Repo = $this->_em->getRepository(Admin1::class); $admin1NamesRepo = $this->_em->getRepository(Admin1AlternateName::class); @@ -53,9 +55,9 @@ public function testFindByAbleToGetCompositeEntitiesWithMixedTypeIdentifiers() $name2 = $admin1NamesRepo->findOneBy(['admin1' => $admin1Rome, 'id' => 2]); $this->assertEquals(1, $name1->id); - $this->assertEquals("Roma", $name1->name); + $this->assertEquals('Roma', $name1->name); $this->assertEquals(2, $name2->id); - $this->assertEquals("Rome", $name2->name); + $this->assertEquals('Rome', $name2->name); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/CustomFunctionsTest.php b/tests/Doctrine/Tests/ORM/Functional/CustomFunctionsTest.php index 0da3d7c2391..128a62ed698 100644 --- a/tests/Doctrine/Tests/ORM/Functional/CustomFunctionsTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/CustomFunctionsTest.php @@ -1,5 +1,7 @@ useModelSet('cms'); parent::setUp(); } - public function testCustomFunctionDefinedWithCallback() + public function testCustomFunctionDefinedWithCallback(): void { - $user = new CmsUser(); - $user->name = 'Bob'; + $user = new CmsUser(); + $user->name = 'Bob'; $user->username = 'Dylan'; $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', static function ($funcName) { return new NoOp($funcName); }); - $this->_em->getConfiguration()->addCustomNumericFunction('BAR', function($funcName) { + $this->_em->getConfiguration()->addCustomNumericFunction('BAR', static function ($funcName) { return new NoOp($funcName); }); @@ -48,10 +52,10 @@ public function testCustomFunctionDefinedWithCallback() $this->assertSame($user, $users[0]); } - public function testCustomFunctionOverride() + public function testCustomFunctionOverride(): void { - $user = new CmsUser(); - $user->name = 'Bob'; + $user = new CmsUser(); + $user->name = 'Bob'; $user->username = 'Dylan'; $this->_em->persist($user); $this->_em->flush(); @@ -68,12 +72,10 @@ public function testCustomFunctionOverride() class NoOp extends FunctionNode { - /** - * @var PathExpression - */ + /** @var PathExpression */ private $field; - public function parse(Parser $parser) + public function parse(Parser $parser): void { $parser->match(Lexer::T_IDENTIFIER); $parser->match(Lexer::T_OPEN_PARENTHESIS); @@ -89,9 +91,7 @@ public function getSql(SqlWalker $sqlWalker) class CustomCount extends FunctionNode { - /** - * @var Query\AST\AggregateExpression - */ + /** @var Query\AST\AggregateExpression */ private $aggregateExpression; public function parse(Parser $parser): void diff --git a/tests/Doctrine/Tests/ORM/Functional/CustomIdObjectTypeTest.php b/tests/Doctrine/Tests/ORM/Functional/CustomIdObjectTypeTest.php index a76a5d7116e..5ecf7448072 100644 --- a/tests/Doctrine/Tests/ORM/Functional/CustomIdObjectTypeTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/CustomIdObjectTypeTest.php @@ -1,17 +1,19 @@ useModelSet('cms'); parent::setUp(); @@ -25,16 +32,16 @@ protected function setUp() : void /** * @group DDC-2059 */ - public function testIssue2059() + public function testIssue2059(): void { - if (!$this->_em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { + if (! $this->_em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { $this->markTestSkipped('Platform does not support foreign keys.'); } - $user = new Table("ddc2059_user"); + $user = new Table('ddc2059_user'); $user->addColumn('id', 'integer'); $user->setPrimaryKey(['id']); - $project = new Table("ddc2059_project"); + $project = new Table('ddc2059_project'); $project->addColumn('id', 'integer'); $project->addColumn('user_id', 'integer'); $project->addColumn('user', 'string'); @@ -47,50 +54,50 @@ public function testIssue2059() $this->assertTrue(isset($metadata['Ddc2059Project']->associationMappings['user2'])); } - public function testLoadMetadataFromDatabase() + public function testLoadMetadataFromDatabase(): void { - if (!$this->_em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { + if (! $this->_em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { $this->markTestSkipped('Platform does not support foreign keys.'); } - $table = new Table("dbdriver_foo"); + $table = new Table('dbdriver_foo'); $table->addColumn('id', 'integer'); $table->setPrimaryKey(['id']); $table->addColumn('bar', 'string', ['notnull' => false, 'length' => 200]); $this->_sm->dropAndCreateTable($table); - $metadatas = $this->extractClassMetadata(["DbdriverFoo"]); + $metadatas = $this->extractClassMetadata(['DbdriverFoo']); $this->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('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->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']); } - public function testLoadMetadataWithForeignKeyFromDatabase() + public function testLoadMetadataWithForeignKeyFromDatabase(): void { - if (!$this->_em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { + if (! $this->_em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { $this->markTestSkipped('Platform does not support foreign keys.'); } - $tableB = new Table("dbdriver_bar"); + $tableB = new Table('dbdriver_bar'); $tableB->addColumn('id', 'integer'); $tableB->setPrimaryKey(['id']); $this->_sm->dropAndCreateTable($tableB); - $tableA = new Table("dbdriver_baz"); + $tableA = new Table('dbdriver_baz'); $tableA->addColumn('id', 'integer'); $tableA->setPrimaryKey(['id']); $tableA->addColumn('bar_id', 'integer'); @@ -98,7 +105,7 @@ public function testLoadMetadataWithForeignKeyFromDatabase() $this->_sm->dropAndCreateTable($tableA); - $metadatas = $this->extractClassMetadata(["DbdriverBar", "DbdriverBaz"]); + $metadatas = $this->extractClassMetadata(['DbdriverBar', 'DbdriverBaz']); $this->assertArrayHasKey('DbdriverBaz', $metadatas); $bazMetadata = $metadatas['DbdriverBaz']; @@ -106,19 +113,19 @@ public function testLoadMetadataWithForeignKeyFromDatabase() $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->associationMappings = \array_change_key_case($bazMetadata->associationMappings, \CASE_LOWER); + $bazMetadata->associationMappings = array_change_key_case($bazMetadata->associationMappings, CASE_LOWER); $this->assertArrayHasKey('bar', $bazMetadata->associationMappings); $this->assertEquals(ClassMetadataInfo::MANY_TO_ONE, $bazMetadata->associationMappings['bar']['type']); } - public function testDetectManyToManyTables() + public function testDetectManyToManyTables(): void { - 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"]); + $metadatas = $this->extractClassMetadata(['CmsUsers', 'CmsGroups', 'CmsTags']); $this->assertArrayHasKey('CmsUsers', $metadatas, 'CmsUsers entity was not detected.'); $this->assertArrayHasKey('CmsGroups', $metadatas, 'CmsGroups entity was not detected.'); @@ -132,33 +139,33 @@ public function testDetectManyToManyTables() $this->assertArrayHasKey('user', $metadatas['CmsGroups']->associationMappings); } - public function testIgnoreManyToManyTableWithoutFurtherForeignKeyDetails() + public function testIgnoreManyToManyTableWithoutFurtherForeignKeyDetails(): void { - $tableB = new Table("dbdriver_bar"); + $tableB = new Table('dbdriver_bar'); $tableB->addColumn('id', 'integer'); $tableB->setPrimaryKey(['id']); - $tableA = new Table("dbdriver_baz"); + $tableA = new Table('dbdriver_baz'); $tableA->addColumn('id', 'integer'); $tableA->setPrimaryKey(['id']); - $tableMany = new Table("dbdriver_bar_baz"); + $tableMany = new Table('dbdriver_bar_baz'); $tableMany->addColumn('bar_id', 'integer'); $tableMany->addColumn('baz_id', 'integer'); $tableMany->addForeignKeyConstraint('dbdriver_bar', ['bar_id'], ['id']); $metadatas = $this->convertToClassMetadata([$tableA, $tableB], [$tableMany]); - $this->assertEquals(0, count($metadatas['DbdriverBaz']->associationMappings), "no association mappings should be detected."); + $this->assertEquals(0, count($metadatas['DbdriverBaz']->associationMappings), 'no association mappings should be detected.'); } - public function testLoadMetadataFromDatabaseDetail() + public function testLoadMetadataFromDatabaseDetail(): void { - if ( ! $this->_em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { + if (! $this->_em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { $this->markTestSkipped('Platform does not support foreign keys.'); } - $table = new Table("dbdriver_foo"); + $table = new Table('dbdriver_foo'); $table->addColumn('id', 'integer', ['unsigned' => true]); $table->setPrimaryKey(['id']); @@ -169,7 +176,7 @@ public function testLoadMetadataFromDatabaseDetail() $table->addColumn('column_index1', 'string'); $table->addColumn('column_index2', 'string'); - $table->addIndex(['column_index1','column_index2'], 'index1'); + $table->addIndex(['column_index1', 'column_index2'], 'index1'); $table->addColumn('column_unique_index1', 'string'); $table->addColumn('column_unique_index2', 'string'); @@ -177,7 +184,7 @@ public function testLoadMetadataFromDatabaseDetail() $this->_sm->dropAndCreateTable($table); - $metadatas = $this->extractClassMetadata(["DbdriverFoo"]); + $metadatas = $this->extractClassMetadata(['DbdriverFoo']); $this->assertArrayHasKey('DbdriverFoo', $metadatas); @@ -190,8 +197,10 @@ public function testLoadMetadataFromDatabaseDetail() // 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) { + 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']); } @@ -206,13 +215,13 @@ public function testLoadMetadataFromDatabaseDetail() $this->assertEquals(4, $metadata->fieldMappings['columnDecimal']['precision']); $this->assertEquals(3, $metadata->fieldMappings['columnDecimal']['scale']); - $this->assertTrue( ! empty($metadata->table['indexes']['index1']['columns'])); + $this->assertTrue(! empty($metadata->table['indexes']['index1']['columns'])); $this->assertEquals( - ['column_index1','column_index2'], + ['column_index1', 'column_index2'], $metadata->table['indexes']['index1']['columns'] ); - $this->assertTrue( ! empty($metadata->table['uniqueConstraints']['unique_index1']['columns'])); + $this->assertTrue(! empty($metadata->table['uniqueConstraints']['unique_index1']['columns'])); $this->assertEquals( ['column_unique_index1', 'column_unique_index2'], $metadata->table['uniqueConstraints']['unique_index1']['columns'] diff --git a/tests/Doctrine/Tests/ORM/Functional/DatabaseDriverTestCase.php b/tests/Doctrine/Tests/ORM/Functional/DatabaseDriverTestCase.php index 89d3cd3583c..99c8fec40ad 100644 --- a/tests/Doctrine/Tests/ORM/Functional/DatabaseDriverTestCase.php +++ b/tests/Doctrine/Tests/ORM/Functional/DatabaseDriverTestCase.php @@ -1,10 +1,19 @@ _em->getConnection()->getSchemaManager(); + $sm = $this->_em->getConnection()->getSchemaManager(); $driver = new DatabaseDriver($sm); $driver->setTables($entityTables, $manyTables); $metadatas = []; - foreach ($driver->getAllClassNames() AS $className) { + foreach ($driver->getAllClassNames() as $className) { $class = new ClassMetadataInfo($className); $driver->loadMetadataForClass($className, $class); $metadatas[$className] = $class; @@ -29,28 +38,29 @@ protected function convertToClassMetadata(array $entityTables, array $manyTables /** * @param string $className - * @return ClassMetadata */ - protected function extractClassMetadata(array $classNames) + protected function extractClassMetadata(array $classNames): ClassMetadata { $classNames = array_map('strtolower', $classNames); - $metadatas = []; + $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)) { + if (! in_array(strtolower($className), $classNames)) { continue; } + $class = new ClassMetadataInfo($className); $driver->loadMetadataForClass($className, $class); $metadatas[$className] = $class; } - if (count($metadatas) != count($classNames)) { - $this->fail("Have not found all classes matching the names '" . implode(", ", $classNames) . "' only tables " . implode(", ", array_keys($metadatas))); + if (count($metadatas) !== count($classNames)) { + $this->fail("Have not found all classes matching the names '" . implode(', ', $classNames) . "' only tables " . implode(', ', array_keys($metadatas))); } + return $metadatas; } } diff --git a/tests/Doctrine/Tests/ORM/Functional/DefaultValuesTest.php b/tests/Doctrine/Tests/ORM/Functional/DefaultValuesTest.php index 26a4f24f419..59563e702a3 100644 --- a/tests/Doctrine/Tests/ORM/Functional/DefaultValuesTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/DefaultValuesTest.php @@ -1,27 +1,30 @@ _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) { + } catch (Exception $e) { // Swallow all exceptions. We do not test the schema tool here. } } @@ -29,24 +32,25 @@ protected function setUp() : void /** * @group non-cacheable */ - public function testSimpleDetachMerge() { - $user = new DefaultValueUser; + public function testSimpleDetachMerge(): void + { + $user = new DefaultValueUser(); $user->name = 'romanb'; $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__); - $a = new DefaultValueAddress; + $a = new DefaultValueAddress(); $a->country = 'de'; - $a->zip = '12345'; - $a->city = 'Berlin'; - $a->street = 'Sesamestreet'; + $a->zip = '12345'; + $a->city = 'Berlin'; + $a->street = 'Sesamestreet'; $a->user = $user2; $this->_em->persist($a); @@ -64,9 +68,9 @@ public function testSimpleDetachMerge() { /** * @group DDC-1386 */ - public function testGetPartialReferenceWithDefaultValueNotEvaluatedInFlush() + public function testGetPartialReferenceWithDefaultValueNotEvaluatedInFlush(): void { - $user = new DefaultValueUser; + $user = new DefaultValueUser(); $user->name = 'romanb'; $user->type = 'Normaluser'; @@ -97,20 +101,17 @@ class DefaultValueUser * @GeneratedValue(strategy="AUTO") */ public $id; - /** - * @Column(type="string") - */ + /** @Column(type="string") */ public $name = ''; - /** - * @Column(type="string") - */ + /** @Column(type="string") */ public $type = 'Poweruser'; - /** - * @OneToOne(targetEntity="DefaultValueAddress", mappedBy="user", cascade={"persist"}) - */ + /** @OneToOne(targetEntity="DefaultValueAddress", mappedBy="user", cascade={"persist"}) */ public $address; - public function getId() {return $this->id;} + public function getId() + { + return $this->id; + } } /** @@ -126,19 +127,13 @@ class DefaultValueAddress */ public $id; - /** - * @Column(type="string", length=50) - */ + /** @Column(type="string", length=50) */ public $country; - /** - * @Column(type="string", length=50) - */ + /** @Column(type="string", length=50) */ public $zip; - /** - * @Column(type="string", length=50) - */ + /** @Column(type="string", length=50) */ public $city; /** @@ -152,5 +147,8 @@ class DefaultValueAddress */ public $user; - public function getUser() {return $this->user;} + public function getUser() + { + return $this->user; + } } diff --git a/tests/Doctrine/Tests/ORM/Functional/DetachedEntityTest.php b/tests/Doctrine/Tests/ORM/Functional/DetachedEntityTest.php index abcef89a229..41e168d4728 100644 --- a/tests/Doctrine/Tests/ORM/Functional/DetachedEntityTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/DetachedEntityTest.php @@ -1,38 +1,43 @@ useModelSet('cms'); parent::setUp(); } - public function testSimpleDetachMerge() + public function testSimpleDetachMerge(): void { - $user = new CmsUser; - $user->name = 'Roman'; + $user = new CmsUser(); + $user->name = 'Roman'; $user->username = 'romanb'; - $user->status = 'dev'; + $user->status = 'dev'; $this->_em->persist($user); $this->_em->flush(); $this->_em->clear(); @@ -50,15 +55,15 @@ public function testSimpleDetachMerge() $this->assertHasDeprecationMessages(); } - public function testSerializeUnserializeModifyMerge() + public function testSerializeUnserializeModifyMerge(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; - $ph1 = new CmsPhonenumber; - $ph1->phonenumber = "1234"; + $ph1 = new CmsPhonenumber(); + $ph1->phonenumber = '1234'; $user->addPhonenumber($ph1); $this->_em->persist($user); @@ -77,16 +82,16 @@ public function testSerializeUnserializeModifyMerge() $user = unserialize($serialized); - $this->assertEquals(1, count($user->getPhonenumbers()), "Pre-Condition: 1 Phonenumber"); + $this->assertEquals(1, count($user->getPhonenumbers()), 'Pre-Condition: 1 Phonenumber'); - $ph2 = new CmsPhonenumber; + $ph2 = new CmsPhonenumber(); - $ph2->phonenumber = "56789"; + $ph2->phonenumber = '56789'; $user->addPhonenumber($ph2); $oldPhonenumbers = $user->getPhonenumbers(); - $this->assertEquals(2, count($oldPhonenumbers), "Pre-Condition: 2 Phonenumbers"); + $this->assertEquals(2, count($oldPhonenumbers), 'Pre-Condition: 2 Phonenumbers'); $this->assertFalse($this->_em->contains($user)); $this->_em->persist($ph2); @@ -98,26 +103,26 @@ public function testSerializeUnserializeModifyMerge() $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."); + $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->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->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."); + $this->assertTrue($this->_em->contains($phonenumbers[0]), 'Failed to assert that first phonenumber in collection is contained inside EntityManager persistence context.'); $this->assertHasDeprecationMessages(); } /** * @group DDC-203 */ - public function testDetachedEntityThrowsExceptionOnFlush() + public function testDetachedEntityThrowsExceptionOnFlush(): void { - $ph = new CmsPhonenumber(); + $ph = new CmsPhonenumber(); $ph->phonenumber = '12345'; $this->_em->persist($ph); @@ -131,18 +136,18 @@ public function testDetachedEntityThrowsExceptionOnFlush() $this->_em->flush(); } - public function testUninitializedLazyAssociationsAreIgnoredOnMerge() + public function testUninitializedLazyAssociationsAreIgnoredOnMerge(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; - $address = new CmsAddress; - $address->city = 'Berlin'; + $address = new CmsAddress(); + $address->city = 'Berlin'; $address->country = 'Germany'; - $address->street = 'Sesamestreet'; - $address->zip = 12345; + $address->street = 'Sesamestreet'; + $address->zip = 12345; $address->setUser($user); $this->_em->persist($address); $this->_em->persist($user); @@ -167,19 +172,19 @@ public function testUninitializedLazyAssociationsAreIgnoredOnMerge() /** * @group DDC-822 */ - public function testUseDetachedEntityAsQueryParameter() + public function testUseDetachedEntityAsQueryParameter(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $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'; + $dql = 'SELECT u FROM ' . CmsUser::class . ' u WHERE u.id = ?1'; $query = $this->_em->createQuery($dql); $query->setParameter(1, $user); @@ -193,12 +198,12 @@ public function testUseDetachedEntityAsQueryParameter() /** * @group DDC-920 */ - public function testDetachManagedUnpersistedEntity() + public function testDetachManagedUnpersistedEntity(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; $this->_em->persist($user); $this->_em->detach($user); @@ -213,11 +218,11 @@ public function testDetachManagedUnpersistedEntity() /** * @group DDC-1340 */ - public function testMergeArticleWrongVersion() + public function testMergeArticleWrongVersion(): void { - $article = new CmsArticle(); - $article->topic = "test"; - $article->text = "test"; + $article = new CmsArticle(); + $article->topic = 'test'; + $article->text = 'test'; $this->_em->persist($article); $this->_em->flush(); @@ -234,4 +239,3 @@ public function testMergeArticleWrongVersion() $this->assertHasDeprecationMessages(); } } - diff --git a/tests/Doctrine/Tests/ORM/Functional/EntityListenersTest.php b/tests/Doctrine/Tests/ORM/Functional/EntityListenersTest.php index a60b9abec9b..234d8ce486d 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(); @@ -30,23 +29,23 @@ protected function setUp() : void ->resolve(CompanyContractListener::class); } - public function testPreFlushListeners() + public function testPreFlushListeners(): void { $fix = new CompanyFixContract(); $fix->setFixPrice(2000); - $this->listener->preFlushCalls = []; + $this->listener->preFlushCalls = []; $this->_em->persist($fix); $this->_em->flush(); - $this->assertCount(1,$this->listener->preFlushCalls); + $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]); } - public function testPostLoadListeners() + public function testPostLoadListeners(): void { $fix = new CompanyFixContract(); $fix->setFixPrice(2000); @@ -55,34 +54,34 @@ public function testPostLoadListeners() $this->_em->flush(); $this->_em->clear(); - $this->listener->postLoadCalls = []; + $this->listener->postLoadCalls = []; - $dql = "SELECT f FROM Doctrine\Tests\Models\Company\CompanyFixContract f WHERE f.id = ?1"; + $dql = 'SELECT f FROM Doctrine\Tests\Models\Company\CompanyFixContract f WHERE f.id = ?1'; $fix = $this->_em->createQuery($dql)->setParameter(1, $fix->getId())->getSingleResult(); - $this->assertCount(1,$this->listener->postLoadCalls); + $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]); } - public function testPrePersistListeners() + public function testPrePersistListeners(): void { $fix = new CompanyFixContract(); $fix->setFixPrice(2000); - $this->listener->prePersistCalls = []; + $this->listener->prePersistCalls = []; $this->_em->persist($fix); $this->_em->flush(); - $this->assertCount(1,$this->listener->prePersistCalls); + $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]); } - public function testPostPersistListeners() + public function testPostPersistListeners(): void { $fix = new CompanyFixContract(); $fix->setFixPrice(2000); @@ -92,13 +91,13 @@ public function testPostPersistListeners() $this->_em->persist($fix); $this->_em->flush(); - $this->assertCount(1,$this->listener->postPersistCalls); + $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]); } - public function testPreUpdateListeners() + public function testPreUpdateListeners(): void { $fix = new CompanyFixContract(); $fix->setFixPrice(1000); @@ -113,13 +112,13 @@ public function testPreUpdateListeners() $this->_em->persist($fix); $this->_em->flush(); - $this->assertCount(1,$this->listener->preUpdateCalls); + $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]); } - public function testPostUpdateListeners() + public function testPostUpdateListeners(): void { $fix = new CompanyFixContract(); $fix->setFixPrice(1000); @@ -134,13 +133,13 @@ public function testPostUpdateListeners() $this->_em->persist($fix); $this->_em->flush(); - $this->assertCount(1,$this->listener->postUpdateCalls); + $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]); } - public function testPreRemoveListeners() + public function testPreRemoveListeners(): void { $fix = new CompanyFixContract(); $fix->setFixPrice(1000); @@ -153,13 +152,13 @@ public function testPreRemoveListeners() $this->_em->remove($fix); $this->_em->flush(); - $this->assertCount(1,$this->listener->preRemoveCalls); + $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]); } - public function testPostRemoveListeners() + public function testPostRemoveListeners(): void { $fix = new CompanyFixContract(); $fix->setFixPrice(1000); @@ -172,7 +171,7 @@ public function testPostRemoveListeners() $this->_em->remove($fix); $this->_em->flush(); - $this->assertCount(1,$this->listener->postRemoveCalls); + $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]); diff --git a/tests/Doctrine/Tests/ORM/Functional/EntityRepositoryCriteriaTest.php b/tests/Doctrine/Tests/ORM/Functional/EntityRepositoryCriteriaTest.php index fc901949c17..991173130e2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/EntityRepositoryCriteriaTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/EntityRepositoryCriteriaTest.php @@ -1,55 +1,58 @@ - */ +use function count; + class EntityRepositoryCriteriaTest extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { $this->useModelSet('generic'); $this->useModelSet('tweet'); parent::setUp(); } - public function tearDown() : void + public function tearDown(): void { if ($this->_em) { $this->_em->getConfiguration()->setEntityNamespaces([]); } + parent::tearDown(); } - public function loadFixture() + public function loadFixture(): void { - $today = new DateTimeModel(); + $today = new DateTimeModel(); $today->datetime = - $today->date = - $today->time = - new \DateTime('today'); + $today->date = + $today->time = + new DateTime('today'); $this->_em->persist($today); - $tomorrow = new DateTimeModel(); + $tomorrow = new DateTimeModel(); $tomorrow->datetime = - $tomorrow->date = - $tomorrow->time = - new \DateTime('tomorrow'); + $tomorrow->date = + $tomorrow->time = + new DateTime('tomorrow'); $this->_em->persist($tomorrow); - $yesterday = new DateTimeModel(); + $yesterday = new DateTimeModel(); $yesterday->datetime = - $yesterday->date = - $yesterday->time = - new \DateTime('yesterday'); + $yesterday->date = + $yesterday->time = + new DateTime('yesterday'); $this->_em->persist($yesterday); $this->_em->flush(); @@ -61,39 +64,39 @@ public function loadFixture() $this->_em->clear(); } - public function testLteDateComparison() + public function testLteDateComparison(): void { $this->loadFixture(); $repository = $this->_em->getRepository(DateTimeModel::class); - $dates = $repository->matching(new Criteria( - Criteria::expr()->lte('datetime', new \DateTime('today')) + $dates = $repository->matching(new Criteria( + Criteria::expr()->lte('datetime', new DateTime('today')) )); $this->assertEquals(2, count($dates)); } - private function loadNullFieldFixtures() + private function loadNullFieldFixtures(): void { - $today = new DateTimeModel(); + $today = new DateTimeModel(); $today->datetime = - $today->date = - new \DateTime('today'); + $today->date = + new DateTime('today'); $this->_em->persist($today); - $tomorrow = new DateTimeModel(); + $tomorrow = new DateTimeModel(); $tomorrow->datetime = - $tomorrow->date = - $tomorrow->time = - new \DateTime('tomorrow'); + $tomorrow->date = + $tomorrow->time = + new DateTime('tomorrow'); $this->_em->persist($tomorrow); $this->_em->flush(); $this->_em->clear(); } - public function testIsNullComparison() + public function testIsNullComparison(): void { $this->loadNullFieldFixtures(); $repository = $this->_em->getRepository(DateTimeModel::class); @@ -105,7 +108,7 @@ public function testIsNullComparison() $this->assertEquals(1, count($dates)); } - public function testEqNullComparison() + public function testEqNullComparison(): void { $this->loadNullFieldFixtures(); $repository = $this->_em->getRepository(DateTimeModel::class); @@ -117,7 +120,7 @@ public function testEqNullComparison() $this->assertEquals(1, count($dates)); } - public function testNotEqNullComparison() + public function testNotEqNullComparison(): void { $this->loadNullFieldFixtures(); $repository = $this->_em->getRepository(DateTimeModel::class); @@ -129,7 +132,7 @@ public function testNotEqNullComparison() $this->assertEquals(1, count($dates)); } - public function testCanCountWithoutLoadingCollection() + public function testCanCountWithoutLoadingCollection(): void { $this->loadFixture(); $repository = $this->_em->getRepository(DateTimeModel::class); @@ -142,7 +145,7 @@ public function testCanCountWithoutLoadingCollection() // Test it can work even with a constraint $dates = $repository->matching(new Criteria( - Criteria::expr()->lte('datetime', new \DateTime('today')) + Criteria::expr()->lte('datetime', new DateTime('today')) )); $this->assertFalse($dates->isInitialized()); @@ -154,15 +157,15 @@ public function testCanCountWithoutLoadingCollection() $this->assertTrue($dates->isInitialized()); } - public function testCanContainsWithoutLoadingCollection() + public function testCanContainsWithoutLoadingCollection(): void { - $user = new User(); + $user = new User(); $user->name = 'Marco'; $this->_em->persist($user); $this->_em->flush(); - $tweet = new Tweet(); - $tweet->author = $user; + $tweet = new Tweet(); + $tweet->author = $user; $tweet->content = 'Criteria is awesome'; $this->_em->persist($tweet); $this->_em->flush(); diff --git a/tests/Doctrine/Tests/ORM/Functional/EntityRepositoryTest.php b/tests/Doctrine/Tests/ORM/Functional/EntityRepositoryTest.php index 73499710ac0..a4565a58a00 100644 --- a/tests/Doctrine/Tests/ORM/Functional/EntityRepositoryTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/EntityRepositoryTest.php @@ -1,12 +1,16 @@ useModelSet('cms'); parent::setUp(); } - public function tearDown() : void + public function tearDown(): void { if ($this->_em) { $this->_em->getConfiguration()->setEntityNamespaces([]); } + parent::tearDown(); } public function loadFixture() { - $user = new CmsUser; - $user->name = 'Roman'; + $user = new CmsUser(); + $user->name = 'Roman'; $user->username = 'romanb'; - $user->status = 'freak'; + $user->status = 'freak'; $this->_em->persist($user); - $user2 = new CmsUser; - $user2->name = 'Guilherme'; + $user2 = new CmsUser(); + $user2->name = 'Guilherme'; $user2->username = 'gblanco'; - $user2->status = 'dev'; + $user2->status = 'dev'; $this->_em->persist($user2); - $user3 = new CmsUser; - $user3->name = 'Benjamin'; + $user3 = new CmsUser(); + $user3->name = 'Benjamin'; $user3->username = 'beberlei'; - $user3->status = null; + $user3->status = null; $this->_em->persist($user3); - $user4 = new CmsUser; - $user4->name = 'Alexander'; + $user4 = new CmsUser(); + $user4->name = 'Alexander'; $user4->username = 'asm89'; - $user4->status = 'dev'; + $user4->status = 'dev'; $this->_em->persist($user4); $this->_em->flush(); @@ -85,16 +92,16 @@ public function loadFixture() public function loadAssociatedFixture() { - $address = new CmsAddress(); - $address->city = "Berlin"; - $address->country = "Germany"; - $address->street = "Foostreet"; - $address->zip = "12345"; + $address = new CmsAddress(); + $address->city = 'Berlin'; + $address->country = 'Germany'; + $address->street = 'Foostreet'; + $address->zip = '12345'; - $user = new CmsUser(); - $user->name = 'Roman'; + $user = new CmsUser(); + $user->name = 'Roman'; $user->username = 'romanb'; - $user->status = 'freak'; + $user->status = 'freak'; $user->setAddress($address); $this->_em->persist($user); @@ -127,9 +134,9 @@ public function loadFixtureUserEmail() $user3->username = 'test3'; $user3->status = 'active'; - $email1->email = 'test1@test.com'; - $email2->email = 'test2@test.com'; - $email3->email = 'test3@test.com'; + $email1->email = 'test1@test.com'; + $email2->email = 'test2@test.com'; + $email3->email = 'test3@test.com'; $user1->setEmail($email1); $user2->setEmail($email2); @@ -151,7 +158,7 @@ public function loadFixtureUserEmail() public function buildUser($name, $username, $status, $address) { - $user = new CmsUser(); + $user = new CmsUser(); $user->name = $name; $user->username = $username; $user->status = $status; @@ -165,7 +172,7 @@ public function buildUser($name, $username, $status, $address) public function buildAddress($country, $city, $street, $zip) { - $address = new CmsAddress(); + $address = new CmsAddress(); $address->country = $country; $address->city = $city; $address->street = $street; @@ -177,30 +184,30 @@ public function buildAddress($country, $city, $street, $zip) return $address; } - public function testBasicFind() + public function testBasicFind(): void { $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->assertInstanceOf(CmsUser::class, $user); $this->assertEquals('Roman', $user->name); $this->assertEquals('freak', $user->status); } - public function testFindByField() + public function testFindByField(): void { $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->assertInstanceOf(CmsUser::class, $users[0]); $this->assertEquals('Guilherme', $users[0]->name); $this->assertEquals('dev', $users[0]->status); } - public function testFindByAssociationWithIntegerAsParameter() + public function testFindByAssociationWithIntegerAsParameter(): void { $address1 = $this->buildAddress('Germany', 'Berlim', 'Foo st.', '123456'); $user1 = $this->buildUser('Benjamin', 'beberlei', 'dev', $address1); @@ -221,10 +228,10 @@ public function testFindByAssociationWithIntegerAsParameter() $addresses = $repository->findBy(['user' => [$user1->getId(), $user2->getId()]]); $this->assertEquals(2, count($addresses)); - $this->assertInstanceOf(CmsAddress::class,$addresses[0]); + $this->assertInstanceOf(CmsAddress::class, $addresses[0]); } - public function testFindByAssociationWithObjectAsParameter() + public function testFindByAssociationWithObjectAsParameter(): void { $address1 = $this->buildAddress('Germany', 'Berlim', 'Foo st.', '123456'); $user1 = $this->buildUser('Benjamin', 'beberlei', 'dev', $address1); @@ -245,34 +252,34 @@ public function testFindByAssociationWithObjectAsParameter() $addresses = $repository->findBy(['user' => [$user1, $user2]]); $this->assertEquals(2, count($addresses)); - $this->assertInstanceOf(CmsAddress::class,$addresses[0]); + $this->assertInstanceOf(CmsAddress::class, $addresses[0]); } - public function testFindFieldByMagicCall() + public function testFindFieldByMagicCall(): void { $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->assertInstanceOf(CmsUser::class, $users[0]); $this->assertEquals('Guilherme', $users[0]->name); $this->assertEquals('dev', $users[0]->status); } - public function testFindAll() + public function testFindAll(): void { $user1Id = $this->loadFixture(); - $repos = $this->_em->getRepository(CmsUser::class); + $repos = $this->_em->getRepository(CmsUser::class); $users = $repos->findAll(); $this->assertEquals(4, count($users)); } - public function testFindByAlias() + public function testFindByAlias(): void { $user1Id = $this->loadFixture(); - $repos = $this->_em->getRepository(CmsUser::class); + $repos = $this->_em->getRepository(CmsUser::class); $this->_em->getConfiguration()->addEntityNamespace('CMS', 'Doctrine\Tests\Models\CMS'); @@ -282,7 +289,7 @@ public function testFindByAlias() $this->assertEquals(4, count($users)); } - public function testCount() + public function testCount(): void { $this->loadFixture(); $repos = $this->_em->getRepository(CmsUser::class); @@ -297,7 +304,7 @@ public function testCount() $this->assertSame(0, $userCount); } - public function testCountBy() + public function testCountBy(): void { $this->loadFixture(); $repos = $this->_em->getRepository(CmsUser::class); @@ -306,13 +313,15 @@ public function testCountBy() $this->assertSame(2, $userCount); } - public function testExceptionIsThrownWhenCallingFindByWithoutParameter() { + public function testExceptionIsThrownWhenCallingFindByWithoutParameter(): void + { $this->expectException('Doctrine\ORM\ORMException'); $this->_em->getRepository(CmsUser::class) ->findByStatus(); } - public function testExceptionIsThrownWhenUsingInvalidFieldName() { + public function testExceptionIsThrownWhenUsingInvalidFieldName(): void + { $this->expectException('Doctrine\ORM\ORMException'); $this->_em->getRepository(CmsUser::class) ->findByThisFieldDoesNotExist('testvalue'); @@ -322,7 +331,7 @@ public function testExceptionIsThrownWhenUsingInvalidFieldName() { * @group locking * @group DDC-178 */ - public function testPessimisticReadLockWithoutTransaction_ThrowsException() + public function testPessimisticReadLockWithoutTransaction_ThrowsException(): void { $this->expectException(TransactionRequiredException::class); @@ -334,7 +343,7 @@ public function testPessimisticReadLockWithoutTransaction_ThrowsException() * @group locking * @group DDC-178 */ - public function testPessimisticWriteLockWithoutTransaction_ThrowsException() + public function testPessimisticWriteLockWithoutTransaction_ThrowsException(): void { $this->expectException(TransactionRequiredException::class); @@ -346,7 +355,7 @@ public function testPessimisticWriteLockWithoutTransaction_ThrowsException() * @group locking * @group DDC-178 */ - public function testOptimisticLockUnversionedEntity_ThrowsException() + public function testOptimisticLockUnversionedEntity_ThrowsException(): void { $this->expectException(OptimisticLockException::class); @@ -358,12 +367,12 @@ public function testOptimisticLockUnversionedEntity_ThrowsException() * @group locking * @group DDC-178 */ - public function testIdentityMappedOptimisticLockUnversionedEntity_ThrowsException() + public function testIdentityMappedOptimisticLockUnversionedEntity_ThrowsException(): void { - $user = new CmsUser; - $user->name = 'Roman'; + $user = new CmsUser(); + $user->name = 'Roman'; $user->username = 'romanb'; - $user->status = 'freak'; + $user->status = 'freak'; $this->_em->persist($user); $this->_em->flush(); @@ -379,7 +388,7 @@ public function testIdentityMappedOptimisticLockUnversionedEntity_ThrowsExceptio /** * @group DDC-819 */ - public function testFindMagicCallByNullValue() + public function testFindMagicCallByNullValue(): void { $this->loadFixture(); @@ -392,9 +401,9 @@ public function testFindMagicCallByNullValue() /** * @group DDC-819 */ - public function testInvalidMagicCall() + public function testInvalidMagicCall(): void { - $this->expectException(\BadMethodCallException::class); + $this->expectException(BadMethodCallException::class); $repos = $this->_em->getRepository(CmsUser::class); $repos->foo(); @@ -403,10 +412,10 @@ public function testInvalidMagicCall() /** * @group DDC-817 */ - public function testFindByAssociationKey_ExceptionOnInverseSide() + public function testFindByAssociationKey_ExceptionOnInverseSide(): void { [$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."); @@ -417,11 +426,11 @@ public function testFindByAssociationKey_ExceptionOnInverseSide() /** * @group DDC-817 */ - public function testFindOneByAssociationKey() + public function testFindOneByAssociationKey(): void { [$userId, $addressId] = $this->loadAssociatedFixture(); - $repos = $this->_em->getRepository(CmsAddress::class); - $address = $repos->findOneBy(['user' => $userId]); + $repos = $this->_em->getRepository(CmsAddress::class); + $address = $repos->findOneBy(['user' => $userId]); $this->assertInstanceOf(CmsAddress::class, $address); $this->assertEquals($addressId, $address->id); @@ -430,25 +439,25 @@ public function testFindOneByAssociationKey() /** * @group DDC-1241 */ - public function testFindOneByOrderBy() + public function testFindOneByOrderBy(): void { - $this->loadFixture(); + $this->loadFixture(); - $repos = $this->_em->getRepository(CmsUser::class); - $userAsc = $repos->findOneBy([], ["username" => "ASC"]); - $userDesc = $repos->findOneBy([], ["username" => "DESC"]); + $repos = $this->_em->getRepository(CmsUser::class); + $userAsc = $repos->findOneBy([], ['username' => 'ASC']); + $userDesc = $repos->findOneBy([], ['username' => 'DESC']); - $this->assertNotSame($userAsc, $userDesc); + $this->assertNotSame($userAsc, $userDesc); } /** * @group DDC-817 */ - public function testFindByAssociationKey() + public function testFindByAssociationKey(): void { [$userId, $addressId] = $this->loadAssociatedFixture(); - $repos = $this->_em->getRepository(CmsAddress::class); - $addresses = $repos->findBy(['user' => $userId]); + $repos = $this->_em->getRepository(CmsAddress::class); + $addresses = $repos->findBy(['user' => $userId]); $this->assertContainsOnly(CmsAddress::class, $addresses); $this->assertEquals(1, count($addresses)); @@ -458,11 +467,11 @@ public function testFindByAssociationKey() /** * @group DDC-817 */ - public function testFindAssociationByMagicCall() + public function testFindAssociationByMagicCall(): void { [$userId, $addressId] = $this->loadAssociatedFixture(); - $repos = $this->_em->getRepository(CmsAddress::class); - $addresses = $repos->findByUser($userId); + $repos = $this->_em->getRepository(CmsAddress::class); + $addresses = $repos->findByUser($userId); $this->assertContainsOnly(CmsAddress::class, $addresses); $this->assertEquals(1, count($addresses)); @@ -472,17 +481,17 @@ public function testFindAssociationByMagicCall() /** * @group DDC-817 */ - public function testFindOneAssociationByMagicCall() + public function testFindOneAssociationByMagicCall(): void { [$userId, $addressId] = $this->loadAssociatedFixture(); - $repos = $this->_em->getRepository(CmsAddress::class); - $address = $repos->findOneByUser($userId); + $repos = $this->_em->getRepository(CmsAddress::class); + $address = $repos->findOneByUser($userId); $this->assertInstanceOf(CmsAddress::class, $address); $this->assertEquals($addressId, $address->id); } - public function testValidNamedQueryRetrieval() + public function testValidNamedQueryRetrieval(): void { $repos = $this->_em->getRepository(CmsUser::class); @@ -492,11 +501,11 @@ public function testValidNamedQueryRetrieval() $this->assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', $query->getDQL()); } - public function testInvalidNamedQueryRetrieval() + public function testInvalidNamedQueryRetrieval(): void { $repos = $this->_em->getRepository(CmsUser::class); - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); + $this->expectException(MappingException::class); $repos->createNamedQuery('invalidNamedQuery'); } @@ -504,17 +513,17 @@ public function testInvalidNamedQueryRetrieval() /** * @group DDC-1087 */ - public function testIsNullCriteriaDoesNotGenerateAParameter() + public function testIsNullCriteriaDoesNotGenerateAParameter(): void { $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(1, count($params), 'Should only execute with one parameter.'); $this->assertEquals(['romanb'], $params); } - public function testIsNullCriteria() + public function testIsNullCriteria(): void { $this->loadFixture(); @@ -527,7 +536,7 @@ public function testIsNullCriteria() /** * @group DDC-1094 */ - public function testFindByLimitOffset() + public function testFindByLimitOffset(): void { $this->loadFixture(); @@ -545,16 +554,16 @@ public function testFindByLimitOffset() /** * @group DDC-1094 */ - public function testFindByOrderBy() + public function testFindByOrderBy(): void { $this->loadFixture(); - $repos = $this->_em->getRepository(CmsUser::class); - $usersAsc = $repos->findBy([], ["username" => "ASC"]); - $usersDesc = $repos->findBy([], ["username" => "DESC"]); + $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->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]); } @@ -562,7 +571,7 @@ public function testFindByOrderBy() /** * @group DDC-1376 */ - public function testFindByOrderByAssociation() + public function testFindByOrderByAssociation(): void { $this->loadFixtureUserEmail(); @@ -580,18 +589,18 @@ public function testFindByOrderByAssociation() /** * @group DDC-1426 */ - public function testFindFieldByMagicCallOrderBy() + public function testFindFieldByMagicCallOrderBy(): void { $this->loadFixture(); $repos = $this->_em->getRepository(CmsUser::class); - $usersAsc = $repos->findByStatus('dev', ['username' => "ASC"]); - $usersDesc = $repos->findByStatus('dev', ['username' => "DESC"]); + $usersAsc = $repos->findByStatus('dev', ['username' => 'ASC']); + $usersDesc = $repos->findByStatus('dev', ['username' => 'DESC']); $this->assertEquals(2, count($usersAsc)); $this->assertEquals(2, count($usersDesc)); - $this->assertInstanceOf(CmsUser::class,$usersAsc[0]); + $this->assertInstanceOf(CmsUser::class, $usersAsc[0]); $this->assertEquals('Alexander', $usersAsc[0]->name); $this->assertEquals('dev', $usersAsc[0]->status); @@ -602,7 +611,7 @@ public function testFindFieldByMagicCallOrderBy() /** * @group DDC-1426 */ - public function testFindFieldByMagicCallLimitOffset() + public function testFindFieldByMagicCallLimitOffset(): void { $this->loadFixture(); $repos = $this->_em->getRepository(CmsUser::class); @@ -618,7 +627,7 @@ public function testFindFieldByMagicCallLimitOffset() /** * @group DDC-753 */ - public function testDefaultRepositoryClassName() + public function testDefaultRepositoryClassName(): void { $this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), EntityRepository::class); $this->_em->getConfiguration()->setDefaultRepositoryClassName(DDC753DefaultRepository::class); @@ -628,7 +637,6 @@ public function testDefaultRepositoryClassName() $this->assertInstanceOf(DDC753DefaultRepository::class, $repos); $this->assertTrue($repos->isDefaultRepository()); - $repos = $this->_em->getRepository(DDC753EntityWithCustomRepository::class); $this->assertInstanceOf(DDC753CustomRepository::class, $repos); $this->assertTrue($repos->isCustomRepository()); @@ -636,13 +644,12 @@ public function testDefaultRepositoryClassName() $this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), DDC753DefaultRepository::class); $this->_em->getConfiguration()->setDefaultRepositoryClassName(EntityRepository::class); $this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), EntityRepository::class); - } /** * @group DDC-753 */ - public function testSetDefaultRepositoryInvalidClassError() + public function testSetDefaultRepositoryInvalidClassError(): void { $this->expectException('Doctrine\ORM\ORMException'); $this->expectExceptionMessage('Invalid repository class \'Doctrine\Tests\Models\DDC753\DDC753InvalidRepository\'. It must be a Doctrine\Persistence\ObjectRepository.'); @@ -653,7 +660,7 @@ public function testSetDefaultRepositoryInvalidClassError() /** * @group DDC-3257 */ - public function testSingleRepositoryInstanceForDifferentEntityAliases() + public function testSingleRepositoryInstanceForDifferentEntityAliases(): void { $config = $this->_em->getConfiguration(); @@ -669,7 +676,7 @@ public function testSingleRepositoryInstanceForDifferentEntityAliases() /** * @group DDC-3257 */ - public function testCanRetrieveRepositoryFromClassNameWithLeadingBackslash() + public function testCanRetrieveRepositoryFromClassNameWithLeadingBackslash(): void { $this->assertSame( $this->_em->getRepository('\\' . CmsUser::class), @@ -680,7 +687,7 @@ public function testCanRetrieveRepositoryFromClassNameWithLeadingBackslash() /** * @group DDC-1376 */ - public function testInvalidOrderByAssociation() + public function testInvalidOrderByAssociation(): void { $this->expectException('Doctrine\ORM\ORMException'); $this->expectExceptionMessage('You cannot search for the association field \'Doctrine\Tests\Models\CMS\CmsUser#address\', because it is the inverse side of an association.'); @@ -691,7 +698,7 @@ public function testInvalidOrderByAssociation() /** * @group DDC-1500 */ - public function testInvalidOrientation() + public function testInvalidOrientation(): void { $this->expectException(ORMException::class); $this->expectExceptionMessage('Invalid order by orientation specified for Doctrine\Tests\Models\CMS\CmsUser#username'); @@ -703,25 +710,25 @@ public function testInvalidOrientation() /** * @group DDC-1713 */ - public function testFindByAssociationArray() + public function testFindByAssociationArray(): void { $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([1, 2, 3], $query['params'][0]); $this->assertEquals(Connection::PARAM_INT_ARRAY, $query['types'][0]); } /** * @group DDC-1637 */ - public function testMatchingEmptyCriteria() + public function testMatchingEmptyCriteria(): void { $this->loadFixture(); $repository = $this->_em->getRepository(CmsUser::class); - $users = $repository->matching(new Criteria()); + $users = $repository->matching(new Criteria()); $this->assertEquals(4, count($users)); } @@ -729,12 +736,12 @@ public function testMatchingEmptyCriteria() /** * @group DDC-1637 */ - public function testMatchingCriteriaEqComparison() + public function testMatchingCriteriaEqComparison(): void { $this->loadFixture(); $repository = $this->_em->getRepository(CmsUser::class); - $users = $repository->matching(new Criteria( + $users = $repository->matching(new Criteria( Criteria::expr()->eq('username', 'beberlei') )); @@ -744,12 +751,12 @@ public function testMatchingCriteriaEqComparison() /** * @group DDC-1637 */ - public function testMatchingCriteriaNeqComparison() + public function testMatchingCriteriaNeqComparison(): void { $this->loadFixture(); $repository = $this->_em->getRepository(CmsUser::class); - $users = $repository->matching(new Criteria( + $users = $repository->matching(new Criteria( Criteria::expr()->neq('username', 'beberlei') )); @@ -759,12 +766,12 @@ public function testMatchingCriteriaNeqComparison() /** * @group DDC-1637 */ - public function testMatchingCriteriaInComparison() + public function testMatchingCriteriaInComparison(): void { $this->loadFixture(); $repository = $this->_em->getRepository(CmsUser::class); - $users = $repository->matching(new Criteria( + $users = $repository->matching(new Criteria( Criteria::expr()->in('username', ['beberlei', 'gblanco']) )); @@ -774,12 +781,12 @@ public function testMatchingCriteriaInComparison() /** * @group DDC-1637 */ - public function testMatchingCriteriaNotInComparison() + public function testMatchingCriteriaNotInComparison(): void { $this->loadFixture(); $repository = $this->_em->getRepository(CmsUser::class); - $users = $repository->matching(new Criteria( + $users = $repository->matching(new Criteria( Criteria::expr()->notIn('username', ['beberlei', 'gblanco', 'asm89']) )); @@ -789,12 +796,12 @@ public function testMatchingCriteriaNotInComparison() /** * @group DDC-1637 */ - public function testMatchingCriteriaLtComparison() + public function testMatchingCriteriaLtComparison(): void { $firstUserId = $this->loadFixture(); $repository = $this->_em->getRepository(CmsUser::class); - $users = $repository->matching(new Criteria( + $users = $repository->matching(new Criteria( Criteria::expr()->lt('id', $firstUserId + 1) )); @@ -804,12 +811,12 @@ public function testMatchingCriteriaLtComparison() /** * @group DDC-1637 */ - public function testMatchingCriteriaLeComparison() + public function testMatchingCriteriaLeComparison(): void { $firstUserId = $this->loadFixture(); $repository = $this->_em->getRepository(CmsUser::class); - $users = $repository->matching(new Criteria( + $users = $repository->matching(new Criteria( Criteria::expr()->lte('id', $firstUserId + 1) )); @@ -819,12 +826,12 @@ public function testMatchingCriteriaLeComparison() /** * @group DDC-1637 */ - public function testMatchingCriteriaGtComparison() + public function testMatchingCriteriaGtComparison(): void { $firstUserId = $this->loadFixture(); $repository = $this->_em->getRepository(CmsUser::class); - $users = $repository->matching(new Criteria( + $users = $repository->matching(new Criteria( Criteria::expr()->gt('id', $firstUserId) )); @@ -834,12 +841,12 @@ public function testMatchingCriteriaGtComparison() /** * @group DDC-1637 */ - public function testMatchingCriteriaGteComparison() + public function testMatchingCriteriaGteComparison(): void { $firstUserId = $this->loadFixture(); $repository = $this->_em->getRepository(CmsUser::class); - $users = $repository->matching(new Criteria( + $users = $repository->matching(new Criteria( Criteria::expr()->gte('id', $firstUserId) )); @@ -849,7 +856,7 @@ public function testMatchingCriteriaGteComparison() /** * @group DDC-2430 */ - public function testMatchingCriteriaAssocationByObjectInMemory() + public function testMatchingCriteriaAssocationByObjectInMemory(): void { [$userId, $addressId] = $this->loadAssociatedFixture(); @@ -860,7 +867,7 @@ public function testMatchingCriteriaAssocationByObjectInMemory() ); $repository = $this->_em->getRepository(CmsAddress::class); - $addresses = $repository->matching($criteria); + $addresses = $repository->matching($criteria); $this->assertEquals(1, count($addresses)); @@ -872,7 +879,7 @@ public function testMatchingCriteriaAssocationByObjectInMemory() /** * @group DDC-2430 */ - public function testMatchingCriteriaAssocationInWithArray() + public function testMatchingCriteriaAssocationInWithArray(): void { [$userId, $addressId] = $this->loadAssociatedFixture(); @@ -883,7 +890,7 @@ public function testMatchingCriteriaAssocationInWithArray() ); $repository = $this->_em->getRepository(CmsAddress::class); - $addresses = $repository->matching($criteria); + $addresses = $repository->matching($criteria); $this->assertEquals(1, count($addresses)); @@ -892,7 +899,7 @@ public function testMatchingCriteriaAssocationInWithArray() $this->assertEquals(1, count($addresses->matching($criteria))); } - public function testMatchingCriteriaContainsComparison() + public function testMatchingCriteriaContainsComparison(): void { $this->loadFixture(); @@ -908,7 +915,7 @@ public function testMatchingCriteriaContainsComparison() $this->assertEquals(2, count($users)); } - public function testMatchingCriteriaStartsWithComparison() + public function testMatchingCriteriaStartsWithComparison(): void { $this->loadFixture(); @@ -924,7 +931,7 @@ public function testMatchingCriteriaStartsWithComparison() $this->assertCount(2, $users); } - public function testMatchingCriteriaEndsWithComparison() + public function testMatchingCriteriaEndsWithComparison(): void { $this->loadFixture(); @@ -943,7 +950,7 @@ public function testMatchingCriteriaEndsWithComparison() /** * @group DDC-2478 */ - public function testMatchingCriteriaNullAssocComparison() + public function testMatchingCriteriaNullAssocComparison(): void { $fixtures = $this->loadFixtureUserEmail(); $user = $this->_em->merge($fixtures[0]); @@ -973,10 +980,10 @@ public function testMatchingCriteriaNullAssocComparison() /** * @group DDC-2055 */ - public function testCreateResultSetMappingBuilder() + public function testCreateResultSetMappingBuilder(): void { $repository = $this->_em->getRepository(CmsUser::class); - $rsm = $repository->createResultSetMappingBuilder('u'); + $rsm = $repository->createResultSetMappingBuilder('u'); $this->assertInstanceOf(Query\ResultSetMappingBuilder::class, $rsm); $this->assertEquals(['u' => CmsUser::class], $rsm->aliasMap); @@ -985,7 +992,7 @@ public function testCreateResultSetMappingBuilder() /** * @group DDC-3045 */ - public function testFindByFieldInjectionPrevented() + public function testFindByFieldInjectionPrevented(): void { $this->expectException(ORMException::class); $this->expectExceptionMessage('Unrecognized field: '); @@ -997,7 +1004,7 @@ public function testFindByFieldInjectionPrevented() /** * @group DDC-3045 */ - public function testFindOneByFieldInjectionPrevented() + public function testFindOneByFieldInjectionPrevented(): void { $this->expectException(ORMException::class); $this->expectExceptionMessage('Unrecognized field: '); @@ -1009,7 +1016,7 @@ public function testFindOneByFieldInjectionPrevented() /** * @group DDC-3045 */ - public function testMatchingInjectionPrevented() + public function testMatchingInjectionPrevented(): void { $this->expectException(ORMException::class); $this->expectExceptionMessage('Unrecognized field: '); @@ -1026,7 +1033,7 @@ public function testMatchingInjectionPrevented() /** * @group DDC-3045 */ - public function testFindInjectionPrevented() + public function testFindInjectionPrevented(): void { $this->expectException(ORMException::class); $this->expectExceptionMessage('Unrecognized identifier fields: '); @@ -1038,17 +1045,17 @@ public function testFindInjectionPrevented() /** * @group DDC-3056 */ - public function testFindByNullValueInInCondition() + public function testFindByNullValueInInCondition(): void { $user1 = new CmsUser(); $user2 = new CmsUser(); $user1->username = 'ocramius'; - $user1->name = 'Marco'; - $user2->status = null; + $user1->name = 'Marco'; + $user2->status = null; $user2->username = 'deeky666'; - $user2->name = 'Steve'; - $user2->status = 'dbal maintainer'; + $user2->name = 'Steve'; + $user2->status = 'dbal maintainer'; $this->_em->persist($user1); $this->_em->persist($user2); @@ -1063,17 +1070,17 @@ public function testFindByNullValueInInCondition() /** * @group DDC-3056 */ - public function testFindByNullValueInMultipleInCriteriaValues() + public function testFindByNullValueInMultipleInCriteriaValues(): void { $user1 = new CmsUser(); $user2 = new CmsUser(); $user1->username = 'ocramius'; - $user1->name = 'Marco'; - $user2->status = null; + $user1->name = 'Marco'; + $user2->status = null; $user2->username = 'deeky666'; - $user2->name = 'Steve'; - $user2->status = 'dbal maintainer'; + $user2->name = 'Steve'; + $user2->status = 'dbal maintainer'; $this->_em->persist($user1); $this->_em->persist($user2); @@ -1091,17 +1098,17 @@ public function testFindByNullValueInMultipleInCriteriaValues() /** * @group DDC-3056 */ - public function testFindMultipleByNullValueInMultipleInCriteriaValues() + public function testFindMultipleByNullValueInMultipleInCriteriaValues(): void { $user1 = new CmsUser(); $user2 = new CmsUser(); $user1->username = 'ocramius'; - $user1->name = 'Marco'; - $user2->status = null; + $user1->name = 'Marco'; + $user2->status = null; $user2->username = 'deeky666'; - $user2->name = 'Steve'; - $user2->status = 'dbal maintainer'; + $user2->name = 'Steve'; + $user2->status = 'dbal maintainer'; $this->_em->persist($user1); $this->_em->persist($user2); @@ -1119,7 +1126,7 @@ public function testFindMultipleByNullValueInMultipleInCriteriaValues() } } - public function testDeprecatedClear() : void + public function testDeprecatedClear(): void { $repository = $this->_em->getRepository(CmsAddress::class); @@ -1132,4 +1139,3 @@ public function testDeprecatedClear() : void $repository->clear(); } } - diff --git a/tests/Doctrine/Tests/ORM/Functional/ExtraLazyCollectionTest.php b/tests/Doctrine/Tests/ORM/Functional/ExtraLazyCollectionTest.php index 34040f7b67d..7b49d9ff837 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ExtraLazyCollectionTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ExtraLazyCollectionTest.php @@ -11,11 +11,10 @@ use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\Models\DDC2504\DDC2504ChildClass; use Doctrine\Tests\Models\DDC2504\DDC2504OtherClass; -use Doctrine\Tests\Models\Tweet\Tweet; -use Doctrine\Tests\Models\Tweet\User; -use Doctrine\Tests\Models\Tweet\UserList; use Doctrine\Tests\OrmFunctionalTestCase; + use function array_shift; +use function assert; use function count; /** @@ -35,7 +34,7 @@ class ExtraLazyCollectionTest extends OrmFunctionalTestCase private $topic; private $phonenumber; - protected function setUp() : void + protected function setUp(): void { $this->useModelSet('tweet'); $this->useModelSet('cms'); @@ -61,7 +60,7 @@ protected function setUp() : void $this->loadFixture(); } - public function tearDown() : void + public function tearDown(): void { parent::tearDown(); @@ -84,7 +83,7 @@ public function tearDown() : void * @group DDC-546 * @group non-cacheable */ - public function testCountNotInitializesCollection() + public function testCountNotInitializesCollection(): void { $user = $this->_em->find(CmsUser::class, $this->userId); $queryCount = $this->getCurrentQueryCount(); @@ -102,7 +101,7 @@ public function testCountNotInitializesCollection() /** * @group DDC-546 */ - public function testCountWhenNewEntityPresent() + public function testCountWhenNewEntityPresent(): void { $user = $this->_em->find(CmsUser::class, $this->userId); @@ -121,7 +120,7 @@ public function testCountWhenNewEntityPresent() * @group DDC-546 * @group non-cacheable */ - public function testCountWhenInitialized() + public function testCountWhenInitialized(): void { $user = $this->_em->find(CmsUser::class, $this->userId); $queryCount = $this->getCurrentQueryCount(); @@ -137,7 +136,7 @@ public function testCountWhenInitialized() /** * @group DDC-546 */ - public function testCountInverseCollection() + public function testCountInverseCollection(): void { $group = $this->_em->find(CmsGroup::class, $this->groupId); $this->assertFalse($group->users->isInitialized(), 'Pre-Condition'); @@ -149,7 +148,7 @@ public function testCountInverseCollection() /** * @group DDC-546 */ - public function testCountOneToMany() + public function testCountOneToMany(): void { $user = $this->_em->find(CmsUser::class, $this->userId); $this->assertFalse($user->groups->isInitialized(), 'Pre-Condition'); @@ -160,7 +159,7 @@ public function testCountOneToMany() /** * @group DDC-2504 */ - public function testCountOneToManyJoinedInheritance() + public function testCountOneToManyJoinedInheritance(): void { $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); @@ -171,7 +170,7 @@ public function testCountOneToManyJoinedInheritance() /** * @group DDC-546 */ - public function testFullSlice() + public function testFullSlice(): void { $user = $this->_em->find(CmsUser::class, $this->userId); $this->assertFalse($user->groups->isInitialized(), 'Pre-Condition: Collection is not initialized.'); @@ -184,7 +183,7 @@ public function testFullSlice() * @group DDC-546 * @group non-cacheable */ - public function testSlice() + public function testSlice(): void { $user = $this->_em->find(CmsUser::class, $this->userId); $this->assertFalse($user->groups->isInitialized(), 'Pre-Condition: Collection is not initialized.'); @@ -216,7 +215,7 @@ public function testSlice() * @group DDC-546 * @group non-cacheable */ - public function testSliceInitializedCollection() + public function testSliceInitializedCollection(): void { $user = $this->_em->find(CmsUser::class, $this->userId); $queryCount = $this->getCurrentQueryCount(); @@ -236,7 +235,7 @@ public function testSliceInitializedCollection() /** * @group DDC-546 */ - public function testSliceInverseCollection() + public function testSliceInverseCollection(): void { $group = $this->_em->find(CmsGroup::class, $this->groupId); $this->assertFalse($group->users->isInitialized(), 'Pre-Condition'); @@ -257,7 +256,7 @@ public function testSliceInverseCollection() /** * @group DDC-546 */ - public function testSliceOneToMany() + public function testSliceOneToMany(): void { $user = $this->_em->find(CmsUser::class, $this->userId); $this->assertFalse($user->articles->isInitialized(), 'Pre-Condition: Collection is not initialized.'); @@ -273,7 +272,7 @@ public function testSliceOneToMany() /** * @group DDC-546 */ - public function testContainsOneToMany() + public function testContainsOneToMany(): void { $user = $this->_em->find(CmsUser::class, $this->userId); $this->assertFalse($user->articles->isInitialized(), 'Pre-Condition: Collection is not initialized.'); @@ -301,7 +300,7 @@ public function testContainsOneToMany() $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->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.'); // Test One to Many existence with state managed @@ -321,7 +320,7 @@ public function testContainsOneToMany() /** * @group DDC-2504 */ - public function testLazyOneToManyJoinedInheritanceIsLazilyInitialized() + public function testLazyOneToManyJoinedInheritanceIsLazilyInitialized(): void { $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); @@ -331,7 +330,7 @@ public function testLazyOneToManyJoinedInheritanceIsLazilyInitialized() /** * @group DDC-2504 */ - public function testContainsOnOneToManyJoinedInheritanceWillNotInitializeCollectionWhenMatchingItemIsFound() + public function testContainsOnOneToManyJoinedInheritanceWillNotInitializeCollectionWhenMatchingItemIsFound(): void { $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); @@ -347,7 +346,7 @@ public function testContainsOnOneToManyJoinedInheritanceWillNotInitializeCollect /** * @group DDC-2504 */ - public function testContainsOnOneToManyJoinedInheritanceWillNotCauseQueriesWhenNonPersistentItemIsMatched() + public function testContainsOnOneToManyJoinedInheritanceWillNotCauseQueriesWhenNonPersistentItemIsMatched(): void { $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); $queryCount = $this->getCurrentQueryCount(); @@ -363,7 +362,7 @@ public function testContainsOnOneToManyJoinedInheritanceWillNotCauseQueriesWhenN /** * @group DDC-2504 */ - public function testContainsOnOneToManyJoinedInheritanceWillNotInitializeCollectionWithClearStateMatchingItem() + public function testContainsOnOneToManyJoinedInheritanceWillNotInitializeCollectionWithClearStateMatchingItem(): void { $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); $childClass = new DDC2504ChildClass(); @@ -381,7 +380,7 @@ public function testContainsOnOneToManyJoinedInheritanceWillNotInitializeCollect /** * @group DDC-2504 */ - public function testContainsOnOneToManyJoinedInheritanceWillNotInitializeCollectionWithNewStateNotMatchingItem() + public function testContainsOnOneToManyJoinedInheritanceWillNotInitializeCollectionWithNewStateNotMatchingItem(): void { $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); $childClass = new DDC2504ChildClass(); @@ -398,7 +397,7 @@ public function testContainsOnOneToManyJoinedInheritanceWillNotInitializeCollect /** * @group DDC-2504 */ - public function testCountingOnOneToManyJoinedInheritanceWillNotInitializeCollection() + public function testCountingOnOneToManyJoinedInheritanceWillNotInitializeCollection(): void { $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); @@ -410,7 +409,7 @@ public function testCountingOnOneToManyJoinedInheritanceWillNotInitializeCollect /** * @group DDC-546 */ - public function testContainsManyToMany() + public function testContainsManyToMany(): void { $user = $this->_em->find(CmsUser::class, $this->userId); $this->assertFalse($user->groups->isInitialized(), 'Pre-Condition: Collection is not initialized.'); @@ -459,7 +458,7 @@ public function testContainsManyToMany() /** * @group DDC-546 */ - public function testContainsManyToManyInverse() + public function testContainsManyToManyInverse(): void { $group = $this->_em->find(CmsGroup::class, $this->groupId); $this->assertFalse($group->users->isInitialized(), 'Pre-Condition: Collection is not initialized.'); @@ -468,7 +467,7 @@ public function testContainsManyToManyInverse() $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->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.'); $newUser = new CmsUser(); @@ -483,7 +482,7 @@ public function testContainsManyToManyInverse() /** * @group DDC-1399 */ - public function testCountAfterAddThenFlush() + public function testCountAfterAddThenFlush(): void { $user = $this->_em->find(CmsUser::class, $this->userId); @@ -506,10 +505,10 @@ public function testCountAfterAddThenFlush() * @group DDC-1462 * @group non-cacheable */ - public function testSliceOnDirtyCollection() + public function testSliceOnDirtyCollection(): void { $user = $this->_em->find(CmsUser::class, $this->userId); - /** @var CmsUser $user */ + assert($user instanceof CmsUser); $newGroup = new CmsGroup(); $newGroup->name = 'Test4'; @@ -528,10 +527,10 @@ public function testSliceOnDirtyCollection() * @group DDC-1398 * @group non-cacheable */ - public function testGetIndexByIdentifier() + public function testGetIndexByIdentifier(): void { $user = $this->_em->find(CmsUser::class, $this->userId); - /** @var CmsUser $user */ + assert($user instanceof CmsUser); $queryCount = $this->getCurrentQueryCount(); $phonenumber = $user->phonenumbers->get($this->phonenumber); @@ -547,10 +546,10 @@ public function testGetIndexByIdentifier() /** * @group DDC-1398 */ - public function testGetIndexByOneToMany() + public function testGetIndexByOneToMany(): void { $user = $this->_em->find(CmsUser::class, $this->userId); - /** @var CmsUser $user */ + assert($user instanceof CmsUser); $queryCount = $this->getCurrentQueryCount(); @@ -564,10 +563,10 @@ public function testGetIndexByOneToMany() /** * @group DDC-1398 */ - public function testGetIndexByManyToManyInverseSide() + public function testGetIndexByManyToManyInverseSide(): void { $group = $this->_em->find(CmsGroup::class, $this->groupId); - /** @var CmsGroup $group */ + assert($group instanceof CmsGroup); $queryCount = $this->getCurrentQueryCount(); @@ -581,10 +580,10 @@ public function testGetIndexByManyToManyInverseSide() /** * @group DDC-1398 */ - public function testGetIndexByManyToManyOwningSide() + public function testGetIndexByManyToManyOwningSide(): void { $user = $this->_em->find(CmsUser::class, $this->userId); - /** @var CmsUser $user */ + assert($user instanceof CmsUser); $queryCount = $this->getCurrentQueryCount(); @@ -598,17 +597,17 @@ public function testGetIndexByManyToManyOwningSide() /** * @group DDC-1398 */ - public function testGetNonExistentIndexBy() + public function testGetNonExistentIndexBy(): void { $user = $this->_em->find(CmsUser::class, $this->userId); $this->assertNull($user->articles->get(-1)); $this->assertNull($user->groups->get(-1)); } - public function testContainsKeyIndexByOneToMany() + public function testContainsKeyIndexByOneToMany(): void { $user = $this->_em->find(CmsUser::class, $this->userId); - /** @var CmsUser $user */ + assert($user instanceof CmsUser); $queryCount = $this->getCurrentQueryCount(); @@ -619,7 +618,7 @@ public function testContainsKeyIndexByOneToMany() $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } - public function testContainsKeyIndexByOneToManyJoinedInheritance() + public function testContainsKeyIndexByOneToManyJoinedInheritance(): void { $class = $this->_em->getClassMetadata(DDC2504OtherClass::class); $class->associationMappings['childClasses']['indexBy'] = 'id'; @@ -635,7 +634,7 @@ public function testContainsKeyIndexByOneToManyJoinedInheritance() $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } - public function testContainsKeyIndexByManyToMany() + public function testContainsKeyIndexByManyToMany(): void { $user = $this->_em->find(CmsUser::class, $this->userId2); @@ -649,7 +648,8 @@ public function testContainsKeyIndexByManyToMany() $this->assertFalse($user->groups->isInitialized(), 'The collection must not be initialized'); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } - public function testContainsKeyIndexByManyToManyNonOwning() + + public function testContainsKeyIndexByManyToManyNonOwning(): void { $user = $this->_em->find(CmsUser::class, $this->userId2); $group = $this->_em->find(CmsGroup::class, $this->groupId); @@ -663,7 +663,7 @@ public function testContainsKeyIndexByManyToManyNonOwning() $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } - public function testContainsKeyIndexByWithPkManyToMany() + public function testContainsKeyIndexByWithPkManyToMany(): void { $class = $this->_em->getClassMetadata(CmsUser::class); $class->associationMappings['groups']['indexBy'] = 'id'; @@ -678,7 +678,8 @@ public function testContainsKeyIndexByWithPkManyToMany() $this->assertFalse($user->groups->isInitialized(), 'The collection must not be initialized'); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } - public function testContainsKeyIndexByWithPkManyToManyNonOwning() + + public function testContainsKeyIndexByWithPkManyToManyNonOwning(): void { $class = $this->_em->getClassMetadata(CmsGroup::class); $class->associationMappings['users']['indexBy'] = 'id'; @@ -694,7 +695,7 @@ public function testContainsKeyIndexByWithPkManyToManyNonOwning() $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } - public function testContainsKeyNonExistentIndexByOneToMany() + public function testContainsKeyNonExistentIndexByOneToMany(): void { $user = $this->_em->find(CmsUser::class, $this->userId2); @@ -707,7 +708,7 @@ public function testContainsKeyNonExistentIndexByOneToMany() $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } - public function testContainsKeyNonExistentIndexByManyToMany() + public function testContainsKeyNonExistentIndexByManyToMany(): void { $user = $this->_em->find(CmsUser::class, $this->userId2); @@ -720,7 +721,7 @@ public function testContainsKeyNonExistentIndexByManyToMany() $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } - private function loadFixture() + private function loadFixture(): void { $user1 = new CmsUser(); $user1->username = 'beberlei'; diff --git a/tests/Doctrine/Tests/ORM/Functional/FlushEventTest.php b/tests/Doctrine/Tests/ORM/Functional/FlushEventTest.php index 1424d60af69..5db5db76557 100644 --- a/tests/Doctrine/Tests/ORM/Functional/FlushEventTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/FlushEventTest.php @@ -1,35 +1,37 @@ useModelSet('cms'); parent::setUp(); } - public function testPersistNewEntitiesOnPreFlush() + public function testPersistNewEntitiesOnPreFlush(): void { //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $this->_em->getEventManager()->addEventListener(Events::onFlush, new OnFlushListener); + $this->_em->getEventManager()->addEventListener(Events::onFlush, new OnFlushListener()); - $user = new CmsUser; + $user = new CmsUser(); $user->username = 'romanb'; - $user->name = 'Roman'; - $user->status = 'Dev'; + $user->name = 'Roman'; + $user->status = 'Dev'; $this->_em->persist($user); @@ -52,7 +54,7 @@ public function testPersistNewEntitiesOnPreFlush() /** * @group DDC-2173 */ - public function testPreAndOnFlushCalledAlways() + public function testPreAndOnFlushCalledAlways(): void { $listener = new OnFlushCalledListener(); $this->_em->getEventManager()->addEventListener(Events::onFlush, $listener); @@ -73,19 +75,18 @@ public function testPreAndOnFlushCalledAlways() class OnFlushListener { - public function onFlush(OnFlushEventArgs $args) + public function onFlush(OnFlushEventArgs $args): void { //echo "---preFlush".PHP_EOL; - $em = $args->getEntityManager(); + $em = $args->getEntityManager(); $uow = $em->getUnitOfWork(); foreach ($uow->getScheduledEntityInsertions() as $entity) { - if ($entity instanceof CmsUser) { // Adds a phonenumber to every newly persisted CmsUser ... - $phone = new CmsPhonenumber; + $phone = new CmsPhonenumber(); $phone->phonenumber = 12345; // Update object model $entity->addPhonenumber($phone); @@ -107,30 +108,28 @@ public function onFlush(OnFlushEventArgs $args) var_dump($old); }*/ - } } } class OnFlushCalledListener { - public $preFlush = 0; - public $onFlush = 0; + public $preFlush = 0; + public $onFlush = 0; public $postFlush = 0; - public function preFlush($args) + public function preFlush($args): void { $this->preFlush++; } - public function onFlush($args) + public function onFlush($args): void { $this->onFlush++; } - public function postFlush($args) + public function postFlush($args): void { $this->postFlush++; } } - diff --git a/tests/Doctrine/Tests/ORM/Functional/GH5988Test.php b/tests/Doctrine/Tests/ORM/Functional/GH5988Test.php index f388b3d8bb3..e15e041ac8a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/GH5988Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/GH5988Test.php @@ -8,6 +8,7 @@ use Doctrine\DBAL\Types\Type as DBALType; use Doctrine\Tests\DbalTypes\CustomIdObject; use Doctrine\Tests\OrmFunctionalTestCase; + use function str_replace; /** @@ -17,7 +18,7 @@ */ final class GH5988Test extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { parent::setUp(); @@ -28,7 +29,7 @@ protected function setUp() : void $this->setUpEntitySchema([GH5988CustomIdObjectTypeParent::class, GH5988CustomIdObjectTypeChild::class]); } - public function testDelete() + public function testDelete(): void { $object = new GH5988CustomIdObjectTypeChild(new CustomIdObject('foo'), 'Test'); @@ -56,6 +57,7 @@ public function convertToDatabaseValue($value, AbstractPlatform $platform) { return $value->id . '_test'; } + /** * {@inheritdoc} */ @@ -63,6 +65,7 @@ public function convertToPHPValue($value, AbstractPlatform $platform) { return new CustomIdObject(str_replace('_test', '', $value)); } + /** * {@inheritdoc} */ @@ -70,6 +73,7 @@ public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $pla { return $platform->getVarcharTypeDeclarationSQL($fieldDeclaration); } + /** * {@inheritdoc} */ diff --git a/tests/Doctrine/Tests/ORM/Functional/HydrationCacheTest.php b/tests/Doctrine/Tests/ORM/Functional/HydrationCacheTest.php index 46a4870ce8b..d980ae0b77a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/HydrationCacheTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/HydrationCacheTest.php @@ -1,60 +1,62 @@ useModelSet('cms'); parent::setUp(); - $user = new CmsUser(); - $user->name = "Benjamin"; - $user->username = "beberlei"; - $user->status = 'active'; + $user = new CmsUser(); + $user->name = 'Benjamin'; + $user->username = 'beberlei'; + $user->status = 'active'; $this->_em->persist($user); $this->_em->flush(); $this->_em->clear(); } - public function testHydrationCache() + public function testHydrationCache(): void { $cache = new ArrayCache(); - $dql = "SELECT u FROM Doctrine\Tests\Models\Cms\CmsUser u"; + $dql = 'SELECT u FROM Doctrine\Tests\Models\Cms\CmsUser u'; $users = $this->_em->createQuery($dql) ->setHydrationCacheProfile(new QueryCacheProfile(null, null, $cache)) ->getResult(); - $c = $this->getCurrentQueryCount(); + $c = $this->getCurrentQueryCount(); $users = $this->_em->createQuery($dql) ->setHydrationCacheProfile(new QueryCacheProfile(null, null, $cache)) ->getResult(); - $this->assertEquals($c, $this->getCurrentQueryCount(), "Should not execute query. Its cached!"); + $this->assertEquals($c, $this->getCurrentQueryCount(), 'Should not execute query. Its cached!'); $users = $this->_em->createQuery($dql) ->setHydrationCacheProfile(new QueryCacheProfile(null, null, $cache)) ->getArrayResult(); - $this->assertEquals($c + 1, $this->getCurrentQueryCount(), "Hydration is part of cache key."); + $this->assertEquals($c + 1, $this->getCurrentQueryCount(), 'Hydration is part of cache key.'); $users = $this->_em->createQuery($dql) ->setHydrationCacheProfile(new QueryCacheProfile(null, null, $cache)) ->getArrayResult(); - $this->assertEquals($c + 1, $this->getCurrentQueryCount(), "Hydration now cached"); + $this->assertEquals($c + 1, $this->getCurrentQueryCount(), 'Hydration now cached'); $users = $this->_em->createQuery($dql) ->setHydrationCacheProfile(new QueryCacheProfile(null, 'cachekey', $cache)) @@ -65,14 +67,14 @@ public function testHydrationCache() $users = $this->_em->createQuery($dql) ->setHydrationCacheProfile(new QueryCacheProfile(null, 'cachekey', $cache)) ->getArrayResult(); - $this->assertEquals($c + 2, $this->getCurrentQueryCount(), "Hydration now cached"); + $this->assertEquals($c + 2, $this->getCurrentQueryCount(), 'Hydration now cached'); } - public function testHydrationParametersSerialization() + public function testHydrationParametersSerialization(): void { $cache = new ArrayCache(); - $dql = "SELECT u FROM Doctrine\Tests\Models\Cms\CmsUser u WHERE u.id = ?1"; + $dql = 'SELECT u FROM Doctrine\Tests\Models\Cms\CmsUser u WHERE u.id = ?1'; $query = $this->_em->createQuery($dql) ->setParameter(1, $userId = 1) ->setHydrationCacheProfile(new QueryCacheProfile(null, null, $cache)); @@ -83,7 +85,6 @@ public function testHydrationParametersSerialization() $query->getResult(); - $this->assertEquals($c, $this->getCurrentQueryCount(), "Should not execute query. Its cached!"); + $this->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 1ab9eb82516..c6aafe41227 100644 --- a/tests/Doctrine/Tests/ORM/Functional/IdentityMapTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/IdentityMapTest.php @@ -1,5 +1,7 @@ */ class IdentityMapTest extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { $this->useModelSet('cms'); parent::setUp(); } - public function testBasicIdentityManagement() + public function testBasicIdentityManagement(): void { - $user = new CmsUser; - $user->status = 'dev'; + $user = new CmsUser(); + $user->status = 'dev'; $user->username = 'romanb'; - $user->name = 'Roman B.'; + $user->name = 'Roman B.'; - $address = new CmsAddress; + $address = new CmsAddress(); $address->country = 'de'; - $address->zip = 1234; - $address->city = 'Berlin'; + $address->zip = 1234; + $address->city = 'Berlin'; $user->setAddress($address); @@ -55,22 +58,22 @@ public function testBasicIdentityManagement() $this->assertTrue($user2->getAddress() === $address2); // !!! } - public function testSingleValuedAssociationIdentityMapBehaviorWithRefresh() + public function testSingleValuedAssociationIdentityMapBehaviorWithRefresh(): void { - $address = new CmsAddress; + $address = new CmsAddress(); $address->country = 'de'; - $address->zip = '12345'; - $address->city = 'Berlin'; + $address->zip = '12345'; + $address->city = 'Berlin'; - $user1 = new CmsUser; - $user1->status = 'dev'; + $user1 = new CmsUser(); + $user1->status = 'dev'; $user1->username = 'romanb'; - $user1->name = 'Roman B.'; + $user1->name = 'Roman B.'; - $user2 = new CmsUser; - $user2->status = 'dev'; + $user2 = new CmsUser(); + $user2->status = 'dev'; $user2->username = 'gblanco'; - $user2->name = 'Guilherme Blanco'; + $user2->name = 'Guilherme Blanco'; $address->setUser($user1); @@ -97,22 +100,22 @@ public function testSingleValuedAssociationIdentityMapBehaviorWithRefresh() $this->assertSame($user1->address, $address); } - public function testSingleValuedAssociationIdentityMapBehaviorWithRefreshQuery() + public function testSingleValuedAssociationIdentityMapBehaviorWithRefreshQuery(): void { - $address = new CmsAddress; + $address = new CmsAddress(); $address->country = 'de'; - $address->zip = '12345'; - $address->city = 'Berlin'; + $address->zip = '12345'; + $address->city = 'Berlin'; - $user1 = new CmsUser; - $user1->status = 'dev'; + $user1 = new CmsUser(); + $user1->status = 'dev'; $user1->username = 'romanb'; - $user1->name = 'Roman B.'; + $user1->name = 'Roman B.'; - $user2 = new CmsUser; - $user2->status = 'dev'; + $user2 = new CmsUser(); + $user2->status = 'dev'; $user2->username = 'gblanco'; - $user2->name = 'Guilherme Blanco'; + $user2->name = 'Guilherme Blanco'; $address->setUser($user1); @@ -121,14 +124,13 @@ public function testSingleValuedAssociationIdentityMapBehaviorWithRefreshQuery() $this->_em->persist($user2); $this->_em->flush(); - $this->assertSame($user1, $address->user); //external update to CmsAddress $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); @@ -154,20 +156,20 @@ public function testSingleValuedAssociationIdentityMapBehaviorWithRefreshQuery() $this->assertSame($user1->address, $address2); } - public function testCollectionValuedAssociationIdentityMapBehaviorWithRefreshQuery() + public function testCollectionValuedAssociationIdentityMapBehaviorWithRefreshQuery(): void { - $user = new CmsUser; - $user->status = 'dev'; + $user = new CmsUser(); + $user->status = 'dev'; $user->username = 'romanb'; - $user->name = 'Roman B.'; + $user->name = 'Roman B.'; - $phone1 = new CmsPhonenumber; + $phone1 = new CmsPhonenumber(); $phone1->phonenumber = 123; - $phone2 = new CmsPhonenumber; + $phone2 = new CmsPhonenumber(); $phone2->phonenumber = 234; - $phone3 = new CmsPhonenumber; + $phone3 = new CmsPhonenumber(); $phone3->phonenumber = 345; $user->addPhonenumber($phone1); @@ -181,11 +183,10 @@ public function testCollectionValuedAssociationIdentityMapBehaviorWithRefreshQue $this->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); @@ -207,20 +208,20 @@ public function testCollectionValuedAssociationIdentityMapBehaviorWithRefreshQue $this->assertEquals(4, count($user3->getPhonenumbers())); } - public function testCollectionValuedAssociationIdentityMapBehaviorWithRefresh() + public function testCollectionValuedAssociationIdentityMapBehaviorWithRefresh(): void { - $user = new CmsUser; - $user->status = 'dev'; + $user = new CmsUser(); + $user->status = 'dev'; $user->username = 'romanb'; - $user->name = 'Roman B.'; + $user->name = 'Roman B.'; - $phone1 = new CmsPhonenumber; + $phone1 = new CmsPhonenumber(); $phone1->phonenumber = 123; - $phone2 = new CmsPhonenumber; + $phone2 = new CmsPhonenumber(); $phone2->phonenumber = 234; - $phone3 = new CmsPhonenumber; + $phone3 = new CmsPhonenumber(); $phone3->phonenumber = 345; $user->addPhonenumber($phone1); @@ -233,11 +234,10 @@ public function testCollectionValuedAssociationIdentityMapBehaviorWithRefresh() $this->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); @@ -255,4 +255,3 @@ public function testCollectionValuedAssociationIdentityMapBehaviorWithRefresh() $this->assertEquals(4, count($user2->getPhonenumbers())); } } - diff --git a/tests/Doctrine/Tests/ORM/Functional/IndexByAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/IndexByAssociationTest.php index bbd49dbc817..8221e02ada9 100644 --- a/tests/Doctrine/Tests/ORM/Functional/IndexByAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/IndexByAssociationTest.php @@ -1,38 +1,41 @@ useModelSet('stockexchange'); parent::setUp(); $this->loadFixture(); } - public function loadFixture() + public function loadFixture(): void { - $this->market = new Market("Some Exchange"); - $stock1 = new Stock("AAPL", 10, $this->market); - $stock2 = new Stock("GOOG", 20, $this->market); + $this->market = new Market('Some Exchange'); + $stock1 = new Stock('AAPL', 10, $this->market); + $stock2 = new Stock('GOOG', 20, $this->market); - $this->bond = new Bond("MyBond"); + $this->bond = new Bond('MyBond'); $this->bond->addStock($stock1); $this->bond->addStock($stock2); @@ -44,61 +47,60 @@ public function loadFixture() $this->_em->clear(); } - public function testManyToOneFinder() + public function testManyToOneFinder(): void { - /* @var $market Market */ $market = $this->_em->find(Market::class, $this->market->getId()); + assert($market instanceof Market); $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()); + $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()); } - public function testManyToOneDQL() + public function testManyToOneDQL(): void { - $dql = "SELECT m, s FROM Doctrine\Tests\Models\StockExchange\Market m JOIN m.stocks s WHERE m.id = ?1"; + $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(); $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()); + $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()); } - public function testManyToMany() + public function testManyToMany(): void { $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()); + $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()); } - public function testManytoManyDQL() + public function testManytoManyDQL(): void { - $dql = "SELECT b, s FROM Doctrine\Tests\Models\StockExchange\Bond b JOIN b.stocks s WHERE b.id = ?1"; + $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(); $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()); + $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()); } - public function testDqlOverrideIndexBy() + public function testDqlOverrideIndexBy(): void { - $dql = "SELECT b, s FROM Doctrine\Tests\Models\StockExchange\Bond b JOIN b.stocks s INDEX BY s.id WHERE b.id = ?1"; + $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(); $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."); + $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.'); } } - diff --git a/tests/Doctrine/Tests/ORM/Functional/JoinedTableCompositeKeyTest.php b/tests/Doctrine/Tests/ORM/Functional/JoinedTableCompositeKeyTest.php index c581fa51810..779e23c35ef 100644 --- a/tests/Doctrine/Tests/ORM/Functional/JoinedTableCompositeKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/JoinedTableCompositeKeyTest.php @@ -1,19 +1,22 @@ useModelSet('compositekeyinheritance'); parent::setUp(); } - public function testInsertWithCompositeKey() + public function testInsertWithCompositeKey(): void { $childEntity = new JoinedChildClass(); $this->_em->persist($childEntity); @@ -28,7 +31,7 @@ public function testInsertWithCompositeKey() /** * @group non-cacheable */ - public function testUpdateWithCompositeKey() + public function testUpdateWithCompositeKey(): void { $childEntity = new JoinedChildClass(); $this->_em->persist($childEntity); @@ -36,7 +39,7 @@ public function testUpdateWithCompositeKey() $this->_em->clear(); - $entity = $this->findEntity(); + $entity = $this->findEntity(); $entity->extension = 'ext-new'; $this->_em->persist($entity); $this->_em->flush(); @@ -47,10 +50,7 @@ public function testUpdateWithCompositeKey() $this->assertEquals($entity, $persistedEntity); } - /** - * @return \Doctrine\Tests\Models\CompositeKeyInheritance\JoinedChildClass - */ - private function findEntity() + private function findEntity(): JoinedChildClass { return $this->_em->find( JoinedRootClass::class, diff --git a/tests/Doctrine/Tests/ORM/Functional/LifecycleCallbackTest.php b/tests/Doctrine/Tests/ORM/Functional/LifecycleCallbackTest.php index a1b0e934c90..812e799976b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/LifecycleCallbackTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/LifecycleCallbackTest.php @@ -1,5 +1,7 @@ _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) { + } catch (Exception $e) { // Swallow all exceptions. We do not test the schema tool here. } } - public function testPreSavePostSaveCallbacksAreInvoked() + public function testPreSavePostSaveCallbacksAreInvoked(): void { - $entity = new LifecycleCallbackTestEntity; + $entity = new LifecycleCallbackTestEntity(); $entity->value = 'hello'; $this->_em->persist($entity); $this->_em->flush(); @@ -41,7 +48,7 @@ public function testPreSavePostSaveCallbacksAreInvoked() $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); @@ -52,9 +59,9 @@ public function testPreSavePostSaveCallbacksAreInvoked() $this->assertEquals('changed from preUpdate callback!', $result[0]->value); } - public function testPreFlushCallbacksAreInvoked() + public function testPreFlushCallbacksAreInvoked(): void { - $entity = new LifecycleCallbackTestEntity; + $entity = new LifecycleCallbackTestEntity(); $entity->value = 'hello'; $this->_em->persist($entity); @@ -68,16 +75,16 @@ public function testPreFlushCallbacksAreInvoked() $this->assertTrue($entity->preFlushCallbackInvoked); - $entity->value = 'bye'; + $entity->value = 'bye'; $entity->preFlushCallbackInvoked = false; $this->_em->flush(); $this->assertTrue($entity->preFlushCallbackInvoked); } - public function testChangesDontGetLost() + public function testChangesDontGetLost(): void { - $user = new LifecycleCallbackTestUser; + $user = new LifecycleCallbackTestUser(); $user->setName('Bob'); $user->setValue('value'); $this->_em->persist($user); @@ -97,9 +104,9 @@ public function testChangesDontGetLost() /** * @group DDC-194 */ - public function testGetReferenceWithPostLoadEventIsDelayedUntilProxyTrigger() + public function testGetReferenceWithPostLoadEventIsDelayedUntilProxyTrigger(): void { - $entity = new LifecycleCallbackTestEntity; + $entity = new LifecycleCallbackTestEntity(); $entity->value = 'hello'; $this->_em->persist($entity); $this->_em->flush(); @@ -117,9 +124,9 @@ public function testGetReferenceWithPostLoadEventIsDelayedUntilProxyTrigger() /** * @group DDC-958 */ - public function testPostLoadTriggeredOnRefresh() + public function testPostLoadTriggeredOnRefresh(): void { - $entity = new LifecycleCallbackTestEntity; + $entity = new LifecycleCallbackTestEntity(); $entity->value = 'hello'; $this->_em->persist($entity); $this->_em->flush(); @@ -132,26 +139,26 @@ public function testPostLoadTriggeredOnRefresh() $reference->postLoadCallbackInvoked = false; $this->_em->refresh($reference); - $this->assertTrue($reference->postLoadCallbackInvoked, "postLoad should be invoked when refresh() is called."); + $this->assertTrue($reference->postLoadCallbackInvoked, 'postLoad should be invoked when refresh() is called.'); } /** * @group DDC-113 */ - public function testCascadedEntitiesCallsPrePersist() + public function testCascadedEntitiesCallsPrePersist(): void { //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $e1 = new LifecycleCallbackTestEntity; - $e2 = new LifecycleCallbackTestEntity; + $e1 = new LifecycleCallbackTestEntity(); + $e2 = new LifecycleCallbackTestEntity(); $c = new LifecycleCallbackCascader(); $this->_em->persist($c); $c->entities[] = $e1; $c->entities[] = $e2; - $e1->cascader = $c; - $e2->cascader = $c; + $e1->cascader = $c; + $e2->cascader = $c; //$this->_em->persist($c); $this->_em->flush(); @@ -164,7 +171,7 @@ public function testCascadedEntitiesCallsPrePersist() * @group DDC-54 * @group DDC-3005 */ - public function testCascadedEntitiesLoadedInPostLoad() + public function testCascadedEntitiesLoadedInPostLoad(): void { $e1 = new LifecycleCallbackTestEntity(); $e2 = new LifecycleCallbackTestEntity(); @@ -174,8 +181,8 @@ public function testCascadedEntitiesLoadedInPostLoad() $c->entities[] = $e1; $c->entities[] = $e2; - $e1->cascader = $c; - $e2->cascader = $c; + $e1->cascader = $c; + $e2->cascader = $c; $this->_em->flush(); $this->_em->clear(); @@ -206,7 +213,7 @@ public function testCascadedEntitiesLoadedInPostLoad() * @group DDC-54 * @group DDC-3005 */ - public function testCascadedEntitiesNotLoadedInPostLoadDuringIteration() + public function testCascadedEntitiesNotLoadedInPostLoadDuringIteration(): void { $e1 = new LifecycleCallbackTestEntity(); $e2 = new LifecycleCallbackTestEntity(); @@ -216,8 +223,8 @@ public function testCascadedEntitiesNotLoadedInPostLoadDuringIteration() $c->entities[] = $e1; $c->entities[] = $e2; - $e1->cascader = $c; - $e2->cascader = $c; + $e1->cascader = $c; + $e2->cascader = $c; $this->_em->flush(); $this->_em->clear(); @@ -253,11 +260,12 @@ public function testCascadedEntitiesNotLoadedInPostLoadDuringIteration() break; } } + /** * @group DDC-54 * @group DDC-3005 */ - public function testCascadedEntitiesNotLoadedInPostLoadDuringIterationWithSimpleObjectHydrator() + public function testCascadedEntitiesNotLoadedInPostLoadDuringIterationWithSimpleObjectHydrator(): void { $this->_em->persist(new LifecycleCallbackTestEntity()); $this->_em->persist(new LifecycleCallbackTestEntity()); @@ -291,7 +299,7 @@ public function testCascadedEntitiesNotLoadedInPostLoadDuringIterationWithSimple /** * https://github.com/doctrine/orm/issues/6568 */ - public function testPostLoadIsInvokedOnFetchJoinedEntities() + public function testPostLoadIsInvokedOnFetchJoinedEntities(): void { $entA = new LifecycleCallbackCascader(); $this->_em->persist($entA); @@ -329,18 +337,18 @@ public function testPostLoadIsInvokedOnFetchJoinedEntities() } } - public function testLifecycleCallbacksGetInherited() + public function testLifecycleCallbacksGetInherited(): void { $childMeta = $this->_em->getClassMetadata(LifecycleCallbackChildEntity::class); $this->assertEquals(['prePersist' => [0 => 'doStuff']], $childMeta->lifecycleCallbacks); } - public function testLifecycleListener_ChangeUpdateChangeSet() + public function testLifecycleListener_ChangeUpdateChangeSet(): void { - $listener = new LifecycleListenerPreUpdate; + $listener = new LifecycleListenerPreUpdate(); $this->_em->getEventManager()->addEventListener(['preUpdate'], $listener); - $user = new LifecycleCallbackTestUser; + $user = new LifecycleCallbackTestUser(); $user->setName('Bob'); $user->setValue('value'); $this->_em->persist($user); @@ -362,11 +370,11 @@ public function testLifecycleListener_ChangeUpdateChangeSet() } /** - * @group DDC-1955 - */ - public function testLifecycleCallbackEventArgs() + * @group DDC-1955 + */ + public function testLifecycleCallbackEventArgs(): void { - $e = new LifecycleCallbackEventArgEntity; + $e = new LifecycleCallbackEventArgEntity(); $e->value = 'foo'; $this->_em->persist($e); @@ -381,7 +389,6 @@ public function testLifecycleCallbackEventArgs() $this->_em->remove($e); $this->_em->flush(); - $this->assertArrayHasKey('preFlushHandler', $e->calls); $this->assertArrayHasKey('postLoadHandler', $e->calls); $this->assertArrayHasKey('prePersistHandler', $e->calls); @@ -403,20 +410,45 @@ public function testLifecycleCallbackEventArgs() } /** @Entity @HasLifecycleCallbacks */ -class LifecycleCallbackTestUser { +class LifecycleCallbackTestUser +{ /** @Id @Column(type="integer") @GeneratedValue */ private $id; /** @Column(type="string") */ private $value; /** @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;} + + public function getId() + { + return $this->id; + } + + public function getValue() + { + return $this->value; + } + + public function setValue($value): void + { + $this->value = $value; + } + + public function getName() + { + return $this->name; + } + + public function setName($name): void + { + $this->name = $name; + } + /** @PreUpdate */ - public function testCallback() {$this->value = 'Hello World';} + public function testCallback(): void + { + $this->value = 'Hello World'; + } } /** @@ -427,20 +459,18 @@ public function testCallback() {$this->value = 'Hello World';} class LifecycleCallbackTestEntity { /* test stuff */ - public $prePersistCallbackInvoked = false; + public $prePersistCallbackInvoked = false; public $postPersistCallbackInvoked = false; - public $postLoadCallbackInvoked = false; - public $postLoadCascaderNotNull = false; - public $preFlushCallbackInvoked = false; + public $postLoadCallbackInvoked = false; + public $postLoadCascaderNotNull = false; + public $preFlushCallbackInvoked = false; /** * @Id @Column(type="integer") * @GeneratedValue(strategy="AUTO") */ private $id; - /** - * @Column(type="string", nullable=true) - */ + /** @Column(type="string", nullable=true) */ public $value; /** @@ -449,37 +479,44 @@ class LifecycleCallbackTestEntity */ public $cascader; - public function getId() { + public function getId() + { return $this->id; } - public function getValue() { + public function getValue() + { return $this->value; } /** @PrePersist */ - public function doStuffOnPrePersist() { + public function doStuffOnPrePersist(): void + { $this->prePersistCallbackInvoked = true; } /** @PostPersist */ - public function doStuffOnPostPersist() { + public function doStuffOnPostPersist(): void + { $this->postPersistCallbackInvoked = true; } /** @PostLoad */ - public function doStuffOnPostLoad() { + public function doStuffOnPostLoad(): void + { $this->postLoadCallbackInvoked = true; $this->postLoadCascaderNotNull = isset($this->cascader); } /** @PreUpdate */ - public function doStuffOnPreUpdate() { + public function doStuffOnPreUpdate(): void + { $this->value = 'changed from preUpdate callback!'; } /** @PreFlush */ - public function doStuffOnPreFlush() { + public function doStuffOnPreFlush(): void + { $this->preFlushCallbackInvoked = true; } } @@ -492,7 +529,7 @@ class LifecycleCallbackCascader { /* test stuff */ public $postLoadCallbackInvoked = false; - public $postLoadEntitiesCount = 0; + public $postLoadEntitiesCount = 0; /** * @Id @Column(type="integer") @@ -500,9 +537,7 @@ class LifecycleCallbackCascader */ private $id; - /** - * @OneToMany(targetEntity="LifecycleCallbackTestEntity", mappedBy="cascader", cascade={"persist"}) - */ + /** @OneToMany(targetEntity="LifecycleCallbackTestEntity", mappedBy="cascader", cascade={"persist"}) */ public $entities; public function __construct() @@ -511,33 +546,37 @@ public function __construct() } /** @PostLoad */ - public function doStuffOnPostLoad() { + public function doStuffOnPostLoad(): void + { $this->postLoadCallbackInvoked = true; - $this->postLoadEntitiesCount = count($this->entities); + $this->postLoadEntitiesCount = count($this->entities); } - public function getId() { + public function getId() + { return $this->id; } } /** @MappedSuperclass @HasLifecycleCallbacks */ -class LifecycleCallbackParentEntity { +class LifecycleCallbackParentEntity +{ /** @PrePersist */ - function doStuff() { - + function doStuff(): void + { } } /** @Entity @Table(name="lc_cb_childentity") */ -class LifecycleCallbackChildEntity extends LifecycleCallbackParentEntity { +class LifecycleCallbackChildEntity extends LifecycleCallbackParentEntity +{ /** @Id @Column(type="integer") @GeneratedValue */ private $id; } class LifecycleListenerPreUpdate { - public function preUpdate(PreUpdateEventArgs $eventArgs) + public function preUpdate(PreUpdateEventArgs $eventArgs): void { $eventArgs->setNewValue('name', 'Bob'); } @@ -557,7 +596,7 @@ class LifecycleCallbackEventArgEntity /** * @PostPersist */ - public function postPersistHandler(LifecycleEventArgs $event) + public function postPersistHandler(LifecycleEventArgs $event): void { $this->calls[__FUNCTION__] = $event; } @@ -565,7 +604,7 @@ public function postPersistHandler(LifecycleEventArgs $event) /** * @PrePersist */ - public function prePersistHandler(LifecycleEventArgs $event) + public function prePersistHandler(LifecycleEventArgs $event): void { $this->calls[__FUNCTION__] = $event; } @@ -573,7 +612,7 @@ public function prePersistHandler(LifecycleEventArgs $event) /** * @PostUpdate */ - public function postUpdateHandler(LifecycleEventArgs $event) + public function postUpdateHandler(LifecycleEventArgs $event): void { $this->calls[__FUNCTION__] = $event; } @@ -581,7 +620,7 @@ public function postUpdateHandler(LifecycleEventArgs $event) /** * @PreUpdate */ - public function preUpdateHandler(PreUpdateEventArgs $event) + public function preUpdateHandler(PreUpdateEventArgs $event): void { $this->calls[__FUNCTION__] = $event; } @@ -589,7 +628,7 @@ public function preUpdateHandler(PreUpdateEventArgs $event) /** * @PostRemove */ - public function postRemoveHandler(LifecycleEventArgs $event) + public function postRemoveHandler(LifecycleEventArgs $event): void { $this->calls[__FUNCTION__] = $event; } @@ -597,7 +636,7 @@ public function postRemoveHandler(LifecycleEventArgs $event) /** * @PreRemove */ - public function preRemoveHandler(LifecycleEventArgs $event) + public function preRemoveHandler(LifecycleEventArgs $event): void { $this->calls[__FUNCTION__] = $event; } @@ -605,7 +644,7 @@ public function preRemoveHandler(LifecycleEventArgs $event) /** * @PreFlush */ - public function preFlushHandler(PreFlushEventArgs $event) + public function preFlushHandler(PreFlushEventArgs $event): void { $this->calls[__FUNCTION__] = $event; } @@ -613,7 +652,7 @@ public function preFlushHandler(PreFlushEventArgs $event) /** * @PostLoad */ - public function postLoadHandler(LifecycleEventArgs $event) + public function postLoadHandler(LifecycleEventArgs $event): void { $this->calls[__FUNCTION__] = $event; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Locking/GearmanLockTest.php b/tests/Doctrine/Tests/ORM/Functional/Locking/GearmanLockTest.php index 5f58f5ea3e1..ed53e29c37a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Locking/GearmanLockTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/Locking/GearmanLockTest.php @@ -1,23 +1,30 @@ markTestSkipped('pecl/gearman is required for this test to run.'); } @@ -25,16 +32,16 @@ protected function setUp() : void parent::setUp(); $this->tasks = []; - $this->gearman = new \GearmanClient(); + $this->gearman = new GearmanClient(); $this->gearman->addServer( $_SERVER['GEARMAN_HOST'] ?? null, $_SERVER['GEARMAN_PORT'] ?? 4730 ); - $this->gearman->setCompleteCallback([$this, "gearmanTaskCompleted"]); + $this->gearman->setCompleteCallback([$this, 'gearmanTaskCompleted']); - $article = new CmsArticle(); - $article->text = "my article"; - $article->topic = "Hello"; + $article = new CmsArticle(); + $article->text = 'my article'; + $article->topic = 'Hello'; $this->_em->persist($article); $this->_em->flush(); @@ -42,12 +49,12 @@ protected function setUp() : void $this->articleId = $article->id; } - public function gearmanTaskCompleted($task) + public function gearmanTaskCompleted($task): void { $this->maxRunTime = max($this->maxRunTime, $task->data()); } - public function testFindWithLock() + public function testFindWithLock(): void { $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); @@ -55,7 +62,7 @@ public function testFindWithLock() $this->assertLockWorked(); } - public function testFindWithWriteThenReadLock() + public function testFindWithWriteThenReadLock(): void { $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_READ); @@ -63,7 +70,7 @@ public function testFindWithWriteThenReadLock() $this->assertLockWorked(); } - public function testFindWithReadThenWriteLock() + public function testFindWithReadThenWriteLock(): void { $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_READ); $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); @@ -71,7 +78,7 @@ public function testFindWithReadThenWriteLock() $this->assertLockWorked(); } - public function testFindWithOneLock() + public function testFindWithOneLock(): void { $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::NONE); @@ -79,7 +86,7 @@ public function testFindWithOneLock() $this->assertLockDoesNotBlock(); } - public function testDqlWithLock() + public function testDqlWithLock(): void { $this->asyncDqlWithLock('SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a', [], LockMode::PESSIMISTIC_WRITE); $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); @@ -87,7 +94,7 @@ public function testDqlWithLock() $this->assertLockWorked(); } - public function testLock() + public function testLock(): void { $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); $this->asyncLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); @@ -95,7 +102,7 @@ public function testLock() $this->assertLockWorked(); } - public function testLock2() + public function testLock2(): void { $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); $this->asyncLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_READ); @@ -103,7 +110,7 @@ public function testLock2() $this->assertLockWorked(); } - public function testLock3() + public function testLock3(): void { $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_READ); $this->asyncLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); @@ -111,7 +118,7 @@ public function testLock3() $this->assertLockWorked(); } - public function testLock4() + public function testLock4(): void { $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::NONE); $this->asyncLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); @@ -119,12 +126,12 @@ public function testLock4() $this->assertLockDoesNotBlock(); } - protected function assertLockDoesNotBlock() + protected function assertLockDoesNotBlock(): void { $this->assertLockWorked($onlyForSeconds = 1); } - protected function assertLockWorked($forTime = 2, $notLongerThan = null) + protected function assertLockWorked($forTime = 2, $notLongerThan = null): void { if ($notLongerThan === null) { $notLongerThan = $forTime + 1; @@ -132,51 +139,51 @@ protected function assertLockWorked($forTime = 2, $notLongerThan = null) $this->gearman->runTasks(); - $this->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, - "The longest task should not run longer than " . $notLongerThan . " seconds, ". - "but did for " . $this->maxRunTime . " seconds." + $this->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, + 'The longest task should not run longer than ' . $notLongerThan . ' seconds, ' . + 'but did for ' . $this->maxRunTime . ' seconds.' ); } - protected function asyncFindWithLock($entityName, $entityId, $lockMode) + protected function asyncFindWithLock($entityName, $entityId, $lockMode): void { $this->startJob('findWithLock', [ 'entityName' => $entityName, 'entityId' => $entityId, 'lockMode' => $lockMode, - ] - ); + ]); } - protected function asyncDqlWithLock($dql, $params, $lockMode) + protected function asyncDqlWithLock($dql, $params, $lockMode): void { $this->startJob('dqlWithLock', [ 'dql' => $dql, 'dqlParams' => $params, 'lockMode' => $lockMode, - ] - ); + ]); } - protected function asyncLock($entityName, $entityId, $lockMode) + protected function asyncLock($entityName, $entityId, $lockMode): void { $this->startJob('lock', [ 'entityName' => $entityName, 'entityId' => $entityId, 'lockMode' => $lockMode, - ] - ); + ]); } - protected function startJob($fn, $fixture) + protected function startJob($fn, $fixture): void { $this->gearman->addTask($fn, serialize( [ - 'conn' => $this->_em->getConnection()->getParams(), - 'fixture' => $fixture + 'conn' => $this->_em->getConnection()->getParams(), + 'fixture' => $fixture, ] )); diff --git a/tests/Doctrine/Tests/ORM/Functional/Locking/LockAgentWorker.php b/tests/Doctrine/Tests/ORM/Functional/Locking/LockAgentWorker.php index 4271b12b476..bd2fd6eb7d7 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Locking/LockAgentWorker.php +++ b/tests/Doctrine/Tests/ORM/Functional/Locking/LockAgentWorker.php @@ -1,38 +1,49 @@ addServer( $_SERVER['GEARMAN_HOST'] ?? null, $_SERVER['GEARMAN_PORT'] ?? 4730 ); - $worker->addFunction("findWithLock", [$lockAgent, "findWithLock"]); - $worker->addFunction("dqlWithLock", [$lockAgent, "dqlWithLock"]); + $worker->addFunction('findWithLock', [$lockAgent, 'findWithLock']); + $worker->addFunction('dqlWithLock', [$lockAgent, 'dqlWithLock']); $worker->addFunction('lock', [$lockAgent, 'lock']); - while($worker->work()) { - if ($worker->returnCode() != GEARMAN_SUCCESS) { - echo "return_code: " . $worker->returnCode() . "\n"; + while ($worker->work()) { + if ($worker->returnCode() !== GEARMAN_SUCCESS) { + echo 'return_code: ' . $worker->returnCode() . "\n"; break; } } } - protected function process($job, \Closure $do) + protected function process($job, Closure $do) { $fixture = $this->processWorkload($job); @@ -46,21 +57,21 @@ protected function process($job, \Closure $do) $this->em->close(); $this->em->getConnection()->close(); - return (microtime(true) - $s); + return microtime(true) - $s; } public function findWithLock($job) { - return $this->process($job, function($fixture, $em) { + return $this->process($job, static function ($fixture, $em): void { $entity = $em->find($fixture['entityName'], $fixture['entityId'], $fixture['lockMode']); }); } public function dqlWithLock($job) { - return $this->process($job, function($fixture, $em) { - /* @var $query Doctrine\ORM\Query */ + return $this->process($job, static function ($fixture, $em): void { $query = $em->createQuery($fixture['dql']); + assert($query instanceof Doctrine\ORM\Query); $query->setLockMode($fixture['lockMode']); $query->setParameters($fixture['dqlParams']); $result = $query->getResult(); @@ -69,7 +80,7 @@ public function dqlWithLock($job) public function lock($job) { - return $this->process($job, function($fixture, $em) { + return $this->process($job, static function ($fixture, $em): void { $entity = $em->find($fixture['entityName'], $fixture['entityId']); $em->lock($entity, $fixture['lockMode']); }); @@ -77,20 +88,21 @@ public function lock($job) protected function processWorkload($job) { - echo "Received job: " . $job->handle() . " for function " . $job->functionName() . "\n"; + echo 'Received job: ' . $job->handle() . ' for function ' . $job->functionName() . "\n"; $workload = $job->workload(); $workload = unserialize($workload); - if (!isset($workload['conn']) || !is_array($workload['conn'])) { - throw new \InvalidArgumentException("Missing Database parameters"); + if (! isset($workload['conn']) || ! is_array($workload['conn'])) { + throw new InvalidArgumentException('Missing Database parameters'); } $this->em = $this->createEntityManager($workload['conn']); - if (!isset($workload['fixture'])) { - throw new \InvalidArgumentException("Missing Fixture parameters"); + if (! isset($workload['fixture'])) { + throw new InvalidArgumentException('Missing Fixture parameters'); } + return $workload['fixture']; } @@ -109,9 +121,7 @@ protected function createEntityManager($conn) $config->setQueryCacheImpl($cache); $config->setSQLLogger(new EchoSQLLogger()); - $em = EntityManager::create($conn, $config); - - return $em; + return EntityManager::create($conn, $config); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Locking/LockTest.php b/tests/Doctrine/Tests/ORM/Functional/Locking/LockTest.php index 9c093379400..a8ea0237cec 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Locking/LockTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/Locking/LockTest.php @@ -1,5 +1,7 @@ useModelSet('cms'); parent::setUp(); @@ -27,11 +33,11 @@ protected function setUp() : void * @group DDC-178 * @group locking */ - public function testLockVersionedEntity() + public function testLockVersionedEntity(): void { - $article = new CmsArticle(); - $article->text = "my article"; - $article->topic = "Hello"; + $article = new CmsArticle(); + $article->text = 'my article'; + $article->topic = 'Hello'; $this->_em->persist($article); $this->_em->flush(); @@ -45,11 +51,11 @@ public function testLockVersionedEntity() * @group DDC-178 * @group locking */ - public function testLockVersionedEntity_MismatchThrowsException() + public function testLockVersionedEntity_MismatchThrowsException(): void { - $article = new CmsArticle(); - $article->text = "my article"; - $article->topic = "Hello"; + $article = new CmsArticle(); + $article->text = 'my article'; + $article->topic = 'Hello'; $this->_em->persist($article); $this->_em->flush(); @@ -63,12 +69,12 @@ public function testLockVersionedEntity_MismatchThrowsException() * @group DDC-178 * @group locking */ - public function testLockUnversionedEntity_ThrowsException() + public function testLockUnversionedEntity_ThrowsException(): void { - $user = new CmsUser(); - $user->name = "foo"; - $user->status = "active"; - $user->username = "foo"; + $user = new CmsUser(); + $user->name = 'foo'; + $user->status = 'active'; + $user->username = 'foo'; $this->_em->persist($user); $this->_em->flush(); @@ -82,11 +88,11 @@ public function testLockUnversionedEntity_ThrowsException() * @group DDC-178 * @group locking */ - public function testLockUnmanagedEntity_ThrowsException() + public function testLockUnmanagedEntity_ThrowsException(): void { $article = new CmsArticle(); - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Entity ' . CmsArticle::class); $this->_em->lock($article, LockMode::OPTIMISTIC, $article->version + 1); @@ -96,11 +102,11 @@ public function testLockUnmanagedEntity_ThrowsException() * @group DDC-178 * @group locking */ - public function testLockPessimisticRead_NoTransaction_ThrowsException() + public function testLockPessimisticRead_NoTransaction_ThrowsException(): void { - $article = new CmsArticle(); - $article->text = "my article"; - $article->topic = "Hello"; + $article = new CmsArticle(); + $article->text = 'my article'; + $article->topic = 'Hello'; $this->_em->persist($article); $this->_em->flush(); @@ -114,11 +120,11 @@ public function testLockPessimisticRead_NoTransaction_ThrowsException() * @group DDC-178 * @group locking */ - public function testLockPessimisticWrite_NoTransaction_ThrowsException() + public function testLockPessimisticWrite_NoTransaction_ThrowsException(): void { - $article = new CmsArticle(); - $article->text = "my article"; - $article->topic = "Hello"; + $article = new CmsArticle(); + $article->text = 'my article'; + $article->topic = 'Hello'; $this->_em->persist($article); $this->_em->flush(); @@ -132,7 +138,7 @@ public function testLockPessimisticWrite_NoTransaction_ThrowsException() * @group DDC-178 * @group locking */ - public function testLockPessimisticWrite() + public function testLockPessimisticWrite(): void { $writeLockSql = $this->_em->getConnection()->getDatabasePlatform()->getWriteLockSQL(); @@ -140,9 +146,9 @@ public function testLockPessimisticWrite() $this->markTestSkipped('Database Driver has no Write Lock support.'); } - $article = new CmsArticle(); - $article->text = "my article"; - $article->topic = "Hello"; + $article = new CmsArticle(); + $article->text = 'my article'; + $article->topic = 'Hello'; $this->_em->persist($article); $this->_em->flush(); @@ -151,20 +157,21 @@ public function testLockPessimisticWrite() try { $this->_em->lock($article, LockMode::PESSIMISTIC_WRITE); $this->_em->commit(); - } catch (\Exception $e) { + } catch (Exception $e) { $this->_em->rollback(); + throw $e; } - $query = array_pop( $this->_sqlLoggerStack->queries ); - $query = array_pop( $this->_sqlLoggerStack->queries ); + $query = array_pop($this->_sqlLoggerStack->queries); + $query = array_pop($this->_sqlLoggerStack->queries); $this->assertContains($writeLockSql, $query['sql']); } /** * @group DDC-178 */ - public function testLockPessimisticRead() + public function testLockPessimisticRead(): void { $readLockSql = $this->_em->getConnection()->getDatabasePlatform()->getReadLockSQL(); @@ -172,9 +179,9 @@ public function testLockPessimisticRead() $this->markTestSkipped('Database Driver has no Write Lock support.'); } - $article = new CmsArticle(); - $article->text = "my article"; - $article->topic = "Hello"; + $article = new CmsArticle(); + $article->text = 'my article'; + $article->topic = 'Hello'; $this->_em->persist($article); $this->_em->flush(); @@ -184,8 +191,9 @@ public function testLockPessimisticRead() try { $this->_em->lock($article, LockMode::PESSIMISTIC_READ); $this->_em->commit(); - } catch (\Exception $e) { + } catch (Exception $e) { $this->_em->rollback(); + throw $e; } @@ -198,9 +206,9 @@ public function testLockPessimisticRead() /** * @group DDC-1693 */ - public function testLockOptimisticNonVersionedThrowsExceptionInDQL() + public function testLockOptimisticNonVersionedThrowsExceptionInDQL(): void { - $dql = "SELECT u FROM " . CmsUser::class . " u WHERE u.username = 'gblanco'"; + $dql = 'SELECT u FROM ' . CmsUser::class . " u WHERE u.username = 'gblanco'"; $this->expectException(OptimisticLockException::class); $this->expectExceptionMessage('The optimistic lock on an entity failed.'); diff --git a/tests/Doctrine/Tests/ORM/Functional/Locking/OptimisticTest.php b/tests/Doctrine/Tests/ORM/Functional/Locking/OptimisticTest.php index 4d8711c97e2..39ec7230c82 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Locking/OptimisticTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/Locking/OptimisticTest.php @@ -1,15 +1,21 @@ _em->getClassMetadata(OptimisticJoinedParent::class), $this->_em->getClassMetadata(OptimisticJoinedChild::class), $this->_em->getClassMetadata(OptimisticStandard::class), - $this->_em->getClassMetadata(OptimisticTimestamp::class) + $this->_em->getClassMetadata(OptimisticTimestamp::class), ] ); - } catch (\Exception $e) { + } catch (Exception $e) { // Swallow all exceptions. We do not test the schema tool here. } @@ -33,7 +39,7 @@ public function testJoinedChildInsertSetsInitialVersionValue() { $test = new OptimisticJoinedChild(); - $test->name = 'child'; + $test->name = 'child'; $test->whatever = 'whatever'; $this->_em->persist($test); @@ -47,7 +53,7 @@ public function testJoinedChildInsertSetsInitialVersionValue() /** * @depends testJoinedChildInsertSetsInitialVersionValue */ - public function testJoinedChildFailureThrowsException(OptimisticJoinedChild $child) + public function testJoinedChildFailureThrowsException(OptimisticJoinedChild $child): void { $q = $this->_em->createQuery('SELECT t FROM Doctrine\Tests\ORM\Functional\Locking\OptimisticJoinedChild t WHERE t.id = :id'); @@ -87,7 +93,7 @@ public function testJoinedParentInsertSetsInitialVersionValue() /** * @depends testJoinedParentInsertSetsInitialVersionValue */ - public function testJoinedParentFailureThrowsException(OptimisticJoinedParent $parent) + public function testJoinedParentFailureThrowsException(OptimisticJoinedParent $parent): void { $q = $this->_em->createQuery('SELECT t FROM Doctrine\Tests\ORM\Functional\Locking\OptimisticJoinedParent t WHERE t.id = :id'); @@ -110,7 +116,7 @@ public function testJoinedParentFailureThrowsException(OptimisticJoinedParent $p } } - public function testMultipleFlushesDoIncrementalUpdates() + public function testMultipleFlushesDoIncrementalUpdates(): void { $test = new OptimisticStandard(); @@ -143,7 +149,7 @@ public function testStandardInsertSetsInitialVersionValue() /** * @depends testStandardInsertSetsInitialVersionValue */ - public function testStandardFailureThrowsException(OptimisticStandard $entity) + public function testStandardFailureThrowsException(OptimisticStandard $entity): void { $q = $this->_em->createQuery('SELECT t FROM Doctrine\Tests\ORM\Functional\Locking\OptimisticStandard t WHERE t.id = :id'); @@ -166,9 +172,9 @@ public function testStandardFailureThrowsException(OptimisticStandard $entity) } } - public function testLockWorksWithProxy() + public function testLockWorksWithProxy(): void { - $test = new OptimisticStandard(); + $test = new OptimisticStandard(); $test->name = 'test'; $this->_em->persist($test); @@ -188,7 +194,7 @@ public function testOptimisticTimestampSetsDefaultValue() $test->name = 'Testing'; - $this->assertNull($test->version, "Pre-Condition"); + $this->assertNull($test->version, 'Pre-Condition'); $this->_em->persist($test); $this->_em->flush(); @@ -201,7 +207,7 @@ public function testOptimisticTimestampSetsDefaultValue() /** * @depends testOptimisticTimestampSetsDefaultValue */ - public function testOptimisticTimestampFailureThrowsException(OptimisticTimestamp $entity) + public function testOptimisticTimestampFailureThrowsException(OptimisticTimestamp $entity): void { $q = $this->_em->createQuery('SELECT t FROM Doctrine\Tests\ORM\Functional\Locking\OptimisticTimestamp t WHERE t.id = :id'); @@ -214,12 +220,11 @@ public function testOptimisticTimestampFailureThrowsException(OptimisticTimestam // Manually increment the version datetime column $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 $caughtException = null; - $test->name = 'Testing again'; + $test->name = 'Testing again'; try { $this->_em->flush(); @@ -227,15 +232,14 @@ public function testOptimisticTimestampFailureThrowsException(OptimisticTimestam $caughtException = $e; } - $this->assertNotNull($caughtException, "No OptimisticLockingException was thrown"); + $this->assertNotNull($caughtException, 'No OptimisticLockingException was thrown'); $this->assertSame($test, $caughtException->getEntity()); - } /** * @depends testOptimisticTimestampSetsDefaultValue */ - public function testOptimisticTimestampLockFailureThrowsException(OptimisticTimestamp $entity) + public function testOptimisticTimestampLockFailureThrowsException(OptimisticTimestamp $entity): void { $q = $this->_em->createQuery('SELECT t FROM Doctrine\Tests\ORM\Functional\Locking\OptimisticTimestamp t WHERE t.id = :id'); @@ -249,18 +253,16 @@ public function testOptimisticTimestampLockFailureThrowsException(OptimisticTime $caughtException = null; try { - $expectedVersionExpired = DateTime::createFromFormat('U', $test->version->getTimestamp()-3600); + $expectedVersionExpired = DateTime::createFromFormat('U', $test->version->getTimestamp() - 3600); $this->_em->lock($test, LockMode::OPTIMISTIC, $expectedVersionExpired); } catch (OptimisticLockException $e) { $caughtException = $e; } - $this->assertNotNull($caughtException, "No OptimisticLockingException was thrown"); + $this->assertNotNull($caughtException, 'No OptimisticLockingException was thrown'); $this->assertSame($test, $caughtException->getEntity()); - } - } /** @@ -278,14 +280,10 @@ class OptimisticJoinedParent */ public $id; - /** - * @Column(type="string", length=255) - */ + /** @Column(type="string", length=255) */ public $name; - /** - * @Version @Column(type="integer") - */ + /** @Version @Column(type="integer") */ public $version; } @@ -295,9 +293,7 @@ class OptimisticJoinedParent */ class OptimisticJoinedChild extends OptimisticJoinedParent { - /** - * @Column(type="string", length=255) - */ + /** @Column(type="string", length=255) */ public $whatever; } @@ -313,14 +309,10 @@ class OptimisticStandard */ public $id; - /** - * @Column(type="string", length=255) - */ + /** @Column(type="string", length=255) */ public $name; - /** - * @Version @Column(type="integer") - */ + /** @Version @Column(type="integer") */ private $version; public function getVersion() @@ -341,13 +333,9 @@ class OptimisticTimestamp */ public $id; - /** - * @Column(type="string", length=255) - */ + /** @Column(type="string", length=255) */ public $name; - /** - * @Version @Column(type="datetime") - */ + /** @Version @Column(type="datetime") */ public $version; } diff --git a/tests/Doctrine/Tests/ORM/Functional/ManyToManyBasicAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/ManyToManyBasicAssociationTest.php index bacacd567bb..079ab94fa54 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ManyToManyBasicAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ManyToManyBasicAssociationTest.php @@ -1,5 +1,7 @@ useModelSet('cms'); parent::setUp(); } - public function testUnsetManyToMany() + public function testUnsetManyToMany(): void { $user = $this->addCmsUserGblancoWithGroups(1); @@ -38,14 +42,14 @@ public function testUnsetManyToMany() $this->assertGblancoGroupCountIs(0); } - public function testBasicManyToManyJoin() + public function testBasicManyToManyJoin(): void { $user = $this->addCmsUserGblancoWithGroups(1); $this->_em->clear(); $this->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(); @@ -68,11 +72,11 @@ public function testBasicManyToManyJoin() $this->_em->flush(); $this->_em->clear(); - $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'); $this->assertEquals(0, count($query->getResult())); } - public function testManyToManyAddRemove() + public function testManyToManyAddRemove(): void { $user = $this->addCmsUserGblancoWithGroups(2); $this->_em->clear(); @@ -82,7 +86,7 @@ public function testManyToManyAddRemove() // Get user $user = $uRep->findOneById($user->getId()); - $this->assertNotNull($user, "Has to return exactly one entry."); + $this->assertNotNull($user, 'Has to return exactly one entry.'); $this->assertFalse($user->getGroups()->isInitialized()); @@ -105,11 +109,11 @@ public function testManyToManyAddRemove() $this->assertEquals(1, $user2->getGroups()->count()); } - public function testManyToManyInverseSideIgnored() + public function testManyToManyInverseSideIgnored(): void { $user = $this->addCmsUserGblancoWithGroups(0); - $group = new CmsGroup; + $group = new CmsGroup(); $group->name = 'Humans'; // modify directly, addUser() would also (properly) set the owning side @@ -123,11 +127,11 @@ public function testManyToManyInverseSideIgnored() // Association should not exist $user2 = $this->_em->find(get_class($user), $user->getId()); - $this->assertNotNull($user2, "Has to return exactly one entry."); + $this->assertNotNull($user2, 'Has to return exactly one entry.'); $this->assertEquals(0, $user2->getGroups()->count()); } - public function testManyToManyCollectionClearing() + public function testManyToManyCollectionClearing(): void { $user = $this->addCmsUserGblancoWithGroups($groupCount = 10); @@ -142,31 +146,28 @@ public function testManyToManyCollectionClearing() $this->assertGblancoGroupCountIs(0); } - public function testManyToManyCollectionClearAndAdd() + public function testManyToManyCollectionClearAndAdd(): void { $user = $this->addCmsUserGblancoWithGroups($groupCount = 10); $groups = $user->groups->toArray(); $user->groups->clear(); - foreach ($groups AS $group) { + foreach ($groups as $group) { $user->groups[] = $group; } $this->assertInstanceOf(PersistentCollection::class, $user->groups); $this->assertTrue($user->groups->isDirty()); - $this->assertEquals($groupCount, count($user->groups), "There should be 10 groups in the collection."); + $this->assertEquals($groupCount, count($user->groups), 'There should be 10 groups in the collection.'); $this->_em->flush(); $this->assertGblancoGroupCountIs($groupCount); } - /** - * @param int $expectedGroupCount - */ - public function assertGblancoGroupCountIs($expectedGroupCount) + public function assertGblancoGroupCountIs(int $expectedGroupCount): void { $countDql = "SELECT count(g.id) FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.groups g WHERE u.username = 'gblanco'"; $this->assertEquals( @@ -176,30 +177,30 @@ public function assertGblancoGroupCountIs($expectedGroupCount) ); } - public function testRetrieveManyToManyAndAddMore() + public function testRetrieveManyToManyAndAddMore(): void { $user = $this->addCmsUserGblancoWithGroups(2); - $group = new CmsGroup(); + $group = new CmsGroup(); $group->name = 'Developers_Fresh'; $this->_em->persist($group); $this->_em->flush(); $this->_em->clear(); - /* @var $freshUser CmsUser */ $freshUser = $this->_em->find(CmsUser::class, $user->getId()); + assert($freshUser instanceof CmsUser); $newGroup = new CmsGroup(); $newGroup->setName('12Monkeys'); $freshUser->addGroup($newGroup); - $this->assertFalse($freshUser->groups->isInitialized(), "CmsUser::groups Collection has to be uninitialized for this test."); + $this->assertFalse($freshUser->groups->isInitialized(), 'CmsUser::groups Collection has to be uninitialized for this test.'); $this->_em->flush(); - $this->assertFalse($freshUser->groups->isInitialized(), "CmsUser::groups Collection has to be uninitialized for this test."); + $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."); + $this->assertEquals(3, count($freshUser->getGroups()->getSnapshot()), 'Snapshot of CmsUser::groups should contain 3 entries.'); $this->_em->clear(); @@ -210,9 +211,9 @@ public function testRetrieveManyToManyAndAddMore() /** * @group DDC-130 */ - public function testRemoveUserWithManyGroups() + public function testRemoveUserWithManyGroups(): void { - $user = $this->addCmsUserGblancoWithGroups(2); + $user = $this->addCmsUserGblancoWithGroups(2); $userId = $user->getId(); $this->_em->remove($user); @@ -225,13 +226,14 @@ public function testRemoveUserWithManyGroups() /** * @group DDC-130 */ - public function testRemoveGroupWithUser() + public function testRemoveGroupWithUser(): void { $user = $this->addCmsUserGblancoWithGroups(2); - foreach ($user->getGroups() AS $group) { + foreach ($user->getGroups() as $group) { $this->_em->remove($group); } + $this->_em->flush(); $this->_em->clear(); @@ -239,9 +241,9 @@ public function testRemoveGroupWithUser() $this->assertEquals(0, count($newUser->getGroups())); } - public function testDereferenceCollectionDelete() + public function testDereferenceCollectionDelete(): void { - $user = $this->addCmsUserGblancoWithGroups(2); + $user = $this->addCmsUserGblancoWithGroups(2); $user->groups = null; $this->_em->flush(); @@ -254,11 +256,11 @@ public function testDereferenceCollectionDelete() /** * @group DDC-839 */ - public function testWorkWithDqlHydratedEmptyCollection() + public function testWorkWithDqlHydratedEmptyCollection(): void { - $user = $this->addCmsUserGblancoWithGroups(0); - $group = new CmsGroup(); - $group->name = "Developers0"; + $user = $this->addCmsUserGblancoWithGroups(0); + $group = new CmsGroup(); + $group->name = 'Developers0'; $this->_em->persist($group); $this->_em->flush(); @@ -279,19 +281,15 @@ public function testWorkWithDqlHydratedEmptyCollection() $this->assertEquals(1, count($newUser->groups)); } - /** - * @param int $groupCount - * @return CmsUser - */ - public function addCmsUserGblancoWithGroups($groupCount = 1) + public function addCmsUserGblancoWithGroups(int $groupCount = 1): CmsUser { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; - for ($i=0; $i < $groupCount; ++$i) { - $group = new CmsGroup; + for ($i = 0; $i < $groupCount; ++$i) { + $group = new CmsGroup(); $group->name = 'Developers_' . $i; $user->addGroup($group); } @@ -307,12 +305,12 @@ public function addCmsUserGblancoWithGroups($groupCount = 1) /** * @group DDC-978 */ - public function testClearAndResetCollection() + public function testClearAndResetCollection(): void { - $user = $this->addCmsUserGblancoWithGroups(2); - $group1 = new CmsGroup; + $user = $this->addCmsUserGblancoWithGroups(2); + $group1 = new CmsGroup(); $group1->name = 'Developers_New1'; - $group2 = new CmsGroup; + $group2 = new CmsGroup(); $group2->name = 'Developers_New2'; $this->_em->persist($group1); @@ -322,11 +320,14 @@ public function testClearAndResetCollection() $user = $this->_em->find(get_class($user), $user->id); - $coll = new ArrayCollection([$group1, $group2]); + $coll = new ArrayCollection([$group1, $group2]); $user->groups = $coll; $this->_em->flush(); - $this->assertInstanceOf(PersistentCollection::class, $user->groups, - "UnitOfWork should have replaced ArrayCollection with PersistentCollection."); + $this->assertInstanceOf( + PersistentCollection::class, + $user->groups, + 'UnitOfWork should have replaced ArrayCollection with PersistentCollection.' + ); $this->_em->flush(); $this->_em->clear(); @@ -340,23 +341,23 @@ public function testClearAndResetCollection() /** * @group DDC-733 */ - public function testInitializePersistentCollection() + public function testInitializePersistentCollection(): void { $user = $this->addCmsUserGblancoWithGroups(2); $this->_em->clear(); $user = $this->_em->find(get_class($user), $user->id); - $this->assertFalse($user->groups->isInitialized(), "Pre-condition: lazy collection"); + $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()"); + $this->assertTrue($user->groups->isInitialized(), 'Collection should be initialized after calling UnitOfWork::initializeObject()'); } /** * @group DDC-1189 * @group DDC-956 */ - public function testClearBeforeLazyLoad() + public function testClearBeforeLazyLoad(): void { $user = $this->addCmsUserGblancoWithGroups(4); @@ -375,13 +376,13 @@ public function testClearBeforeLazyLoad() /** * @group DDC-3952 */ - public function testManyToManyOrderByIsNotIgnored() + public function testManyToManyOrderByIsNotIgnored(): void { $user = $this->addCmsUserGblancoWithGroups(1); - $group1 = new CmsGroup; - $group2 = new CmsGroup; - $group3 = new CmsGroup; + $group1 = new CmsGroup(); + $group2 = new CmsGroup(); + $group3 = new CmsGroup(); $group1->name = 'C'; $group2->name = 'A'; @@ -406,7 +407,7 @@ public function testManyToManyOrderByIsNotIgnored() $user ->getGroups() ->matching($criteria) - ->map(function (CmsGroup $group) { + ->map(static function (CmsGroup $group) { return $group->getName(); }) ->toArray() @@ -416,16 +417,16 @@ public function testManyToManyOrderByIsNotIgnored() /** * @group DDC-3952 */ - public function testManyToManyOrderByHonorsFieldNameColumnNameAliases() + public function testManyToManyOrderByHonorsFieldNameColumnNameAliases(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; - $tag1 = new CmsTag; - $tag2 = new CmsTag; - $tag3 = new CmsTag; + $tag1 = new CmsTag(); + $tag2 = new CmsTag(); + $tag3 = new CmsTag(); $tag1->name = 'C'; $tag2->name = 'A'; @@ -450,14 +451,14 @@ public function testManyToManyOrderByHonorsFieldNameColumnNameAliases() $user ->getTags() ->matching($criteria) - ->map(function (CmsTag $tag) { + ->map(static function (CmsTag $tag) { return $tag->getName(); }) ->toArray() ); } - public function testMatchingWithLimit() + public function testMatchingWithLimit(): void { $user = $this->addCmsUserGblancoWithGroups(2); $this->_em->clear(); @@ -465,17 +466,17 @@ public function testMatchingWithLimit() $user = $this->_em->find(get_class($user), $user->id); $groups = $user->groups; - $this->assertFalse($user->groups->isInitialized(), "Pre-condition: lazy collection"); + $this->assertFalse($user->groups->isInitialized(), 'Pre-condition: lazy collection'); $criteria = Criteria::create()->setMaxResults(1); $result = $groups->matching($criteria); $this->assertCount(1, $result); - $this->assertFalse($user->groups->isInitialized(), "Post-condition: matching does not initialize collection"); + $this->assertFalse($user->groups->isInitialized(), 'Post-condition: matching does not initialize collection'); } - public function testMatchingWithOffset() + public function testMatchingWithOffset(): void { $user = $this->addCmsUserGblancoWithGroups(2); $this->_em->clear(); @@ -483,7 +484,7 @@ public function testMatchingWithOffset() $user = $this->_em->find(get_class($user), $user->id); $groups = $user->groups; - $this->assertFalse($user->groups->isInitialized(), "Pre-condition: lazy collection"); + $this->assertFalse($user->groups->isInitialized(), 'Pre-condition: lazy collection'); $criteria = Criteria::create()->setFirstResult(1); $result = $groups->matching($criteria); @@ -493,10 +494,10 @@ public function testMatchingWithOffset() $firstGroup = $result->first(); $this->assertEquals('Developers_1', $firstGroup->name); - $this->assertFalse($user->groups->isInitialized(), "Post-condition: matching does not initialize collection"); + $this->assertFalse($user->groups->isInitialized(), 'Post-condition: matching does not initialize collection'); } - public function testMatchingWithLimitAndOffset() + public function testMatchingWithLimitAndOffset(): void { $user = $this->addCmsUserGblancoWithGroups(5); $this->_em->clear(); @@ -504,7 +505,7 @@ public function testMatchingWithLimitAndOffset() $user = $this->_em->find(get_class($user), $user->id); $groups = $user->groups; - $this->assertFalse($user->groups->isInitialized(), "Pre-condition: lazy collection"); + $this->assertFalse($user->groups->isInitialized(), 'Pre-condition: lazy collection'); $criteria = Criteria::create()->setFirstResult(1)->setMaxResults(3); $result = $groups->matching($criteria); @@ -517,10 +518,10 @@ public function testMatchingWithLimitAndOffset() $lastGroup = $result->last(); $this->assertEquals('Developers_3', $lastGroup->name); - $this->assertFalse($user->groups->isInitialized(), "Post-condition: matching does not initialize collection"); + $this->assertFalse($user->groups->isInitialized(), 'Post-condition: matching does not initialize collection'); } - public function testMatching() + public function testMatching(): void { $user = $this->addCmsUserGblancoWithGroups(2); $this->_em->clear(); @@ -528,7 +529,7 @@ public function testMatching() $user = $this->_em->find(get_class($user), $user->id); $groups = $user->groups; - $this->assertFalse($user->groups->isInitialized(), "Pre-condition: lazy collection"); + $this->assertFalse($user->groups->isInitialized(), 'Pre-condition: lazy collection'); $criteria = Criteria::create()->where(Criteria::expr()->eq('name', (string) 'Developers_0')); $result = $groups->matching($criteria); @@ -538,6 +539,6 @@ public function testMatching() $firstGroup = $result->first(); $this->assertEquals('Developers_0', $firstGroup->name); - $this->assertFalse($user->groups->isInitialized(), "Post-condition: matching does not initialize collection"); + $this->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 80e639aaf74..d23258e527e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ManyToManyBidirectionalAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ManyToManyBidirectionalAssociationTest.php @@ -1,11 +1,13 @@ useModelSet('ecommerce'); parent::setUp(); $this->firstProduct = new ECommerceProduct(); - $this->firstProduct->setName("First Product"); + $this->firstProduct->setName('First Product'); $this->secondProduct = new ECommerceProduct(); - $this->secondProduct->setName("Second Product"); + $this->secondProduct->setName('Second Product'); $this->firstCategory = new ECommerceCategory(); - $this->firstCategory->setName("Business"); + $this->firstCategory->setName('Business'); $this->secondCategory = new ECommerceCategory(); - $this->secondCategory->setName("Home"); + $this->secondCategory->setName('Home'); } - public function testSavesAManyToManyAssociationWithCascadeSaveSet() + public function testSavesAManyToManyAssociationWithCascadeSaveSet(): void { $this->firstProduct->addCategory($this->firstCategory); $this->firstProduct->addCategory($this->secondCategory); @@ -46,7 +48,7 @@ public function testSavesAManyToManyAssociationWithCascadeSaveSet() $this->assertForeignKeysContain($this->firstProduct->getId(), $this->secondCategory->getId()); } - public function testRemovesAManyToManyAssociation() + public function testRemovesAManyToManyAssociation(): void { $this->firstProduct->addCategory($this->firstCategory); $this->firstProduct->addCategory($this->secondCategory); @@ -64,7 +66,7 @@ public function testRemovesAManyToManyAssociation() $this->assertForeignKeysNotContain($this->firstProduct->getId(), $this->secondCategory->getId()); } - public function testEagerLoadFromInverseSideAndLazyLoadFromOwningSide() + public function testEagerLoadFromInverseSideAndLazyLoadFromOwningSide(): void { //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); $this->_createLoadingFixture(); @@ -72,7 +74,7 @@ public function testEagerLoadFromInverseSideAndLazyLoadFromOwningSide() $this->assertLazyLoadFromOwningSide($categories); } - public function testEagerLoadFromOwningSideAndLazyLoadFromInverseSide() + public function testEagerLoadFromOwningSideAndLazyLoadFromInverseSide(): void { //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); $this->_createLoadingFixture(); @@ -80,7 +82,7 @@ public function testEagerLoadFromOwningSideAndLazyLoadFromInverseSide() $this->assertLazyLoadFromInverseSide($products); } - private function _createLoadingFixture() + private function _createLoadingFixture(): void { $this->firstProduct->addCategory($this->firstCategory); $this->firstProduct->addCategory($this->secondCategory); @@ -128,11 +130,11 @@ protected function _findCategories() return $result; } - public function assertLazyLoadFromInverseSide($products) + public function assertLazyLoadFromInverseSide($products): void { [$firstProduct, $secondProduct] = $products; - $firstProductCategories = $firstProduct->getCategories(); + $firstProductCategories = $firstProduct->getCategories(); $secondProductCategories = $secondProduct->getCategories(); $this->assertEquals(2, count($firstProductCategories)); @@ -141,7 +143,7 @@ public function assertLazyLoadFromInverseSide($products) $this->assertTrue($firstProductCategories[0] === $secondProductCategories[0]); $this->assertTrue($firstProductCategories[1] === $secondProductCategories[1]); - $firstCategoryProducts = $firstProductCategories[0]->getProducts(); + $firstCategoryProducts = $firstProductCategories[0]->getProducts(); $secondCategoryProducts = $firstProductCategories[1]->getProducts(); $this->assertFalse($firstCategoryProducts->isInitialized()); @@ -163,11 +165,11 @@ public function assertLazyLoadFromInverseSide($products) $this->assertCollectionEquals($firstCategoryProducts, $secondCategoryProducts); } - public function assertLazyLoadFromOwningSide($categories) + public function assertLazyLoadFromOwningSide($categories): void { [$firstCategory, $secondCategory] = $categories; - $firstCategoryProducts = $firstCategory->getProducts(); + $firstCategoryProducts = $firstCategory->getProducts(); $secondCategoryProducts = $secondCategory->getProducts(); $this->assertEquals(2, count($firstCategoryProducts)); @@ -176,7 +178,7 @@ public function assertLazyLoadFromOwningSide($categories) $this->assertTrue($firstCategoryProducts[0] === $secondCategoryProducts[0]); $this->assertTrue($firstCategoryProducts[1] === $secondCategoryProducts[1]); - $firstProductCategories = $firstCategoryProducts[0]->getCategories(); + $firstProductCategories = $firstCategoryProducts[0]->getCategories(); $secondProductCategories = $firstCategoryProducts[1]->getCategories(); $this->assertFalse($firstProductCategories->isInitialized()); diff --git a/tests/Doctrine/Tests/ORM/Functional/ManyToManyEventTest.php b/tests/Doctrine/Tests/ORM/Functional/ManyToManyEventTest.php index adf36de71be..7893d655410 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ManyToManyEventTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ManyToManyEventTest.php @@ -1,42 +1,40 @@ */ class ManyToManyEventTest extends OrmFunctionalTestCase { - /** - * @var PostUpdateListener - */ + /** @var PostUpdateListener */ private $listener; - protected function setUp() : void + protected function setUp(): void { $this->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() + public function testListenerShouldBeNotifiedOnlyWhenUpdating(): void { $user = $this->createNewValidUser(); $this->_em->persist($user); $this->_em->flush(); $this->assertFalse($this->listener->wasNotified); - $group = new CmsGroup(); - $group->name = "admins"; + $group = new CmsGroup(); + $group->name = 'admins'; $user->addGroup($group); $this->_em->persist($user); $this->_em->flush(); @@ -44,32 +42,25 @@ public function testListenerShouldBeNotifiedOnlyWhenUpdating() $this->assertTrue($this->listener->wasNotified); } - /** - * @return CmsUser - */ - private function createNewValidUser() + private function createNewValidUser(): CmsUser { - $user = new CmsUser(); + $user = new CmsUser(); $user->username = 'fran6co'; - $user->name = 'Francisco Facioni'; - $group = new CmsGroup(); - $group->name = "users"; + $user->name = 'Francisco Facioni'; + $group = new CmsGroup(); + $group->name = 'users'; $user->addGroup($group); + return $user; } } class PostUpdateListener { - /** - * @var bool - */ + /** @var bool */ public $wasNotified = false; - /** - * @param $args - */ - public function postUpdate($args) + public function postUpdate($args): void { $this->wasNotified = true; } diff --git a/tests/Doctrine/Tests/ORM/Functional/ManyToManySelfReferentialAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/ManyToManySelfReferentialAssociationTest.php index 4663033ad57..13c967174b9 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ManyToManySelfReferentialAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ManyToManySelfReferentialAssociationTest.php @@ -1,10 +1,13 @@ useModelSet('ecommerce'); parent::setUp(); - $this->firstProduct = new ECommerceProduct(); + $this->firstProduct = new ECommerceProduct(); $this->secondProduct = new ECommerceProduct(); - $this->firstRelated = new ECommerceProduct(); - $this->firstRelated->setName("Business"); + $this->firstRelated = new ECommerceProduct(); + $this->firstRelated->setName('Business'); $this->secondRelated = new ECommerceProduct(); - $this->secondRelated->setName("Home"); + $this->secondRelated->setName('Home'); } - public function testSavesAManyToManyAssociationWithCascadeSaveSet() + public function testSavesAManyToManyAssociationWithCascadeSaveSet(): void { $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->assertForeignKeysContain( + $this->firstProduct->getId(), + $this->firstRelated->getId() + ); + $this->assertForeignKeysContain( + $this->firstProduct->getId(), + $this->secondRelated->getId() + ); } - public function testRemovesAManyToManyAssociation() + public function testRemovesAManyToManyAssociation(): void { $this->firstProduct->addRelated($this->firstRelated); $this->firstProduct->addRelated($this->secondRelated); @@ -55,39 +62,43 @@ public function testRemovesAManyToManyAssociation() $this->_em->flush(); - $this->assertForeignKeysNotContain($this->firstProduct->getId(), - $this->firstRelated->getId()); - $this->assertForeignKeysContain($this->firstProduct->getId(), - $this->secondRelated->getId()); + $this->assertForeignKeysNotContain( + $this->firstProduct->getId(), + $this->firstRelated->getId() + ); + $this->assertForeignKeysContain( + $this->firstProduct->getId(), + $this->secondRelated->getId() + ); } - public function testEagerLoadsOwningSide() + public function testEagerLoadsOwningSide(): void { $this->_createLoadingFixture(); $products = $this->_findProducts(); $this->assertLoadingOfOwningSide($products); } - public function testLazyLoadsOwningSide() + public function testLazyLoadsOwningSide(): void { $this->_createLoadingFixture(); - $metadata = $this->_em->getClassMetadata(ECommerceProduct::class); + $metadata = $this->_em->getClassMetadata(ECommerceProduct::class); $metadata->associationMappings['related']['fetch'] = ClassMetadata::FETCH_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); } - public function assertLoadingOfOwningSide($products) + public function assertLoadingOfOwningSide($products): void { [$firstProduct, $secondProduct] = $products; $this->assertEquals(2, count($firstProduct->getRelated())); $this->assertEquals(2, count($secondProduct->getRelated())); - $categories = $firstProduct->getRelated(); - $firstRelatedBy = $categories[0]->getRelated(); + $categories = $firstProduct->getRelated(); + $firstRelatedBy = $categories[0]->getRelated(); $secondRelatedBy = $categories[1]->getRelated(); $this->assertEquals(2, count($firstRelatedBy)); @@ -101,7 +112,7 @@ public function assertLoadingOfOwningSide($products) $this->assertCollectionEquals($firstRelatedBy, $secondRelatedBy); } - protected function _createLoadingFixture() + protected function _createLoadingFixture(): void { $this->firstProduct->addRelated($this->firstRelated); $this->firstProduct->addRelated($this->secondRelated); @@ -117,6 +128,7 @@ protected function _createLoadingFixture() 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'); + return $query->getResult(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ManyToManyUnidirectionalAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/ManyToManyUnidirectionalAssociationTest.php index 1c94b4b942c..f897aa71fd1 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ManyToManyUnidirectionalAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ManyToManyUnidirectionalAssociationTest.php @@ -1,11 +1,12 @@ useModelSet('ecommerce'); parent::setUp(); @@ -29,11 +30,11 @@ protected function setUp() : void $this->firstProduct->setName('Doctrine 1.x Manual'); $this->secondProduct = new ECommerceProduct(); $this->secondProduct->setName('Doctrine 2.x Manual'); - $this->firstCart = new ECommerceCart(); + $this->firstCart = new ECommerceCart(); $this->secondCart = new ECommerceCart(); } - public function testSavesAManyToManyAssociationWithCascadeSaveSet() + public function testSavesAManyToManyAssociationWithCascadeSaveSet(): void { $this->firstCart->addProduct($this->firstProduct); $this->firstCart->addProduct($this->secondProduct); @@ -44,7 +45,7 @@ public function testSavesAManyToManyAssociationWithCascadeSaveSet() $this->assertForeignKeysContain($this->firstCart->getId(), $this->secondProduct->getId()); } - public function testRemovesAManyToManyAssociation() + public function testRemovesAManyToManyAssociation(): void { $this->firstCart->addProduct($this->firstProduct); $this->firstCart->addProduct($this->secondProduct); @@ -57,14 +58,14 @@ public function testRemovesAManyToManyAssociation() $this->assertForeignKeysContain($this->firstCart->getId(), $this->secondProduct->getId()); } - public function testEagerLoad() + public function testEagerLoad(): void { $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'); - $result = $query->getResult(); - $firstCart = $result[0]; - $products = $firstCart->getProducts(); + $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]); @@ -74,16 +75,16 @@ public function testEagerLoad() //$this->assertEquals("Doctrine 2.x Manual", $products[1]->getName()); } - public function testLazyLoadsCollection() + public function testLazyLoadsCollection(): void { $this->_createFixture(); - $metadata = $this->_em->getClassMetadata(ECommerceCart::class); + $metadata = $this->_em->getClassMetadata(ECommerceCart::class); $metadata->associationMappings['products']['fetch'] = ClassMetadata::FETCH_LAZY; - $query = $this->_em->createQuery('SELECT c FROM Doctrine\Tests\Models\ECommerce\ECommerceCart c'); - $result = $query->getResult(); - $firstCart = $result[0]; - $products = $firstCart->getProducts(); + $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]); @@ -91,7 +92,7 @@ public function testLazyLoadsCollection() $this->assertCollectionEquals($products, $secondCart->getProducts()); } - private function _createFixture() + private function _createFixture(): void { $this->firstCart->addProduct($this->firstProduct); $this->firstCart->addProduct($this->secondProduct); diff --git a/tests/Doctrine/Tests/ORM/Functional/ManyToOneOrphanRemovalTest.php b/tests/Doctrine/Tests/ORM/Functional/ManyToOneOrphanRemovalTest.php index 2e16cbcbc6e..617679cd18e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ManyToOneOrphanRemovalTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ManyToOneOrphanRemovalTest.php @@ -1,14 +1,20 @@ [ Person::class, PhoneNumber::class, - ] + ], ]; - protected function setUp() : void + protected function setUp(): void { $this->useModelSet('ornemental_orphan_removal'); parent::setUp(); - $person = new Person; + $person = new Person(); $person->id = 'ca41a293-799f-4d68-bf79-626c3ad223ec'; - $phone1 = new PhoneNumber; - $phone1->id = 'f4132478-c492-4dfe-aab5-a5b79ae129e7'; + $phone1 = new PhoneNumber(); + $phone1->id = 'f4132478-c492-4dfe-aab5-a5b79ae129e7'; $phone1->phonenumber = '123456'; - $phone2 = new PhoneNumber; - $phone2->id = '7faa4cd3-a155-4fbf-bc42-aa4269a4454d'; + $phone2 = new PhoneNumber(); + $phone2->id = '7faa4cd3-a155-4fbf-bc42-aa4269a4454d'; $phone2->phonenumber = '234567'; $phone1->person = $person; @@ -52,7 +58,7 @@ protected function setUp() : void $this->_em->clear(); } - public function testOrphanRemovalIsPurelyOrnemental() + public function testOrphanRemovalIsPurelyOrnemental(): void { $person = $this->_em->getReference(Person::class, $this->personId); @@ -76,11 +82,11 @@ public function testOrphanRemovalIsPurelyOrnemental() } protected function _getEntityManager( - Connection $connection = null, - MappingDriver $mappingDriver = null + ?Connection $connection = null, + ?MappingDriver $mappingDriver = null ) { return parent::_getEntityManager($connection, new XmlDriver( - __DIR__.DIRECTORY_SEPARATOR.'xml' + __DIR__ . DIRECTORY_SEPARATOR . 'xml' )); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/MappedSuperclassTest.php b/tests/Doctrine/Tests/ORM/Functional/MappedSuperclassTest.php index 40bf1b6039b..7c6da7d46c6 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(); } - public function testCRUD() + public function testCRUD(): void { $root = new Directory(); $root->setName('Root'); diff --git a/tests/Doctrine/Tests/ORM/Functional/MergeCompositeToOneKeyTest.php b/tests/Doctrine/Tests/ORM/Functional/MergeCompositeToOneKeyTest.php index f7dcb33125a..585ed102a1d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/MergeCompositeToOneKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/MergeCompositeToOneKeyTest.php @@ -1,5 +1,7 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(Country::class), - $this->_em->getClassMetadata(CompositeToOneKeyState::class), + $this->_em->getClassMetadata(Country::class), + $this->_em->getClassMetadata(CompositeToOneKeyState::class), ] ); } @@ -30,17 +31,17 @@ protected function setUp() : void * @group DDC-3378 * @group 1176 */ - public function testMergingOfEntityWithCompositeIdentifierContainingToOneAssociation() + public function testMergingOfEntityWithCompositeIdentifierContainingToOneAssociation(): void { - $country = new Country(); + $country = new Country(); $country->country = 'US'; - $state = new CompositeToOneKeyState(); + $state = new CompositeToOneKeyState(); $state->state = 'CA'; $state->country = $country; - /* @var $merged CompositeToOneKeyState */ $merged = $this->_em->merge($state); + assert($merged instanceof CompositeToOneKeyState); $this->assertInstanceOf(CompositeToOneKeyState::class, $state); $this->assertNotSame($state, $merged); diff --git a/tests/Doctrine/Tests/ORM/Functional/MergeProxiesTest.php b/tests/Doctrine/Tests/ORM/Functional/MergeProxiesTest.php index 92750299d23..b9e0831f560 100644 --- a/tests/Doctrine/Tests/ORM/Functional/MergeProxiesTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/MergeProxiesTest.php @@ -1,7 +1,10 @@ useModelSet('generic'); @@ -28,7 +33,7 @@ protected function setUp() : void } /** @after */ - public function ensureTestGeneratedDeprecationMessages() : void + public function ensureTestGeneratedDeprecationMessages(): void { $this->assertHasDeprecationMessages(); } @@ -39,7 +44,7 @@ public function ensureTestGeneratedDeprecationMessages() : void * @group DDC-3368 * @group #1172 */ - public function testMergeDetachedUnInitializedProxy() + public function testMergeDetachedUnInitializedProxy(): void { $detachedUninitialized = $this->_em->getReference(DateTimeModel::class, 123); @@ -59,7 +64,7 @@ public function testMergeDetachedUnInitializedProxy() * @group DDC-3368 * @group #1172 */ - public function testMergeUnserializedUnInitializedProxy() + public function testMergeUnserializedUnInitializedProxy(): void { $detachedUninitialized = $this->_em->getReference(DateTimeModel::class, 123); @@ -82,7 +87,7 @@ public function testMergeUnserializedUnInitializedProxy() * @group DDC-3368 * @group #1172 */ - public function testMergeManagedProxy() + public function testMergeManagedProxy(): void { $managed = $this->_em->getReference(DateTimeModel::class, 123); @@ -100,7 +105,7 @@ public function testMergeManagedProxy() * 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() + public function testMergeWithExistingUninitializedManagedProxy(): void { $date = new DateTimeModel(); @@ -113,7 +118,7 @@ public function testMergeWithExistingUninitializedManagedProxy() $this->assertInstanceOf(Proxy::class, $managed); $this->assertFalse($managed->__isInitialized()); - $date->date = $dateTime = new \DateTime(); + $date->date = $dateTime = new DateTime(); $this->assertSame($managed, $this->_em->merge($date)); $this->assertTrue($managed->__isInitialized()); @@ -126,7 +131,7 @@ public function testMergeWithExistingUninitializedManagedProxy() * @group DDC-3368 * @group #1172 */ - public function testMergingProxyFromDifferentEntityManagerWithExistingManagedInstanceDoesNotReplaceInitializer() + public function testMergingProxyFromDifferentEntityManagerWithExistingManagedInstanceDoesNotReplaceInitializer(): void { $em1 = $this->createEntityManager($logger1 = new DebugStack()); $em2 = $this->createEntityManager($logger2 = new DebugStack()); @@ -187,7 +192,7 @@ public function testMergingProxyFromDifferentEntityManagerWithExistingManagedIns * @group DDC-3368 * @group #1172 */ - public function testMergingUnInitializedProxyDoesNotInitializeIt() + public function testMergingUnInitializedProxyDoesNotInitializeIt(): void { $em1 = $this->createEntityManager($logger1 = new DebugStack()); $em2 = $this->createEntityManager($logger2 = new DebugStack()); @@ -237,12 +242,7 @@ public function testMergingUnInitializedProxyDoesNotInitializeIt() ); } - /** - * @param SQLLogger $logger - * - * @return EntityManager - */ - private function createEntityManager(SQLLogger $logger) + private function createEntityManager(SQLLogger $logger): EntityManager { $config = new Configuration(); @@ -260,12 +260,11 @@ private function createEntityManager(SQLLogger $logger) $connection = DriverManager::getConnection( [ 'driver' => 'pdo_sqlite', - 'memory' => true + 'memory' => true, ], $config ); - $entityManager = EntityManager::create($connection, $config); (new SchemaTool($entityManager))->createSchema([$entityManager->getClassMetadata(DateTimeModel::class)]); diff --git a/tests/Doctrine/Tests/ORM/Functional/MergeSharedEntitiesTest.php b/tests/Doctrine/Tests/ORM/Functional/MergeSharedEntitiesTest.php index 518565c9a37..f0e414cbe39 100644 --- a/tests/Doctrine/Tests/ORM/Functional/MergeSharedEntitiesTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/MergeSharedEntitiesTest.php @@ -1,27 +1,29 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(MSEFile::class), - $this->_em->getClassMetadata(MSEPicture::class), + $this->_em->getClassMetadata(MSEFile::class), + $this->_em->getClassMetadata(MSEPicture::class), ] ); } catch (ToolsException $ignored) { @@ -29,15 +31,15 @@ protected function setUp() : void } /** @after */ - public function ensureTestGeneratedDeprecationMessages() : void + public function ensureTestGeneratedDeprecationMessages(): void { $this->assertHasDeprecationMessages(); } - public function testMergeSharedNewEntities() + public function testMergeSharedNewEntities(): void { - $file = new MSEFile; - $picture = new MSEPicture; + $file = new MSEFile(); + $picture = new MSEPicture(); $picture->file = $file; $picture->otherFile = $file; @@ -47,10 +49,10 @@ public function testMergeSharedNewEntities() $this->assertEquals($picture->file, $picture->otherFile, 'Identical entities must remain identical'); } - public function testMergeSharedManagedEntities() + public function testMergeSharedManagedEntities(): void { - $file = new MSEFile; - $picture = new MSEPicture; + $file = new MSEFile(); + $picture = new MSEPicture(); $picture->file = $file; $picture->otherFile = $file; @@ -65,10 +67,10 @@ public function testMergeSharedManagedEntities() $this->assertEquals($picture->file, $picture->otherFile, 'Identical entities must remain identical'); } - public function testMergeSharedDetachedSerializedEntities() + public function testMergeSharedDetachedSerializedEntities(): void { - $file = new MSEFile; - $picture = new MSEPicture; + $file = new MSEFile(); + $picture = new MSEPicture(); $picture->file = $file; $picture->otherFile = $file; @@ -88,7 +90,7 @@ public function testMergeSharedDetachedSerializedEntities() /** * @group DDC-2704 */ - public function testMergeInheritedTransientPrivateProperties() + public function testMergeInheritedTransientPrivateProperties(): void { $admin1 = new MSEAdmin(); $admin2 = new MSEAdmin(); @@ -135,7 +137,7 @@ public function getSession() return $this->session; } - public function setSession($session) + public function setSession($session): void { $this->session = $session; } diff --git a/tests/Doctrine/Tests/ORM/Functional/MergeVersionedManyToOneTest.php b/tests/Doctrine/Tests/ORM/Functional/MergeVersionedManyToOneTest.php index 2993374db94..22d76e814e9 100644 --- a/tests/Doctrine/Tests/ORM/Functional/MergeVersionedManyToOneTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/MergeVersionedManyToOneTest.php @@ -1,5 +1,7 @@ useModelSet('versioned_many_to_one'); @@ -25,7 +27,7 @@ protected function setUp() : void * This test case asserts that a detached and unmodified entity could be merge without firing * OptimisticLockException. */ - public function testSetVersionOnCreate() + public function testSetVersionOnCreate(): void { $category = new Category(); $article = new Article(); diff --git a/tests/Doctrine/Tests/ORM/Functional/NativeQueryTest.php b/tests/Doctrine/Tests/ORM/Functional/NativeQueryTest.php index d69c00109ee..f46a4a3450a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/NativeQueryTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/NativeQueryTest.php @@ -1,5 +1,7 @@ useModelSet('cms'); $this->useModelSet('company'); @@ -39,18 +44,18 @@ protected function setUp() : void $this->platform = $this->_em->getConnection()->getDatabasePlatform(); } - public function testBasicNativeQuery() + public function testBasicNativeQuery(): void { - $user = new CmsUser; - $user->name = 'Roman'; + $user = new CmsUser(); + $user->name = 'Roman'; $user->username = 'romanb'; - $user->status = 'dev'; + $user->status = 'dev'; $this->_em->persist($user); $this->_em->flush(); $this->_em->clear(); - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', $this->platform->getSQLResultCasing('id'), 'id'); $rsm->addFieldResult('u', $this->platform->getSQLResultCasing('name'), 'name'); @@ -65,18 +70,17 @@ public function testBasicNativeQuery() $this->assertEquals('Roman', $users[0]->name); } - public function testBasicNativeQueryWithMetaResult() + public function testBasicNativeQueryWithMetaResult(): void { - $user = new CmsUser; - $user->name = 'Roman'; + $user = new CmsUser(); + $user->name = 'Roman'; $user->username = 'romanb'; - $user->status = 'dev'; + $user->status = 'dev'; - $addr = new CmsAddress; + $addr = new CmsAddress(); $addr->country = 'germany'; - $addr->zip = 10827; - $addr->city = 'Berlin'; - + $addr->zip = 10827; + $addr->city = 'Berlin'; $user->setAddress($addr); @@ -85,7 +89,7 @@ public function testBasicNativeQueryWithMetaResult() $this->_em->clear(); - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsAddress::class, 'a'); $rsm->addFieldResult('a', $this->platform->getSQLResultCasing('id'), 'id'); $rsm->addFieldResult('a', $this->platform->getSQLResultCasing('country'), 'country'); @@ -107,14 +111,14 @@ public function testBasicNativeQueryWithMetaResult() $this->assertTrue($addresses[0]->user instanceof CmsUser); } - public function testJoinedOneToManyNativeQuery() + public function testJoinedOneToManyNativeQuery(): void { - $user = new CmsUser; - $user->name = 'Roman'; + $user = new CmsUser(); + $user->name = 'Roman'; $user->username = 'romanb'; - $user->status = 'dev'; + $user->status = 'dev'; - $phone = new CmsPhonenumber; + $phone = new CmsPhonenumber(); $phone->phonenumber = 424242; $user->addPhonenumber($phone); @@ -124,7 +128,7 @@ public function testJoinedOneToManyNativeQuery() $this->_em->clear(); - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', $this->platform->getSQLResultCasing('id'), 'id'); $rsm->addFieldResult('u', $this->platform->getSQLResultCasing('name'), 'name'); @@ -145,21 +149,19 @@ public function testJoinedOneToManyNativeQuery() $phones = $users[0]->getPhonenumbers(); $this->assertEquals(424242, $phones[0]->phonenumber); $this->assertTrue($phones[0]->getUser() === $users[0]); - } - public function testJoinedOneToOneNativeQuery() + public function testJoinedOneToOneNativeQuery(): void { - $user = new CmsUser; - $user->name = 'Roman'; + $user = new CmsUser(); + $user->name = 'Roman'; $user->username = 'romanb'; - $user->status = 'dev'; + $user->status = 'dev'; - $addr = new CmsAddress; + $addr = new CmsAddress(); $addr->country = 'germany'; - $addr->zip = 10827; - $addr->city = 'Berlin'; - + $addr->zip = 10827; + $addr->city = 'Berlin'; $user->setAddress($addr); @@ -168,8 +170,7 @@ public function testJoinedOneToOneNativeQuery() $this->_em->clear(); - - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', $this->platform->getSQLResultCasing('id'), 'id'); $rsm->addFieldResult('u', $this->platform->getSQLResultCasing('name'), 'name'); @@ -191,21 +192,21 @@ public function testJoinedOneToOneNativeQuery() $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->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()); } - public function testFluentInterface() + public function testFluentInterface(): void { - $parameters = new ArrayCollection; + $parameters = new ArrayCollection(); $parameters->add(new Parameter(1, 'foo')); $parameters->add(new Parameter(2, 'bar')); - $rsm = new ResultSetMapping; + $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) @@ -218,14 +219,14 @@ public function testFluentInterface() $this->assertSame($q, $q2); } - public function testJoinedOneToManyNativeQueryWithRSMBuilder() + public function testJoinedOneToManyNativeQueryWithRSMBuilder(): void { - $user = new CmsUser; - $user->name = 'Roman'; + $user = new CmsUser(); + $user->name = 'Roman'; $user->username = 'romanb'; - $user->status = 'dev'; + $user->status = 'dev'; - $phone = new CmsPhonenumber; + $phone = new CmsPhonenumber(); $phone->phonenumber = 424242; $user->addPhonenumber($phone); @@ -264,18 +265,17 @@ public function testJoinedOneToManyNativeQueryWithRSMBuilder() $this->assertEquals($user->name, $phone->getUser()->getName()); } - public function testJoinedOneToOneNativeQueryWithRSMBuilder() + public function testJoinedOneToOneNativeQueryWithRSMBuilder(): void { - $user = new CmsUser; - $user->name = 'Roman'; + $user = new CmsUser(); + $user->name = 'Roman'; $user->username = 'romanb'; - $user->status = 'dev'; + $user->status = 'dev'; - $addr = new CmsAddress; + $addr = new CmsAddress(); $addr->country = 'germany'; - $addr->zip = 10827; - $addr->city = 'Berlin'; - + $addr->zip = 10827; + $addr->city = 'Berlin'; $user->setAddress($addr); @@ -284,11 +284,9 @@ public function testJoinedOneToOneNativeQueryWithRSMBuilder() $this->_em->clear(); - $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->setParameter(1, 'romanb'); @@ -301,7 +299,7 @@ public function testJoinedOneToOneNativeQueryWithRSMBuilder() $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->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()); @@ -321,7 +319,7 @@ public function testJoinedOneToOneNativeQueryWithRSMBuilder() /** * @group rsm-sti */ - public function testConcreteClassInSingleTableInheritanceSchemaWithRSMBuilderIsFine() + public function testConcreteClassInSingleTableInheritanceSchemaWithRSMBuilderIsFine(): void { $rsm = new ResultSetMappingBuilder($this->_em); $rsm->addRootEntityFromClassMetadata(CompanyFixContract::class, 'c'); @@ -332,16 +330,16 @@ public function testConcreteClassInSingleTableInheritanceSchemaWithRSMBuilderIsF /** * @group rsm-sti */ - public function testAbstractClassInSingleTableInheritanceSchemaWithRSMBuilderThrowsException() + public function testAbstractClassInSingleTableInheritanceSchemaWithRSMBuilderThrowsException(): void { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('ResultSetMapping builder does not currently support your inheritance scheme.'); $rsm = new ResultSetMappingBuilder($this->_em); $rsm->addRootEntityFromClassMetadata(CompanyContract::class, 'c'); } - public function testRSMBuilderThrowsExceptionOnColumnConflict() + public function testRSMBuilderThrowsExceptionOnColumnConflict(): void { $this->expectException('InvalidArgumentException'); $rsm = new ResultSetMappingBuilder($this->_em); @@ -352,12 +350,11 @@ public function testRSMBuilderThrowsExceptionOnColumnConflict() /** * @group PR-39 */ - public function testUnknownParentAliasThrowsException() + public function testUnknownParentAliasThrowsException(): void { $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->setParameter(1, 'romanb'); @@ -368,21 +365,20 @@ public function testUnknownParentAliasThrowsException() $users = $query->getResult(); } - /** * @group DDC-1663 */ - public function testBasicNativeNamedQueryWithSqlResultSetMapping() + public function testBasicNativeNamedQueryWithSqlResultSetMapping(): void { - $user = new CmsUser; + $user = new CmsUser(); $user->name = 'Fabio B. Silva'; $user->username = 'FabioBatSilva'; $user->status = 'dev'; - $addr = new CmsAddress; - $addr->country = 'Brazil'; - $addr->zip = 10827; - $addr->city = 'São Paulo'; + $addr = new CmsAddress(); + $addr->country = 'Brazil'; + $addr->zip = 10827; + $addr->city = 'São Paulo'; $user->setAddress($addr); @@ -392,30 +388,29 @@ public function testBasicNativeNamedQueryWithSqlResultSetMapping() $this->_em->clear(); - $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->id, $result[0]->id); + $this->assertEquals($addr->city, $result[0]->city); $this->assertEquals($addr->country, $result[0]->country); } /** * @group DDC-1663 */ - public function testBasicNativeNamedQueryWithResultClass() + public function testBasicNativeNamedQueryWithResultClass(): void { - $user = new CmsUser; + $user = new CmsUser(); $user->name = 'Fabio B. Silva'; $user->username = 'FabioBatSilva'; $user->status = 'dev'; - $email = new CmsEmail(); - $email->email = 'fabio.bat.silva@gmail.com'; + $email = new CmsEmail(); + $email->email = 'fabio.bat.silva@gmail.com'; $user->setEmail($email); @@ -453,21 +448,20 @@ public function testBasicNativeNamedQueryWithResultClass() $this->assertInstanceOf(CmsEmail::class, $result[0]->email); } - /** * @group DDC-1663 */ - public function testJoinedOneToOneNativeNamedQueryWithResultSetMapping() + public function testJoinedOneToOneNativeNamedQueryWithResultSetMapping(): void { - $user = new CmsUser; + $user = new CmsUser(); $user->name = 'Fabio B. Silva'; $user->username = 'FabioBatSilva'; $user->status = 'dev'; - $addr = new CmsAddress; - $addr->country = 'Brazil'; - $addr->zip = 10827; - $addr->city = 'São Paulo'; + $addr = new CmsAddress(); + $addr->country = 'Brazil'; + $addr->zip = 10827; + $addr->city = 'São Paulo'; $user->setAddress($addr); @@ -486,7 +480,7 @@ public function testJoinedOneToOneNativeNamedQueryWithResultSetMapping() $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->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()); @@ -495,14 +489,14 @@ public function testJoinedOneToOneNativeNamedQueryWithResultSetMapping() /** * @group DDC-1663 */ - public function testJoinedOneToManyNativeNamedQueryWithResultSetMapping() + public function testJoinedOneToManyNativeNamedQueryWithResultSetMapping(): void { - $user = new CmsUser; - $user->name = 'Fabio B. Silva'; - $user->username = 'FabioBatSilva'; - $user->status = 'dev'; + $user = new CmsUser(); + $user->name = 'Fabio B. Silva'; + $user->username = 'FabioBatSilva'; + $user->status = 'dev'; - $phone = new CmsPhonenumber; + $phone = new CmsPhonenumber(); $phone->phonenumber = 424242; $user->addPhonenumber($phone); @@ -531,24 +525,24 @@ public function testJoinedOneToManyNativeNamedQueryWithResultSetMapping() /** * @group DDC-1663 */ - public function testMixedNativeNamedQueryNormalJoin() + public function testMixedNativeNamedQueryNormalJoin(): void { - $user1 = new CmsUser; - $user1->name = 'Fabio B. Silva'; - $user1->username = 'FabioBatSilva'; - $user1->status = 'dev'; - - $user2 = new CmsUser; - $user2->name = 'test tester'; - $user2->username = 'test'; - $user2->status = 'tester'; - - $phone1 = new CmsPhonenumber; - $phone2 = new CmsPhonenumber; - $phone3 = new CmsPhonenumber; - $phone1->phonenumber = 11111111; - $phone2->phonenumber = 22222222; - $phone3->phonenumber = 33333333; + $user1 = new CmsUser(); + $user1->name = 'Fabio B. Silva'; + $user1->username = 'FabioBatSilva'; + $user1->status = 'dev'; + + $user2 = new CmsUser(); + $user2->name = 'test tester'; + $user2->username = 'test'; + $user2->status = 'tester'; + + $phone1 = new CmsPhonenumber(); + $phone2 = new CmsPhonenumber(); + $phone3 = new CmsPhonenumber(); + $phone1->phonenumber = 11111111; + $phone2->phonenumber = 22222222; + $phone3->phonenumber = 33333333; $user1->addPhonenumber($phone1); $user1->addPhonenumber($phone2); @@ -563,7 +557,7 @@ public function testMixedNativeNamedQueryNormalJoin() $repository = $this->_em->getRepository(CmsUser::class); $result = $repository->createNativeNamedQuery('fetchUserPhonenumberCount') - ->setParameter(1, ['test','FabioBatSilva'])->getResult(); + ->setParameter(1, ['test', 'FabioBatSilva'])->getResult(); $this->assertEquals(2, count($result)); $this->assertTrue(is_array($result[0])); @@ -583,12 +577,12 @@ public function testMixedNativeNamedQueryNormalJoin() /** * @group DDC-1663 */ - public function testNativeNamedQueryInheritance() + public function testNativeNamedQueryInheritance(): void { - $person = new CompanyPerson; + $person = new CompanyPerson(); $person->setName('Fabio B. Silva'); - $employee = new CompanyEmployee; + $employee = new CompanyEmployee(); $employee->setName('Fabio Silva'); $employee->setSalary(100000); $employee->setDepartment('IT'); @@ -612,10 +606,8 @@ public function testNativeNamedQueryInheritance() $this->assertEquals('Fabio B. Silva', $result[0]->getName()); $this->assertEquals('Fabio Silva', $result[1]->getName()); - $this->_em->clear(); - $result = $repository->createNativeNamedQuery('fetchAllWithResultClass') ->getResult(); @@ -632,67 +624,60 @@ public function testNativeNamedQueryInheritance() * @group DDC-1663 * DQL : SELECT u, a, COUNT(p) AS numphones FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.address a JOIN u.phonenumbers p */ - public function testMultipleEntityResults() + public function testMultipleEntityResults(): void { + $user = new CmsUser(); + $user->name = 'Fabio B. Silva'; + $user->username = 'FabioBatSilva'; + $user->status = 'dev'; - $user = new CmsUser; - $user->name = 'Fabio B. Silva'; - $user->username = 'FabioBatSilva'; - $user->status = 'dev'; - - $addr = new CmsAddress; - $addr->country = 'Brazil'; - $addr->zip = 10827; - $addr->city = 'São Paulo'; + $addr = new CmsAddress(); + $addr->country = 'Brazil'; + $addr->zip = 10827; + $addr->city = 'São Paulo'; - $phone = new CmsPhonenumber; + $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(); - $repository = $this->_em->getRepository(CmsUser::class); $query = $repository->createNativeNamedQuery('fetchMultipleJoinsEntityResults'); $result = $query->getResult(); - $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->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']); - } /** * @group DDC-1663 */ - public function testNamedNativeQueryInheritance() + public function testNamedNativeQueryInheritance(): void { - $contractMetadata = $this->_em->getClassMetadata(CompanyContract::class); - $flexMetadata = $this->_em->getClassMetadata(CompanyFlexContract::class); + $contractMetadata = $this->_em->getClassMetadata(CompanyContract::class); + $flexMetadata = $this->_em->getClassMetadata(CompanyFlexContract::class); - $contractQueries = $contractMetadata->getNamedNativeQueries(); - $flexQueries = $flexMetadata->getNamedNativeQueries(); - - $contractMappings = $contractMetadata->getSqlResultSetMappings(); - $flexMappings = $flexMetadata->getSqlResultSetMappings(); + $contractQueries = $contractMetadata->getNamedNativeQueries(); + $flexQueries = $flexMetadata->getNamedNativeQueries(); + $contractMappings = $contractMetadata->getSqlResultSetMappings(); + $flexMappings = $flexMetadata->getSqlResultSetMappings(); // contract queries $this->assertEquals('all-contracts', $contractQueries['all-contracts']['name']); @@ -701,7 +686,6 @@ public function testNamedNativeQueryInheritance() $this->assertEquals('all', $contractQueries['all']['name']); $this->assertEquals(CompanyContract::class, $contractQueries['all']['resultClass']); - // flex contract queries $this->assertEquals('all-contracts', $flexQueries['all-contracts']['name']); $this->assertEquals(CompanyFlexContract::class, $flexQueries['all-contracts']['resultClass']); @@ -712,7 +696,6 @@ public function testNamedNativeQueryInheritance() $this->assertEquals('all', $flexQueries['all']['name']); $this->assertEquals(CompanyFlexContract::class, $flexQueries['all']['resultClass']); - // contract result mapping $this->assertEquals('mapping-all-contracts', $contractMappings['mapping-all-contracts']['name']); $this->assertEquals(CompanyContract::class, $contractMappings['mapping-all-contracts']['entities'][0]['entityClass']); @@ -729,13 +712,12 @@ public function testNamedNativeQueryInheritance() $this->assertEquals('mapping-all-flex', $flexMappings['mapping-all-flex']['name']); $this->assertEquals(CompanyFlexContract::class, $flexMappings['mapping-all-flex']['entities'][0]['entityClass']); - } /** * @group DDC-2055 */ - public function testGenerateSelectClauseNoRenameSingleEntity() + public function testGenerateSelectClauseNoRenameSingleEntity(): void { $rsm = new ResultSetMappingBuilder($this->_em); $rsm->addRootEntityFromClassMetadata(CmsUser::class, 'u'); @@ -748,14 +730,13 @@ public function testGenerateSelectClauseNoRenameSingleEntity() /** * @group DDC-2055 */ - public function testGenerateSelectClauseCustomRenames() + public function testGenerateSelectClauseCustomRenames(): void { $rsm = new ResultSetMappingBuilder($this->_em); $rsm->addRootEntityFromClassMetadata(CmsUser::class, 'u', [ 'id' => 'id1', - 'username' => 'username2' - ] - ); + 'username' => 'username2', + ]); $selectClause = $rsm->generateSelectClause(); @@ -765,7 +746,7 @@ public function testGenerateSelectClauseCustomRenames() /** * @group DDC-2055 */ - public function testGenerateSelectClauseRenameTableAlias() + public function testGenerateSelectClauseRenameTableAlias(): void { $rsm = new ResultSetMappingBuilder($this->_em); $rsm->addRootEntityFromClassMetadata(CmsUser::class, 'u'); @@ -778,7 +759,7 @@ public function testGenerateSelectClauseRenameTableAlias() /** * @group DDC-2055 */ - public function testGenerateSelectClauseIncrement() + public function testGenerateSelectClauseIncrement(): void { $rsm = new ResultSetMappingBuilder($this->_em, ResultSetMappingBuilder::COLUMN_RENAMING_INCREMENT); $rsm->addRootEntityFromClassMetadata(CmsUser::class, 'u'); @@ -791,18 +772,18 @@ public function testGenerateSelectClauseIncrement() /** * @group DDC-2055 */ - public function testGenerateSelectClauseToString() + public function testGenerateSelectClauseToString(): void { $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); + $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); } /** * @group DDC-3899 */ - public function testGenerateSelectClauseWithDiscriminatorColumn() + public function testGenerateSelectClauseWithDiscriminatorColumn(): void { $rsm = new ResultSetMappingBuilder($this->_em, ResultSetMappingBuilder::COLUMN_RENAMING_INCREMENT); $rsm->addEntityResult(DDC3899User::class, 'u'); diff --git a/tests/Doctrine/Tests/ORM/Functional/NewOperatorTest.php b/tests/Doctrine/Tests/ORM/Functional/NewOperatorTest.php index 0a198b4085c..fc2127c9a47 100644 --- a/tests/Doctrine/Tests/ORM/Functional/NewOperatorTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/NewOperatorTest.php @@ -1,27 +1,29 @@ useModelSet('cms'); parent::setUp(); @@ -37,11 +39,11 @@ public function provideDataForHydrationMode() ]; } - private function loadFixtures() + private function loadFixtures(): void { - $u1 = new CmsUser; - $u2 = new CmsUser; - $u3 = new CmsUser; + $u1 = new CmsUser(); + $u2 = new CmsUser(); + $u3 = new CmsUser(); $u1->setEmail(new CmsEmail()); $u1->setAddress(new CmsAddress()); @@ -58,35 +60,35 @@ private function loadFixtures() $u3->addPhonenumber(new CmsPhonenumber()); $u3->addPhonenumber(new CmsPhonenumber()); - $u1->name = 'Test 1'; - $u1->username = '1test'; - $u1->status = 'developer'; - $u1->email->email = 'email@test1.com'; - $u1->address->zip = '111111111'; - $u1->address->city = 'Some City 1'; - $u1->address->country = 'Some Country 2'; - $u1->phonenumbers[0]->phonenumber = "(11) 1111-1111"; - - $u2->name = 'Test 2'; - $u2->username = '2test'; - $u2->status = 'developer'; - $u2->email->email = 'email@test2.com'; - $u2->address->zip = '222222222'; - $u2->address->city = 'Some City 2'; - $u2->address->country = 'Some Country 2'; - $u2->phonenumbers[0]->phonenumber = "(22) 1111-1111"; - $u2->phonenumbers[1]->phonenumber = "(22) 2222-2222"; - - $u3->name = 'Test 3'; - $u3->username = '3test'; - $u3->status = 'developer'; - $u3->email->email = 'email@test3.com'; - $u3->address->zip = '33333333'; - $u3->address->city = 'Some City 3'; - $u3->address->country = 'Some Country 3'; - $u3->phonenumbers[0]->phonenumber = "(33) 1111-1111"; - $u3->phonenumbers[1]->phonenumber = "(33) 2222-2222"; - $u3->phonenumbers[2]->phonenumber = "(33) 3333-3333"; + $u1->name = 'Test 1'; + $u1->username = '1test'; + $u1->status = 'developer'; + $u1->email->email = 'email@test1.com'; + $u1->address->zip = '111111111'; + $u1->address->city = 'Some City 1'; + $u1->address->country = 'Some Country 2'; + $u1->phonenumbers[0]->phonenumber = '(11) 1111-1111'; + + $u2->name = 'Test 2'; + $u2->username = '2test'; + $u2->status = 'developer'; + $u2->email->email = 'email@test2.com'; + $u2->address->zip = '222222222'; + $u2->address->city = 'Some City 2'; + $u2->address->country = 'Some Country 2'; + $u2->phonenumbers[0]->phonenumber = '(22) 1111-1111'; + $u2->phonenumbers[1]->phonenumber = '(22) 2222-2222'; + + $u3->name = 'Test 3'; + $u3->username = '3test'; + $u3->status = 'developer'; + $u3->email->email = 'email@test3.com'; + $u3->address->zip = '33333333'; + $u3->address->city = 'Some City 3'; + $u3->address->country = 'Some Country 3'; + $u3->phonenumbers[0]->phonenumber = '(33) 1111-1111'; + $u3->phonenumbers[1]->phonenumber = '(33) 2222-2222'; + $u3->phonenumbers[2]->phonenumber = '(33) 3333-3333'; $this->_em->persist($u1); $this->_em->persist($u2); @@ -101,9 +103,9 @@ private function loadFixtures() /** * @dataProvider provideDataForHydrationMode */ - public function testShouldSupportsBasicUsage($hydrationMode) + public function testShouldSupportsBasicUsage($hydrationMode): void { - $dql = " + $dql = ' SELECT new Doctrine\Tests\Models\CMS\CmsUserDTO( u.name, @@ -117,7 +119,7 @@ public function testShouldSupportsBasicUsage($hydrationMode) JOIN u.address a ORDER BY - u.name"; + u.name'; $query = $this->_em->createQuery($dql); $result = $query->getResult($hydrationMode); @@ -144,9 +146,9 @@ public function testShouldSupportsBasicUsage($hydrationMode) /** * @dataProvider provideDataForHydrationMode */ - public function testShouldIgnoreAliasesForSingleObject($hydrationMode) + public function testShouldIgnoreAliasesForSingleObject($hydrationMode): void { - $dql = " + $dql = ' SELECT new Doctrine\Tests\Models\CMS\CmsUserDTO( u.name, @@ -160,7 +162,7 @@ public function testShouldIgnoreAliasesForSingleObject($hydrationMode) JOIN u.address a ORDER BY - u.name"; + u.name'; $query = $this->_em->createQuery($dql); $result = $query->getResult($hydrationMode); @@ -184,9 +186,9 @@ public function testShouldIgnoreAliasesForSingleObject($hydrationMode) $this->assertEquals($this->fixtures[2]->address->city, $result[2]->address); } - public function testShouldAssumeFromEntityNamespaceWhenNotGiven() + public function testShouldAssumeFromEntityNamespaceWhenNotGiven(): void { - $dql = " + $dql = ' SELECT new CmsUserDTO(u.name, e.email, a.city) FROM @@ -196,7 +198,7 @@ public function testShouldAssumeFromEntityNamespaceWhenNotGiven() JOIN u.address a ORDER BY - u.name"; + u.name'; $query = $this->_em->createQuery($dql); $result = $query->getResult(); @@ -208,9 +210,9 @@ public function testShouldAssumeFromEntityNamespaceWhenNotGiven() $this->assertInstanceOf(CmsUserDTO::class, $result[2]); } - public function testShouldSupportFromEntityNamespaceAlias() + public function testShouldSupportFromEntityNamespaceAlias(): void { - $dql = " + $dql = ' SELECT new CmsUserDTO(u.name, e.email, a.city) FROM @@ -220,8 +222,7 @@ public function testShouldSupportFromEntityNamespaceAlias() JOIN u.address a ORDER BY - u.name"; - + u.name'; $this->_em->getConfiguration() ->addEntityNamespace('cms', 'Doctrine\Tests\Models\CMS'); @@ -236,9 +237,9 @@ public function testShouldSupportFromEntityNamespaceAlias() $this->assertInstanceOf(CmsUserDTO::class, $result[2]); } - public function testShouldSupportValueObjectNamespaceAlias() + public function testShouldSupportValueObjectNamespaceAlias(): void { - $dql = " + $dql = ' SELECT new cms:CmsUserDTO(u.name, e.email, a.city) FROM @@ -248,8 +249,7 @@ public function testShouldSupportValueObjectNamespaceAlias() JOIN u.address a ORDER BY - u.name"; - + u.name'; $this->_em->getConfiguration() ->addEntityNamespace('cms', 'Doctrine\Tests\Models\CMS'); @@ -264,7 +264,7 @@ public function testShouldSupportValueObjectNamespaceAlias() $this->assertInstanceOf(CmsUserDTO::class, $result[2]); } - public function testShouldSupportLiteralExpression() + public function testShouldSupportLiteralExpression(): void { $dql = " SELECT @@ -296,7 +296,6 @@ public function testShouldSupportLiteralExpression() $this->assertInstanceOf(CmsUserDTO::class, $result[1]); $this->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); @@ -314,7 +313,7 @@ public function testShouldSupportLiteralExpression() $this->assertEquals(123, $result[2]->phonenumbers); } - public function testShouldSupportCaseExpression() + public function testShouldSupportCaseExpression(): void { $dql = " SELECT @@ -344,7 +343,6 @@ public function testShouldSupportCaseExpression() $this->assertInstanceOf(CmsUserDTO::class, $result[1]); $this->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); @@ -354,9 +352,9 @@ public function testShouldSupportCaseExpression() $this->assertEquals('OTHER_TEST', $result[2]->email); } - public function testShouldSupportSimpleArithmeticExpression() + public function testShouldSupportSimpleArithmeticExpression(): void { - $dql = " + $dql = ' SELECT new Doctrine\Tests\Models\CMS\CmsUserDTO( u.name, @@ -375,7 +373,7 @@ public function testShouldSupportSimpleArithmeticExpression() GROUP BY u, e, a ORDER BY - u.name"; + u.name'; $query = $this->_em->createQuery($dql); $result = $query->getResult(); @@ -399,24 +397,24 @@ public function testShouldSupportSimpleArithmeticExpression() $this->assertEquals($this->fixtures[2]->address->city, $result[2]->address); $this->assertEquals( - ($this->fixtures[0]->address->id + $this->fixtures[0]->id), + $this->fixtures[0]->address->id + $this->fixtures[0]->id, $result[0]->phonenumbers ); $this->assertEquals( - ($this->fixtures[1]->address->id + $this->fixtures[1]->id), + $this->fixtures[1]->address->id + $this->fixtures[1]->id, $result[1]->phonenumbers ); $this->assertEquals( - ($this->fixtures[2]->address->id + $this->fixtures[2]->id), + $this->fixtures[2]->address->id + $this->fixtures[2]->id, $result[2]->phonenumbers ); } - public function testShouldSupportAggregateFunctions() + public function testShouldSupportAggregateFunctions(): void { - $dql = " + $dql = ' SELECT new Doctrine\Tests\Models\CMS\CmsUserDTO( u.name, @@ -435,7 +433,7 @@ public function testShouldSupportAggregateFunctions() GROUP BY u, e, a ORDER BY - u.name"; + u.name'; $query = $this->_em->createQuery($dql); $result = $query->getResult(); @@ -459,24 +457,24 @@ public function testShouldSupportAggregateFunctions() $this->assertEquals($this->fixtures[2]->address->city, $result[2]->address); $this->assertEquals( - (count($this->fixtures[0]->phonenumbers)), + count($this->fixtures[0]->phonenumbers), $result[0]->phonenumbers ); $this->assertEquals( - (count($this->fixtures[1]->phonenumbers)), + count($this->fixtures[1]->phonenumbers), $result[1]->phonenumbers ); $this->assertEquals( - (count($this->fixtures[2]->phonenumbers)), + count($this->fixtures[2]->phonenumbers), $result[2]->phonenumbers ); } - public function testShouldSupportArithmeticExpression() + public function testShouldSupportArithmeticExpression(): void { - $dql = " + $dql = ' SELECT new Doctrine\Tests\Models\CMS\CmsUserDTO( u.name, @@ -495,7 +493,7 @@ public function testShouldSupportArithmeticExpression() GROUP BY u, e, a ORDER BY - u.name"; + u.name'; $query = $this->_em->createQuery($dql); $result = $query->getResult(); @@ -519,24 +517,24 @@ public function testShouldSupportArithmeticExpression() $this->assertEquals($this->fixtures[2]->address->city, $result[2]->address); $this->assertEquals( - (count($this->fixtures[0]->phonenumbers) + $this->fixtures[0]->id), + count($this->fixtures[0]->phonenumbers) + $this->fixtures[0]->id, $result[0]->phonenumbers ); $this->assertEquals( - (count($this->fixtures[1]->phonenumbers) + $this->fixtures[1]->id), + count($this->fixtures[1]->phonenumbers) + $this->fixtures[1]->id, $result[1]->phonenumbers ); $this->assertEquals( - (count($this->fixtures[2]->phonenumbers) + $this->fixtures[2]->id), + count($this->fixtures[2]->phonenumbers) + $this->fixtures[2]->id, $result[2]->phonenumbers ); } - public function testShouldSupportMultipleNewOperators() + public function testShouldSupportMultipleNewOperators(): void { - $dql = " + $dql = ' SELECT new CmsUserDTO( u.name, @@ -553,7 +551,7 @@ public function testShouldSupportMultipleNewOperators() JOIN u.address a ORDER BY - u.name"; + u.name'; $query = $this->_em->createQuery($dql); $result = $query->getResult(); @@ -576,7 +574,6 @@ public function testShouldSupportMultipleNewOperators() $this->assertEquals($this->fixtures[1]->email->email, $result[1][0]->email); $this->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); @@ -586,9 +583,9 @@ public function testShouldSupportMultipleNewOperators() $this->assertEquals($this->fixtures[2]->address->country, $result[2][1]->country); } - public function testShouldSupportMultipleNewOperatorsWithAliases() + public function testShouldSupportMultipleNewOperatorsWithAliases(): void { - $dql = " + $dql = ' SELECT new CmsUserDTO( u.name, @@ -605,7 +602,7 @@ public function testShouldSupportMultipleNewOperatorsWithAliases() JOIN u.address a ORDER BY - u.name"; + u.name'; $query = $this->_em->createQuery($dql); $result = $query->getResult(); @@ -628,7 +625,6 @@ public function testShouldSupportMultipleNewOperatorsWithAliases() $this->assertEquals($this->fixtures[1]->email->email, $result[1]['cmsUser']->email); $this->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); @@ -638,9 +634,9 @@ public function testShouldSupportMultipleNewOperatorsWithAliases() $this->assertEquals($this->fixtures[2]->address->country, $result[2]['cmsAddress']->country); } - public function testShouldSupportMultipleNewOperatorsWithAndWithoutAliases() + public function testShouldSupportMultipleNewOperatorsWithAndWithoutAliases(): void { - $dql = " + $dql = ' SELECT new CmsUserDTO( u.name, @@ -657,7 +653,7 @@ public function testShouldSupportMultipleNewOperatorsWithAndWithoutAliases() JOIN u.address a ORDER BY - u.name"; + u.name'; $query = $this->_em->createQuery($dql); $result = $query->getResult(); @@ -680,7 +676,6 @@ public function testShouldSupportMultipleNewOperatorsWithAndWithoutAliases() $this->assertEquals($this->fixtures[1]->email->email, $result[1]['cmsUser']->email); $this->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); @@ -690,9 +685,9 @@ public function testShouldSupportMultipleNewOperatorsWithAndWithoutAliases() $this->assertEquals($this->fixtures[2]->address->country, $result[2][0]->country); } - public function testShouldSupportMultipleNewOperatorsAndSingleScalar() + public function testShouldSupportMultipleNewOperatorsAndSingleScalar(): void { - $dql = " + $dql = ' SELECT new CmsUserDTO( u.name, @@ -710,7 +705,7 @@ public function testShouldSupportMultipleNewOperatorsAndSingleScalar() JOIN u.address a ORDER BY - u.name"; + u.name'; $query = $this->_em->createQuery($dql); $result = $query->getResult(); @@ -733,7 +728,6 @@ public function testShouldSupportMultipleNewOperatorsAndSingleScalar() $this->assertEquals($this->fixtures[1]->email->email, $result[1][0]->email); $this->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); @@ -742,14 +736,14 @@ public function testShouldSupportMultipleNewOperatorsAndSingleScalar() $this->assertEquals($this->fixtures[1]->address->country, $result[1][1]->country); $this->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']); + $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']); } - public function testShouldSupportMultipleNewOperatorsAndSingleScalarWithAliases() + public function testShouldSupportMultipleNewOperatorsAndSingleScalarWithAliases(): void { - $dql = " + $dql = ' SELECT new CmsUserDTO( u.name, @@ -767,7 +761,7 @@ public function testShouldSupportMultipleNewOperatorsAndSingleScalarWithAliases( JOIN u.address a ORDER BY - u.name"; + u.name'; $query = $this->_em->createQuery($dql); $result = $query->getResult(); @@ -790,7 +784,6 @@ public function testShouldSupportMultipleNewOperatorsAndSingleScalarWithAliases( $this->assertEquals($this->fixtures[1]->email->email, $result[1]['cmsUser']->email); $this->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); @@ -799,14 +792,14 @@ public function testShouldSupportMultipleNewOperatorsAndSingleScalarWithAliases( $this->assertEquals($this->fixtures[1]->address->country, $result[1]['cmsAddress']->country); $this->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']); + $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']); } - public function testShouldSupportMultipleNewOperatorsAndSingleScalarWithAndWithoutAliases() + public function testShouldSupportMultipleNewOperatorsAndSingleScalarWithAndWithoutAliases(): void { - $dql = " + $dql = ' SELECT new CmsUserDTO( u.name, @@ -824,7 +817,7 @@ public function testShouldSupportMultipleNewOperatorsAndSingleScalarWithAndWitho JOIN u.address a ORDER BY - u.name"; + u.name'; $query = $this->_em->createQuery($dql); $result = $query->getResult(); @@ -847,7 +840,6 @@ public function testShouldSupportMultipleNewOperatorsAndSingleScalarWithAndWitho $this->assertEquals($this->fixtures[1]->email->email, $result[1]['cmsUser']->email); $this->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); @@ -856,14 +848,14 @@ public function testShouldSupportMultipleNewOperatorsAndSingleScalarWithAndWitho $this->assertEquals($this->fixtures[1]->address->country, $result[1][0]->country); $this->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']); + $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']); } - public function testShouldSupportMultipleNewOperatorsAndMultipleScalars() + public function testShouldSupportMultipleNewOperatorsAndMultipleScalars(): void { - $dql = " + $dql = ' SELECT new CmsUserDTO( u.name, @@ -882,7 +874,7 @@ public function testShouldSupportMultipleNewOperatorsAndMultipleScalars() JOIN u.address a ORDER BY - u.name"; + u.name'; $query = $this->_em->createQuery($dql); $result = $query->getResult(); @@ -905,7 +897,6 @@ public function testShouldSupportMultipleNewOperatorsAndMultipleScalars() $this->assertEquals($this->fixtures[1]->email->email, $result[1][0]->email); $this->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); @@ -914,18 +905,18 @@ public function testShouldSupportMultipleNewOperatorsAndMultipleScalars() $this->assertEquals($this->fixtures[1]->address->country, $result[1][1]->country); $this->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']); + $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']); - $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']); + $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']); } - public function testShouldSupportMultipleNewOperatorsAndMultipleScalarsWithAliases() + public function testShouldSupportMultipleNewOperatorsAndMultipleScalarsWithAliases(): void { - $dql = " + $dql = ' SELECT new CmsUserDTO( u.name, @@ -944,7 +935,7 @@ public function testShouldSupportMultipleNewOperatorsAndMultipleScalarsWithAlias JOIN u.address a ORDER BY - u.name"; + u.name'; $query = $this->_em->createQuery($dql); $result = $query->getResult(); @@ -967,7 +958,6 @@ public function testShouldSupportMultipleNewOperatorsAndMultipleScalarsWithAlias $this->assertEquals($this->fixtures[1]->email->email, $result[1]['cmsUser']->email); $this->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); @@ -976,18 +966,18 @@ public function testShouldSupportMultipleNewOperatorsAndMultipleScalarsWithAlias $this->assertEquals($this->fixtures[1]->address->country, $result[1]['cmsAddress']->country); $this->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']); + $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']); - $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']); + $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']); } - public function testShouldSupportMultipleNewOperatorsAndMultipleScalarsWithAndWithoutAliases() + public function testShouldSupportMultipleNewOperatorsAndMultipleScalarsWithAndWithoutAliases(): void { - $dql = " + $dql = ' SELECT new CmsUserDTO( u.name, @@ -1006,7 +996,7 @@ public function testShouldSupportMultipleNewOperatorsAndMultipleScalarsWithAndWi JOIN u.address a ORDER BY - u.name"; + u.name'; $query = $this->_em->createQuery($dql); $result = $query->getResult(); @@ -1029,7 +1019,6 @@ public function testShouldSupportMultipleNewOperatorsAndMultipleScalarsWithAndWi $this->assertEquals($this->fixtures[1]->email->email, $result[1]['cmsUser']->email); $this->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); @@ -1038,44 +1027,44 @@ public function testShouldSupportMultipleNewOperatorsAndMultipleScalarsWithAndWi $this->assertEquals($this->fixtures[1]->address->country, $result[1][0]->country); $this->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']); + $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']); - $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']); + $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']); } - public function testInvalidClassException() + public function testInvalidClassException(): void { $this->expectException('Doctrine\ORM\Query\QueryException'); $this->expectExceptionMessage('[Semantical Error] line 0, col 11 near \'\InvalidClass(u.name)\': Error: Class "\InvalidClass" is not defined.'); - $dql = "SELECT new \InvalidClass(u.name) FROM Doctrine\Tests\Models\CMS\CmsUser u"; + $dql = 'SELECT new \InvalidClass(u.name) FROM Doctrine\Tests\Models\CMS\CmsUser u'; $this->_em->createQuery($dql)->getResult(); } - public function testInvalidClassConstructorException() + public function testInvalidClassConstructorException(): void { $this->expectException('Doctrine\ORM\Query\QueryException'); $this->expectExceptionMessage('[Semantical Error] line 0, col 11 near \'\stdClass(u.name)\': Error: Class "\stdClass" has not a valid constructor.'); - $dql = "SELECT new \stdClass(u.name) FROM Doctrine\Tests\Models\CMS\CmsUser u"; + $dql = 'SELECT new \stdClass(u.name) FROM Doctrine\Tests\Models\CMS\CmsUser u'; $this->_em->createQuery($dql)->getResult(); } - public function testInvalidClassWithoutConstructorException() + public function testInvalidClassWithoutConstructorException(): void { $this->expectException('Doctrine\ORM\Query\QueryException'); $this->expectExceptionMessage('[Semantical Error] line 0, col 11 near \'Doctrine\Tests\ORM\Functional\ClassWithTooMuchArgs(u.name)\': Error: Number of arguments does not match with "Doctrine\Tests\ORM\Functional\ClassWithTooMuchArgs" constructor declaration.'); - $dql = "SELECT new Doctrine\Tests\ORM\Functional\ClassWithTooMuchArgs(u.name) FROM Doctrine\Tests\Models\CMS\CmsUser u"; + $dql = 'SELECT new Doctrine\Tests\ORM\Functional\ClassWithTooMuchArgs(u.name) FROM Doctrine\Tests\Models\CMS\CmsUser u'; $this->_em->createQuery($dql)->getResult(); } - public function testClassCantBeInstantiatedException() + public function testClassCantBeInstantiatedException(): void { $this->expectException('Doctrine\ORM\Query\QueryException'); $this->expectExceptionMessage('[Semantical Error] line 0, col 11 near \'Doctrine\Tests\ORM\Functional\ClassWithPrivateConstructor(u.name)\': Error: Class "Doctrine\Tests\ORM\Functional\ClassWithPrivateConstructor" can not be instantiated.'); - $dql = "SELECT new Doctrine\Tests\ORM\Functional\ClassWithPrivateConstructor(u.name) FROM Doctrine\Tests\Models\CMS\CmsUser u"; + $dql = 'SELECT new Doctrine\Tests\ORM\Functional\ClassWithPrivateConstructor(u.name) FROM Doctrine\Tests\Models\CMS\CmsUser u'; $this->_em->createQuery($dql)->getResult(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/NotifyPolicyTest.php b/tests/Doctrine/Tests/ORM/Functional/NotifyPolicyTest.php index 128ea1ff826..22c9c6cfdd3 100644 --- a/tests/Doctrine/Tests/ORM/Functional/NotifyPolicyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/NotifyPolicyTest.php @@ -1,37 +1,40 @@ _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) { + } catch (Exception $e) { // Swallow all exceptions. We do not test the schema tool here. } } - public function testChangeTracking() + public function testChangeTracking(): void { - $user = new NotifyUser(); + $user = new NotifyUser(); $group = new NotifyGroup(); $user->setName('roman'); $group->setName('dev'); @@ -51,7 +54,7 @@ public function testChangeTracking() $this->assertEquals(1, count($user->listeners)); $this->assertEquals(1, count($group->listeners)); - $userId = $user->getId(); + $userId = $user->getId(); $groupId = $group->getId(); unset($user, $group); @@ -90,14 +93,17 @@ public function testChangeTracking() } } -class NotifyBaseEntity implements NotifyPropertyChanged { +class NotifyBaseEntity implements NotifyPropertyChanged +{ public $listeners = []; - public function addPropertyChangedListener(PropertyChangedListener $listener) { + public function addPropertyChangedListener(PropertyChangedListener $listener): void + { $this->listeners[] = $listener; } - protected function onPropertyChanged($propName, $oldValue, $newValue) { + protected function onPropertyChanged($propName, $oldValue, $newValue): void + { if ($this->listeners) { foreach ($this->listeners as $listener) { $listener->propertyChanged($this, $propName, $oldValue, $newValue); @@ -107,7 +113,8 @@ protected function onPropertyChanged($propName, $oldValue, $newValue) { } /** @Entity @ChangeTrackingPolicy("NOTIFY") */ -class NotifyUser extends NotifyBaseEntity { +class NotifyUser extends NotifyBaseEntity +{ /** @Id @Column(type="integer") @GeneratedValue */ private $id; @@ -117,30 +124,36 @@ class NotifyUser extends NotifyBaseEntity { /** @ManyToMany(targetEntity="NotifyGroup") */ private $groups; - function __construct() { - $this->groups = new ArrayCollection; + function __construct() + { + $this->groups = new ArrayCollection(); } - function getId() { + function getId() + { return $this->id; } - function getName() { + function getName() + { return $this->name; } - function setName($name) { + function setName($name): void + { $this->onPropertyChanged('name', $this->name, $name); $this->name = $name; } - function getGroups() { + function getGroups() + { return $this->groups; } } /** @Entity */ -class NotifyGroup extends NotifyBaseEntity { +class NotifyGroup extends NotifyBaseEntity +{ /** @Id @Column(type="integer") @GeneratedValue */ private $id; @@ -150,25 +163,29 @@ class NotifyGroup extends NotifyBaseEntity { /** @ManyToMany(targetEntity="NotifyUser", mappedBy="groups") */ private $users; - function __construct() { - $this->users = new ArrayCollection; + function __construct() + { + $this->users = new ArrayCollection(); } - function getId() { + function getId() + { return $this->id; } - function getName() { + function getName() + { return $this->name; } - function setName($name) { + function setName($name): void + { $this->onPropertyChanged('name', $this->name, $name); $this->name = $name; } - function getUsers() { + function getUsers() + { return $this->users; } } - diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToManyBidirectionalAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToManyBidirectionalAssociationTest.php index 91f81a72dad..fe4a634565a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToManyBidirectionalAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToManyBidirectionalAssociationTest.php @@ -1,5 +1,7 @@ useModelSet('ecommerce'); parent::setUp(); @@ -30,7 +34,8 @@ protected function setUp() : void $this->secondFeature->setDescription('Annotations examples'); } - public function testSavesAOneToManyAssociationWithCascadeSaveSet() { + public function testSavesAOneToManyAssociationWithCascadeSaveSet(): void + { $this->product->addFeature($this->firstFeature); $this->product->addFeature($this->secondFeature); $this->_em->persist($this->product); @@ -40,7 +45,7 @@ public function testSavesAOneToManyAssociationWithCascadeSaveSet() { $this->assertFeatureForeignKeyIs($this->product->getId(), $this->secondFeature); } - public function testSavesAnEmptyCollection() + public function testSavesAnEmptyCollection(): void { $this->_em->persist($this->product); $this->_em->flush(); @@ -48,7 +53,8 @@ public function testSavesAnEmptyCollection() $this->assertEquals(0, count($this->product->getFeatures())); } - public function testDoesNotSaveAnInverseSideSet() { + public function testDoesNotSaveAnInverseSideSet(): void + { $this->product->brokenAddFeature($this->firstFeature); $this->_em->persist($this->product); $this->_em->flush(); @@ -56,7 +62,7 @@ public function testDoesNotSaveAnInverseSideSet() { $this->assertFeatureForeignKeyIs(null, $this->firstFeature); } - public function testRemovesOneToOneAssociation() + public function testRemovesOneToOneAssociation(): void { $this->product->addFeature($this->firstFeature); $this->product->addFeature($this->secondFeature); @@ -69,11 +75,11 @@ public function testRemovesOneToOneAssociation() $this->assertFeatureForeignKeyIs($this->product->getId(), $this->secondFeature); } - public function testEagerLoadsOneToManyAssociation() + public function testEagerLoadsOneToManyAssociation(): void { $this->_createFixture(); - $query = $this->_em->createQuery('select p, f from Doctrine\Tests\Models\ECommerce\ECommerceProduct p join p.features f'); - $result = $query->getResult(); + $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(); @@ -88,13 +94,13 @@ public function testEagerLoadsOneToManyAssociation() $this->assertEquals('Annotations examples', $features[1]->getDescription()); } - public function testLazyLoadsObjectsOnTheOwningSide() + public function testLazyLoadsObjectsOnTheOwningSide(): void { $this->_createFixture(); - $query = $this->_em->createQuery('select p from Doctrine\Tests\Models\ECommerce\ECommerceProduct p'); - $result = $query->getResult(); - $product = $result[0]; + $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()); @@ -107,11 +113,11 @@ public function testLazyLoadsObjectsOnTheOwningSide() $this->assertEquals('Annotations examples', $features[1]->getDescription()); } - public function testLazyLoadsObjectsOnTheInverseSide() + public function testLazyLoadsObjectsOnTheInverseSide(): void { $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(); @@ -122,12 +128,12 @@ public function testLazyLoadsObjectsOnTheInverseSide() $this->assertTrue($product->__isInitialized__); } - public function testLazyLoadsObjectsOnTheInverseSide2() + public function testLazyLoadsObjectsOnTheInverseSide2(): void { //$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(); @@ -145,9 +151,9 @@ public function testLazyLoadsObjectsOnTheInverseSide2() //$this->_em->getConnection()->getConfiguration()->setSQLLogger(null); } - public function testJoinFromOwningSide() + public function testJoinFromOwningSide(): void { - $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)); } @@ -155,7 +161,7 @@ public function testJoinFromOwningSide() /** * @group DDC-1637 */ - public function testMatching() + public function testMatching(): void { $this->_createFixture(); @@ -178,11 +184,11 @@ public function testMatching() /** * @group DDC-2340 */ - public function testMatchingOnDirtyCollection() + public function testMatchingOnDirtyCollection(): void { $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'); @@ -197,7 +203,7 @@ public function testMatchingOnDirtyCollection() $this->assertEquals(2, count($results)); } - public function testMatchingBis() + public function testMatchingBis(): void { $this->_createFixture(); @@ -221,7 +227,7 @@ public function testMatchingBis() $this->assertCount(3, $results); } - private function _createFixture() + private function _createFixture(): void { $this->product->addFeature($this->firstFeature); $this->product->addFeature($this->secondFeature); @@ -231,7 +237,8 @@ private function _createFixture() $this->_em->clear(); } - public function assertFeatureForeignKeyIs($value, ECommerceFeature $feature) { + public function assertFeatureForeignKeyIs($value, ECommerceFeature $feature): void + { $foreignKey = $this->_em->getConnection()->executeQuery( 'SELECT product_id FROM ecommerce_features WHERE id=?', [$feature->getId()] diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToManyOrphanRemovalTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToManyOrphanRemovalTest.php index ff75cb4fb2a..3f5f7e39349 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToManyOrphanRemovalTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToManyOrphanRemovalTest.php @@ -1,11 +1,15 @@ useModelSet('cms'); parent::setUp(); - $user = new CmsUser; - $user->status = 'dev'; + $user = new CmsUser(); + $user->status = 'dev'; $user->username = 'romanb'; - $user->name = 'Roman B.'; + $user->name = 'Roman B.'; - $phone1 = new CmsPhonenumber; + $phone1 = new CmsPhonenumber(); $phone1->phonenumber = '123456'; - $phone2 = new CmsPhonenumber; + $phone2 = new CmsPhonenumber(); $phone2->phonenumber = '234567'; $user->addPhonenumber($phone1); @@ -40,7 +44,7 @@ protected function setUp() : void $this->_em->clear(); } - public function testOrphanRemoval() + public function testOrphanRemoval(): void { $userProxy = $this->_em->getReference(CmsUser::class, $this->userId); @@ -62,7 +66,7 @@ public function testOrphanRemoval() /** * @group DDC-3382 */ - public function testOrphanRemovalRemoveFromCollection() + public function testOrphanRemovalRemoveFromCollection(): void { $user = $this->_em->find(CmsUser::class, $this->userId); @@ -80,7 +84,7 @@ public function testOrphanRemovalRemoveFromCollection() /** * @group DDC-3382 */ - public function testOrphanRemovalClearCollectionAndReAdd() + public function testOrphanRemovalClearCollectionAndReAdd(): void { $user = $this->_em->find(CmsUser::class, $this->userId); @@ -100,7 +104,7 @@ public function testOrphanRemovalClearCollectionAndReAdd() /** * @group DDC-2524 */ - public function testOrphanRemovalClearCollectionAndAddNew() + public function testOrphanRemovalClearCollectionAndAddNew(): void { $user = $this->_em->find(CmsUser::class, $this->userId); $newPhone = new CmsPhonenumber(); @@ -121,7 +125,7 @@ public function testOrphanRemovalClearCollectionAndAddNew() /** * @group DDC-1496 */ - public function testOrphanRemovalUnitializedCollection() + public function testOrphanRemovalUnitializedCollection(): void { $user = $this->_em->find(CmsUser::class, $this->userId); diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToManySelfReferentialAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToManySelfReferentialAssociationTest.php index be85a103921..b34c838ec25 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToManySelfReferentialAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToManySelfReferentialAssociationTest.php @@ -1,12 +1,16 @@ useModelSet('ecommerce'); parent::setUp(); @@ -28,7 +32,8 @@ protected function setUp() : void $this->secondChild->setName('Php books'); } - public function testSavesAOneToManyAssociationWithCascadeSaveSet() { + public function testSavesAOneToManyAssociationWithCascadeSaveSet(): void + { $this->parent->addChild($this->firstChild); $this->parent->addChild($this->secondChild); $this->_em->persist($this->parent); @@ -39,7 +44,7 @@ public function testSavesAOneToManyAssociationWithCascadeSaveSet() { $this->assertForeignKeyIs($this->parent->getId(), $this->secondChild); } - public function testSavesAnEmptyCollection() + public function testSavesAnEmptyCollection(): void { $this->_em->persist($this->parent); $this->_em->flush(); @@ -47,7 +52,8 @@ public function testSavesAnEmptyCollection() $this->assertEquals(0, count($this->parent->getChildren())); } - public function testDoesNotSaveAnInverseSideSet() { + public function testDoesNotSaveAnInverseSideSet(): void + { $this->parent->brokenAddChild($this->firstChild); $this->_em->persist($this->parent); $this->_em->flush(); @@ -55,7 +61,7 @@ public function testDoesNotSaveAnInverseSideSet() { $this->assertForeignKeyIs(null, $this->firstChild); } - public function testRemovesOneToManyAssociation() + public function testRemovesOneToManyAssociation(): void { $this->parent->addChild($this->firstChild); $this->parent->addChild($this->secondChild); @@ -68,14 +74,14 @@ public function testRemovesOneToManyAssociation() $this->assertForeignKeyIs($this->parent->getId(), $this->secondChild); } - public function testEagerLoadsOneToManyAssociation() + public function testEagerLoadsOneToManyAssociation(): void { $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)); - $parent = $result[0]; + $parent = $result[0]; $children = $parent->getChildren(); $this->assertInstanceOf(ECommerceCategory::class, $children[0]); @@ -86,15 +92,15 @@ public function testEagerLoadsOneToManyAssociation() $this->assertEquals(' books', strstr($children[1]->getName(), ' books')); } - public function testLazyLoadsOneToManyAssociation() + public function testLazyLoadsOneToManyAssociation(): void { $this->_createFixture(); - $metadata = $this->_em->getClassMetadata(ECommerceCategory::class); + $metadata = $this->_em->getClassMetadata(ECommerceCategory::class); $metadata->associationMappings['children']['fetch'] = ClassMetadata::FETCH_LAZY; - $query = $this->_em->createQuery('select c from Doctrine\Tests\Models\ECommerce\ECommerceCategory c order by c.id asc'); - $result = $query->getResult(); - $parent = $result[0]; + $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]); @@ -105,7 +111,7 @@ public function testLazyLoadsOneToManyAssociation() $this->assertEquals(' books', strstr($children[1]->getName(), ' books')); } - private function _createFixture() + private function _createFixture(): void { $this->parent->addChild($this->firstChild); $this->parent->addChild($this->secondChild); @@ -115,9 +121,9 @@ private function _createFixture() $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(); + public function assertForeignKeyIs($value, ECommerceCategory $child): void + { + $foreignKey = $this->_em->getConnection()->executeQuery('SELECT parent_id FROM ecommerce_categories WHERE id=?', [$child->getId()])->fetchColumn(); $this->assertEquals($value, $foreignKey); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToManyUnidirectionalAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToManyUnidirectionalAssociationTest.php index f521fb6dcb5..cc5859f1fe1 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToManyUnidirectionalAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToManyUnidirectionalAssociationTest.php @@ -1,11 +1,17 @@ useModelSet('routing'); parent::setUp(); - $locations = ["Berlin", "Bonn", "Brasilia", "Atlanta"]; + $locations = ['Berlin', 'Bonn', 'Brasilia', 'Atlanta']; - foreach ($locations AS $locationName) { - $location = new RoutingLocation(); + foreach ($locations as $locationName) { + $location = new RoutingLocation(); $location->name = $locationName; $this->_em->persist($location); $this->locations[$locationName] = $location; } + $this->_em->flush(); } - public function testPersistOwning_InverseCascade() + public function testPersistOwning_InverseCascade(): void { - $leg = new RoutingLeg(); - $leg->fromLocation = $this->locations['Berlin']; - $leg->toLocation = $this->locations['Bonn']; - $leg->departureDate = new \DateTime("now"); - $leg->arrivalDate = new \DateTime("now +5 hours"); + $leg = new RoutingLeg(); + $leg->fromLocation = $this->locations['Berlin']; + $leg->toLocation = $this->locations['Bonn']; + $leg->departureDate = new DateTime('now'); + $leg->arrivalDate = new DateTime('now +5 hours'); - $route = new RoutingRoute(); + $route = new RoutingRoute(); $route->legs[] = $leg; $this->_em->persist($route); @@ -46,27 +53,27 @@ public function testPersistOwning_InverseCascade() $this->_em->clear(); $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" + '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); + $this->assertEquals('Berlin', $routes->legs[0]->fromLocation->name); + $this->assertEquals('Bonn', $routes->legs[0]->toLocation->name); } - public function testLegsAreUniqueToRoutes() + public function testLegsAreUniqueToRoutes(): void { - $leg = new RoutingLeg(); - $leg->fromLocation = $this->locations['Berlin']; - $leg->toLocation = $this->locations['Bonn']; - $leg->departureDate = new \DateTime("now"); - $leg->arrivalDate = new \DateTime("now +5 hours"); + $leg = new RoutingLeg(); + $leg->fromLocation = $this->locations['Berlin']; + $leg->toLocation = $this->locations['Bonn']; + $leg->departureDate = new DateTime('now'); + $leg->arrivalDate = new DateTime('now +5 hours'); - $routeA = new RoutingRoute(); + $routeA = new RoutingRoute(); $routeA->legs[] = $leg; - $routeB = new RoutingRoute(); + $routeB = new RoutingRoute(); $routeB->legs[] = $leg; $this->_em->persist($routeA); @@ -76,10 +83,10 @@ public function testLegsAreUniqueToRoutes() try { // exception depending on the underlying Database Driver $this->_em->flush(); - } catch(\Exception $e) { + } catch (Exception $e) { $exceptionThrown = true; } - $this->assertTrue($exceptionThrown, "The underlying database driver throws an exception."); + $this->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 83691e886ee..41b2902c645 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToOneBidirectionalAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToOneBidirectionalAssociationTest.php @@ -1,8 +1,9 @@ useModelSet('ecommerce'); parent::setUp(); @@ -27,7 +28,8 @@ protected function setUp() : void $this->cart->setPayment('Credit card'); } - public function testSavesAOneToOneAssociationWithCascadeSaveSet() { + public function testSavesAOneToOneAssociationWithCascadeSaveSet(): void + { $this->customer->setCart($this->cart); $this->_em->persist($this->customer); $this->_em->flush(); @@ -35,7 +37,8 @@ public function testSavesAOneToOneAssociationWithCascadeSaveSet() { $this->assertCartForeignKeyIs($this->customer->getId()); } - public function testDoesNotSaveAnInverseSideSet() { + public function testDoesNotSaveAnInverseSideSet(): void + { $this->customer->brokenSetCart($this->cart); $this->_em->persist($this->customer); $this->_em->flush(); @@ -43,7 +46,7 @@ public function testDoesNotSaveAnInverseSideSet() { $this->assertCartForeignKeyIs(null); } - public function testRemovesOneToOneAssociation() + public function testRemovesOneToOneAssociation(): void { $this->customer->setCart($this->cart); $this->_em->persist($this->customer); @@ -54,39 +57,40 @@ public function testRemovesOneToOneAssociation() $this->assertCartForeignKeyIs(null); } - public function testEagerLoad() + public function testEagerLoad(): void { $this->_createFixture(); - $query = $this->_em->createQuery('select c, ca from Doctrine\Tests\Models\ECommerce\ECommerceCustomer c join c.cart ca'); - $result = $query->getResult(); + $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()); } - public function testLazyLoadsObjectsOnTheOwningSide() { + public function testLazyLoadsObjectsOnTheOwningSide(): void + { $this->_createFixture(); - $metadata = $this->_em->getClassMetadata(ECommerceCart::class); + $metadata = $this->_em->getClassMetadata(ECommerceCart::class); $metadata->associationMappings['customer']['fetchMode'] = ClassMetadata::FETCH_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]; + $cart = $result[0]; $this->assertInstanceOf(ECommerceCustomer::class, $cart->getCustomer()); $this->assertEquals('Giorgio', $cart->getCustomer()->getName()); } - public function testInverseSideIsNeverLazy() + public function testInverseSideIsNeverLazy(): void { $this->_createFixture(); - $metadata = $this->_em->getClassMetadata(ECommerceCustomer::class); + $metadata = $this->_em->getClassMetadata(ECommerceCustomer::class); $metadata->associationMappings['mentor']['fetch'] = ClassMetadata::FETCH_EAGER; - $query = $this->_em->createQuery('select c from Doctrine\Tests\Models\ECommerce\ECommerceCustomer c'); - $result = $query->getResult(); + $query = $this->_em->createQuery('select c from Doctrine\Tests\Models\ECommerce\ECommerceCustomer c'); + $result = $query->getResult(); $customer = $result[0]; $this->assertNull($customer->getMentor()); @@ -95,11 +99,11 @@ public function testInverseSideIsNeverLazy() $this->assertEquals('paypal', $customer->getCart()->getPayment()); } - public function testUpdateWithProxyObject() + public function testUpdateWithProxyObject(): void { - $cust = new ECommerceCustomer; + $cust = new ECommerceCustomer(); $cust->setName('Roman'); - $cart = new ECommerceCart; + $cart = new ECommerceCart(); $cart->setPayment('CARD'); $cust->setCart($cart); @@ -130,11 +134,11 @@ public function testUpdateWithProxyObject() $this->assertEquals('Roman', $cart3->getCustomer()->getName()); } - protected function _createFixture() + protected function _createFixture(): void { - $customer = new ECommerceCustomer; + $customer = new ECommerceCustomer(); $customer->setName('Giorgio'); - $cart = new ECommerceCart; + $cart = new ECommerceCart(); $cart->setPayment('paypal'); $customer->setCart($cart); @@ -144,9 +148,9 @@ protected function _createFixture() $this->_em->clear(); } - public function assertCartForeignKeyIs($value) { - $foreignKey = $this->_em->getConnection()->executeQuery('SELECT customer_id FROM ecommerce_carts WHERE id=?', [$this->cart->getId()] - )->fetchColumn(); + public function assertCartForeignKeyIs($value): void + { + $foreignKey = $this->_em->getConnection()->executeQuery('SELECT customer_id FROM ecommerce_carts WHERE id=?', [$this->cart->getId()])->fetchColumn(); $this->assertEquals($value, $foreignKey); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToOneEagerLoadingTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToOneEagerLoadingTest.php index 375242352ab..4c3e43a976c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToOneEagerLoadingTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToOneEagerLoadingTest.php @@ -1,40 +1,48 @@ _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) {} + } catch (Exception $e) { + } } /** * @group non-cacheable */ - public function testEagerLoadOneToOneOwningSide() + public function testEagerLoadOneToOneOwningSide(): void { - $train = new Train(new TrainOwner("Alexander")); - $driver = new TrainDriver("Benjamin"); + $train = new Train(new TrainOwner('Alexander')); + $driver = new TrainDriver('Benjamin'); $waggon = new Waggon(); $train->setDriver($driver); @@ -48,7 +56,7 @@ public function testEagerLoadOneToOneOwningSide() $train = $this->_em->find(get_class($train), $train->id); $this->assertNotInstanceOf(Proxy::class, $train->driver); - $this->assertEquals("Benjamin", $train->driver->name); + $this->assertEquals('Benjamin', $train->driver->name); $this->assertEquals($sqlCount + 1, count($this->_sqlLoggerStack->queries)); } @@ -56,9 +64,9 @@ public function testEagerLoadOneToOneOwningSide() /** * @group non-cacheable */ - public function testEagerLoadOneToOneNullOwningSide() + public function testEagerLoadOneToOneNullOwningSide(): void { - $train = new Train(new TrainOwner("Alexander")); + $train = new Train(new TrainOwner('Alexander')); $this->_em->persist($train); // cascades $this->_em->flush(); @@ -76,9 +84,9 @@ public function testEagerLoadOneToOneNullOwningSide() /** * @group non-cacheable */ - public function testEagerLoadOneToOneInverseSide() + public function testEagerLoadOneToOneInverseSide(): void { - $owner = new TrainOwner("Alexander"); + $owner = new TrainOwner('Alexander'); $train = new Train($owner); $this->_em->persist($train); // cascades @@ -97,9 +105,9 @@ public function testEagerLoadOneToOneInverseSide() /** * @group non-cacheable */ - public function testEagerLoadOneToOneNullInverseSide() + public function testEagerLoadOneToOneNullInverseSide(): void { - $driver = new TrainDriver("Dagny Taggert"); + $driver = new TrainDriver('Dagny Taggert'); $this->_em->persist($driver); $this->_em->flush(); @@ -116,9 +124,9 @@ public function testEagerLoadOneToOneNullInverseSide() $this->assertEquals($sqlCount + 1, count($this->_sqlLoggerStack->queries)); } - public function testEagerLoadManyToOne() + public function testEagerLoadManyToOne(): void { - $train = new Train(new TrainOwner("Alexander")); + $train = new Train(new TrainOwner('Alexander')); $waggon = new Waggon(); $train->addWaggon($waggon); @@ -134,10 +142,10 @@ public function testEagerLoadManyToOne() /** * @group non-cacheable */ - public function testEagerLoadWithNullableColumnsGeneratesLeftJoinOnBothSides() + public function testEagerLoadWithNullableColumnsGeneratesLeftJoinOnBothSides(): void { - $train = new Train(new TrainOwner("Alexander")); - $driver = new TrainDriver("Benjamin"); + $train = new Train(new TrainOwner('Alexander')); + $driver = new TrainDriver('Benjamin'); $train->setDriver($driver); $this->_em->persist($train); @@ -146,14 +154,14 @@ public function testEagerLoadWithNullableColumnsGeneratesLeftJoinOnBothSides() $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 = ?", + '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'] ); $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 (?)", + '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'] ); } @@ -161,12 +169,12 @@ public function testEagerLoadWithNullableColumnsGeneratesLeftJoinOnBothSides() /** * @group non-cacheable */ - public function testEagerLoadWithNonNullableColumnsGeneratesInnerJoinOnOwningSide() + public function testEagerLoadWithNonNullableColumnsGeneratesInnerJoinOnOwningSide(): void { $waggon = new Waggon(); // It should have a train - $train = new Train(new TrainOwner("Alexander")); + $train = new Train(new TrainOwner('Alexander')); $train->addWaggon($waggon); $this->_em->persist($train); @@ -177,13 +185,13 @@ public function testEagerLoadWithNonNullableColumnsGeneratesInnerJoinOnOwningSid // 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 (?)", + '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'] ); // 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 = ?", + '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'] ); } @@ -191,7 +199,7 @@ public function testEagerLoadWithNonNullableColumnsGeneratesInnerJoinOnOwningSid /** * @group non-cacheable */ - public function testEagerLoadWithNonNullableColumnsGeneratesLeftJoinOnNonOwningSide() + public function testEagerLoadWithNonNullableColumnsGeneratesLeftJoinOnNonOwningSide(): void { $owner = new TrainOwner('Alexander'); $train = new Train($owner); @@ -201,7 +209,7 @@ public function testEagerLoadWithNonNullableColumnsGeneratesLeftJoinOnNonOwningS $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 = ?", + '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'] ); } @@ -209,7 +217,7 @@ public function testEagerLoadWithNonNullableColumnsGeneratesLeftJoinOnNonOwningS /** * @group DDC-1946 */ - public function testEagerLoadingDoesNotBreakRefresh() + public function testEagerLoadingDoesNotBreakRefresh(): void { $train = new Train(new TrainOwner('Johannes')); $order = new TrainOrder($train); @@ -217,11 +225,11 @@ public function testEagerLoadingDoesNotBreakRefresh() $this->_em->persist($order); $this->_em->flush(); - $this->_em->getConnection()->exec("UPDATE TrainOrder SET train_id = NULL"); + $this->_em->getConnection()->exec('UPDATE TrainOrder SET train_id = NULL'); $this->assertSame($train, $order->train); $this->_em->refresh($order); - $this->assertTrue($order->train === null, "Train reference was not refreshed to NULL."); + $this->assertTrue($order->train === null, 'Train reference was not refreshed to NULL.'); } } @@ -237,19 +245,19 @@ class Train public $id; /** * Owning side + * * @OneToOne(targetEntity="TrainDriver", inversedBy="train", fetch="EAGER", cascade={"persist"}) * @JoinColumn(nullable=true) */ public $driver; /** * Owning side + * * @OneToOne(targetEntity="TrainOwner", inversedBy="train", fetch="EAGER", cascade={"persist"}) * @JoinColumn(nullable=false) */ public $owner; - /** - * @oneToMany(targetEntity="Waggon", mappedBy="train", cascade={"persist"}) - */ + /** @oneToMany(targetEntity="Waggon", mappedBy="train", cascade={"persist"}) */ public $waggons; public function __construct(TrainOwner $owner) @@ -258,19 +266,19 @@ public function __construct(TrainOwner $owner) $this->setOwner($owner); } - public function setDriver(TrainDriver $driver) + public function setDriver(TrainDriver $driver): void { $this->driver = $driver; $driver->setTrain($this); } - public function setOwner(TrainOwner $owner) + public function setOwner(TrainOwner $owner): void { $this->owner = $owner; $owner->setTrain($this); } - public function addWaggon(Waggon $w) + public function addWaggon(Waggon $w): void { $w->setTrain($this); $this->waggons[] = $w; @@ -288,6 +296,7 @@ class TrainDriver public $name; /** * Inverse side + * * @OneToOne(targetEntity="Train", mappedBy="driver", fetch="EAGER") */ public $train; @@ -297,7 +306,7 @@ public function __construct($name) $this->name = $name; } - public function setTrain(Train $t) + public function setTrain(Train $t): void { $this->train = $t; } @@ -314,6 +323,7 @@ class TrainOwner public $name; /** * Inverse side + * * @OneToOne(targetEntity="Train", mappedBy="owner", fetch="EAGER") */ public $train; @@ -323,7 +333,7 @@ public function __construct($name) $this->name = $name; } - public function setTrain(Train $t) + public function setTrain(Train $t): void { $this->train = $t; } @@ -342,7 +352,7 @@ class Waggon */ public $train; - public function setTrain($train) + public function setTrain($train): void { $this->train = $train; } diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToOneInverseSideLoadAfterDqlQueryTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToOneInverseSideLoadAfterDqlQueryTest.php index f0c51538c30..eb76a457cbe 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToOneInverseSideLoadAfterDqlQueryTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToOneInverseSideLoadAfterDqlQueryTest.php @@ -9,9 +9,11 @@ use Doctrine\Tests\Models\OneToOneInverseSideLoad\OwningSide; use Doctrine\Tests\OrmFunctionalTestCase; +use function assert; + class OneToOneInverseSideLoadAfterDqlQueryTest extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { parent::setUp(); @@ -20,7 +22,7 @@ protected function setUp() : void $this->_em->getClassMetadata(OwningSide::class), $this->_em->getClassMetadata(InverseSide::class), ]); - } catch(ToolsException $e) { + } catch (ToolsException $e) { // ignored } } @@ -43,7 +45,6 @@ public function testInverseSideOneToOneLoadedAfterDqlQuery(): void $this->_em->flush(); $this->_em->clear(); - /* @var $fetchedInverse InverseSide */ $fetchedInverse = $this ->_em ->createQueryBuilder() @@ -53,6 +54,7 @@ public function testInverseSideOneToOneLoadedAfterDqlQuery(): void ->setParameter('id', 'inverse') ->getQuery() ->getSingleResult(); + assert($fetchedInverse instanceof InverseSide); self::assertInstanceOf(InverseSide::class, $fetchedInverse); self::assertInstanceOf(OwningSide::class, $fetchedInverse->owning); diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToOneOrphanRemovalTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToOneOrphanRemovalTest.php index d99acc34b02..35caf365ede 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToOneOrphanRemovalTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToOneOrphanRemovalTest.php @@ -1,5 +1,7 @@ useModelSet('cms'); parent::setUp(); } - public function testOrphanRemoval() + public function testOrphanRemoval(): void { - $user = new CmsUser; - $user->status = 'dev'; + $user = new CmsUser(); + $user->status = 'dev'; $user->username = 'romanb'; - $user->name = 'Roman B.'; + $user->name = 'Roman B.'; - $address = new CmsAddress; + $address = new CmsAddress(); $address->country = 'de'; - $address->zip = 1234; - $address->city = 'Berlin'; + $address->zip = 1234; + $address->city = 'Berlin'; $user->setAddress($address); @@ -57,14 +61,14 @@ public function testOrphanRemoval() $this->assertEquals(0, count($result), 'CmsAddress should be removed by orphanRemoval'); } - public function testOrphanRemovalWhenUnlink() + public function testOrphanRemovalWhenUnlink(): void { - $user = new CmsUser; - $user->status = 'dev'; + $user = new CmsUser(); + $user->status = 'dev'; $user->username = 'beberlei'; - $user->name = 'Benjamin Eberlei'; + $user->name = 'Benjamin Eberlei'; - $email = new CmsEmail; + $email = new CmsEmail(); $email->email = 'beberlei@domain.com'; $user->setEmail($email); diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToOneSelfReferentialAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToOneSelfReferentialAssociationTest.php index cf15e7d6e04..81ae61ed38e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToOneSelfReferentialAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToOneSelfReferentialAssociationTest.php @@ -1,12 +1,16 @@ useModelSet('ecommerce'); parent::setUp(); @@ -30,7 +34,8 @@ protected function setUp() : void $this->mentor->setName('Obi-wan Kenobi'); } - public function testSavesAOneToOneAssociationWithCascadeSaveSet() { + public function testSavesAOneToOneAssociationWithCascadeSaveSet(): void + { $this->customer->setMentor($this->mentor); $this->_em->persist($this->customer); $this->_em->flush(); @@ -38,7 +43,7 @@ public function testSavesAOneToOneAssociationWithCascadeSaveSet() { $this->assertForeignKeyIs($this->mentor->getId()); } - public function testRemovesOneToOneAssociation() + public function testRemovesOneToOneAssociation(): void { $this->customer->setMentor($this->mentor); $this->_em->persist($this->customer); @@ -49,7 +54,7 @@ public function testRemovesOneToOneAssociation() $this->assertForeignKeyIs(null); } - public function testFind() + public function testFind(): void { $id = $this->_createFixture(); @@ -57,49 +62,48 @@ public function testFind() $this->assertNotInstanceOf(Proxy::class, $customer->getMentor()); } - public function testEagerLoadsAssociation() + public function testEagerLoadsAssociation(): void { $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'); - $result = $query->getResult(); + $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); } /** * @group mine - * @return unknown_type */ - public function testLazyLoadsAssociation() + public function testLazyLoadsAssociation(): unknown_type { $this->_createFixture(); - $metadata = $this->_em->getClassMetadata(ECommerceCustomer::class); + $metadata = $this->_em->getClassMetadata(ECommerceCustomer::class); $metadata->associationMappings['mentor']['fetch'] = ClassMetadata::FETCH_LAZY; - $query = $this->_em->createQuery("select c from Doctrine\Tests\Models\ECommerce\ECommerceCustomer c where c.name='Luke Skywalker'"); - $result = $query->getResult(); + $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); } - public function testMultiSelfReference() + public function testMultiSelfReference(): void { try { $this->_schemaTool->createSchema( [ - $this->_em->getClassMetadata(MultiSelfReference::class) + $this->_em->getClassMetadata(MultiSelfReference::class), ] ); - } catch (\Exception $e) { + } catch (Exception $e) { // Swallow all exceptions. We do not test the schema tool here. } $entity1 = new MultiSelfReference(); $this->_em->persist($entity1); - $entity1->setOther1($entity2 = new MultiSelfReference); - $entity1->setOther2($entity3 = new MultiSelfReference); + $entity1->setOther1($entity2 = new MultiSelfReference()); + $entity1->setOther2($entity3 = new MultiSelfReference()); $this->_em->flush(); $this->_em->clear(); @@ -114,23 +118,23 @@ public function testMultiSelfReference() $this->assertNull($entity2->getOther2()->getOther2()); } - public function assertLoadingOfAssociation($customer) + public function assertLoadingOfAssociation($customer): void { $this->assertInstanceOf(ECommerceCustomer::class, $customer->getMentor()); $this->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(); + public function assertForeignKeyIs($value): void + { + $foreignKey = $this->_em->getConnection()->executeQuery('SELECT mentor_id FROM ecommerce_customers WHERE id=?', [$this->customer->getId()])->fetchColumn(); $this->assertEquals($value, $foreignKey); } private function _createFixture() { - $customer = new ECommerceCustomer; + $customer = new ECommerceCustomer(); $customer->setName('Luke Skywalker'); - $mentor = new ECommerceCustomer; + $mentor = new ECommerceCustomer(); $mentor->setName('Obi-wan Kenobi'); $customer->setMentor($mentor); @@ -146,7 +150,8 @@ private function _createFixture() /** * @Entity */ -class MultiSelfReference { +class MultiSelfReference +{ /** @Id @GeneratedValue(strategy="AUTO") @Column(type="integer") */ private $id; /** @@ -160,9 +165,28 @@ class MultiSelfReference { */ private $other2; - public function getId() {return $this->id;} - public function setOther1($other1) {$this->other1 = $other1;} - public function getOther1() {return $this->other1;} - public function setOther2($other2) {$this->other2 = $other2;} - public function getOther2() {return $this->other2;} + public function getId() + { + return $this->id; + } + + public function setOther1($other1): void + { + $this->other1 = $other1; + } + + public function getOther1() + { + return $this->other1; + } + + public function setOther2($other2): void + { + $this->other2 = $other2; + } + + public function getOther2() + { + return $this->other2; + } } diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToOneSingleTableInheritanceTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToOneSingleTableInheritanceTest.php index b20ab908210..b871e688148 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToOneSingleTableInheritanceTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToOneSingleTableInheritanceTest.php @@ -1,16 +1,19 @@ litterBox = new LitterBox(); @@ -37,8 +40,8 @@ public function testFindFromOneToOneOwningSideJoinedTableInheritance() $this->_em->flush(); $this->_em->clear(); - /* @var $foundCat Cat */ $foundCat = $this->_em->find(Pet::class, $cat->id); + assert($foundCat instanceof Cat); $this->assertInstanceOf(Cat::class, $foundCat); $this->assertSame($cat->id, $foundCat->id); diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToOneUnidirectionalAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToOneUnidirectionalAssociationTest.php index 2d967167a8d..50bb4bfe0ba 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToOneUnidirectionalAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToOneUnidirectionalAssociationTest.php @@ -1,14 +1,17 @@ useModelSet('ecommerce'); parent::setUp(); @@ -28,7 +31,8 @@ protected function setUp() : void $this->shipping->setDays('5'); } - public function testSavesAOneToOneAssociationWithCascadeSaveSet() { + public function testSavesAOneToOneAssociationWithCascadeSaveSet(): void + { $this->product->setShipping($this->shipping); $this->_em->persist($this->product); $this->_em->flush(); @@ -36,7 +40,7 @@ public function testSavesAOneToOneAssociationWithCascadeSaveSet() { $this->assertForeignKeyIs($this->shipping->getId()); } - public function testRemovesOneToOneAssociation() + public function testRemovesOneToOneAssociation(): void { $this->product->setShipping($this->shipping); $this->_em->persist($this->product); @@ -47,48 +51,50 @@ public function testRemovesOneToOneAssociation() $this->assertForeignKeyIs(null); } - public function _testEagerLoad() + public function _testEagerLoad(): void { $this->_createFixture(); - $query = $this->_em->createQuery('select p, s from Doctrine\Tests\Models\ECommerce\ECommerceProduct p left join p.shipping s'); - $result = $query->getResult(); + $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()); } - public function testLazyLoadsObjects() { + public function testLazyLoadsObjects(): void + { $this->_createFixture(); - $metadata = $this->_em->getClassMetadata(ECommerceProduct::class); + $metadata = $this->_em->getClassMetadata(ECommerceProduct::class); $metadata->associationMappings['shipping']['fetch'] = ClassMetadata::FETCH_LAZY; - $query = $this->_em->createQuery('select p from Doctrine\Tests\Models\ECommerce\ECommerceProduct p'); - $result = $query->getResult(); + $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()); } - public function testDoesNotLazyLoadObjectsIfConfigurationDoesNotAllowIt() { + public function testDoesNotLazyLoadObjectsIfConfigurationDoesNotAllowIt(): void + { $this->_createFixture(); $query = $this->_em->createQuery('select p from Doctrine\Tests\Models\ECommerce\ECommerceProduct p'); $query->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true); - $result = $query->getResult(); + $result = $query->getResult(); $product = $result[0]; $this->assertNull($product->getShipping()); } - protected function _createFixture() + protected function _createFixture(): void { - $product = new ECommerceProduct; + $product = new ECommerceProduct(); $product->setName('Php manual'); - $shipping = new ECommerceShipping; + $shipping = new ECommerceShipping(); $shipping->setDays('1'); $product->setShipping($shipping); @@ -98,7 +104,8 @@ protected function _createFixture() $this->_em->clear(); } - public function assertForeignKeyIs($value) { + public function assertForeignKeyIs($value): void + { $foreignKey = $this->_em->getConnection()->executeQuery( 'SELECT shipping_id FROM ecommerce_products WHERE id=?', [$this->product->getId()] @@ -109,7 +116,7 @@ public function assertForeignKeyIs($value) { /** * @group DDC-762 */ - public function testNullForeignKey() + public function testNullForeignKey(): void { $product = new ECommerceProduct(); $product->setName('Doctrine 2 Manual'); diff --git a/tests/Doctrine/Tests/ORM/Functional/OrderedCollectionTest.php b/tests/Doctrine/Tests/ORM/Functional/OrderedCollectionTest.php index 00de0cd05a8..83a74a60a0f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OrderedCollectionTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OrderedCollectionTest.php @@ -1,30 +1,36 @@ useModelSet('routing'); parent::setUp(); - $locations = ["Berlin", "Bonn", "Brasilia", "Atlanta"]; + $locations = ['Berlin', 'Bonn', 'Brasilia', 'Atlanta']; - foreach ($locations AS $locationName) { - $location = new RoutingLocation(); + foreach ($locations as $locationName) { + $location = new RoutingLocation(); $location->name = $locationName; $this->_em->persist($location); $this->locations[$locationName] = $location; } + $this->_em->flush(); } @@ -32,17 +38,17 @@ public function createPersistedRouteWithLegs() { $route = new RoutingRoute(); - $leg1 = new RoutingLeg(); - $leg1->fromLocation = $this->locations['Berlin']; - $leg1->toLocation = $this->locations['Bonn']; - $leg1->departureDate = new \DateTime("now"); - $leg1->arrivalDate = new \DateTime("now +5 hours"); + $leg1 = new RoutingLeg(); + $leg1->fromLocation = $this->locations['Berlin']; + $leg1->toLocation = $this->locations['Bonn']; + $leg1->departureDate = new DateTime('now'); + $leg1->arrivalDate = new DateTime('now +5 hours'); - $leg2 = new RoutingLeg(); - $leg2->fromLocation = $this->locations['Bonn']; - $leg2->toLocation = $this->locations['Brasilia']; - $leg2->departureDate = new \DateTime("now +6 hours"); - $leg2->arrivalDate = new \DateTime("now +24 hours"); + $leg2 = new RoutingLeg(); + $leg2->fromLocation = $this->locations['Bonn']; + $leg2->toLocation = $this->locations['Brasilia']; + $leg2->departureDate = new DateTime('now +6 hours'); + $leg2->arrivalDate = new DateTime('now +24 hours'); $route->legs[] = $leg2; $route->legs[] = $leg1; @@ -55,18 +61,18 @@ public function createPersistedRouteWithLegs() return $routeId; } - public function testLazyManyToManyCollection_IsRetrievedWithOrderByClause() + public function testLazyManyToManyCollection_IsRetrievedWithOrderByClause(): void { $routeId = $this->createPersistedRouteWithLegs(); $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()); + $this->assertEquals('Berlin', $route->legs[0]->fromLocation->getName()); + $this->assertEquals('Bonn', $route->legs[1]->fromLocation->getName()); } - public function testLazyOneToManyCollection_IsRetrievedWithOrderByClause() + public function testLazyOneToManyCollection_IsRetrievedWithOrderByClause(): void { $route = new RoutingRoute(); @@ -74,15 +80,15 @@ public function testLazyOneToManyCollection_IsRetrievedWithOrderByClause() $this->_em->flush(); $routeId = $route->id; - $booking1 = new RoutingRouteBooking(); - $booking1->passengerName = "Guilherme"; - $booking2 = new RoutingRouteBooking(); - $booking2->passengerName = "Benjamin"; + $booking1 = new RoutingRouteBooking(); + $booking1->passengerName = 'Guilherme'; + $booking2 = new RoutingRouteBooking(); + $booking2->passengerName = 'Benjamin'; $route->bookings[] = $booking1; - $booking1->route = $route; + $booking1->route = $route; $route->bookings[] = $booking2; - $booking2->route = $route; + $booking2->route = $route; $this->_em->persist($booking1); $this->_em->persist($booking2); @@ -97,16 +103,16 @@ public function testLazyOneToManyCollection_IsRetrievedWithOrderByClause() $this->assertEquals('Guilherme', $route->bookings[1]->getPassengerName()); } - public function testOrderedResultFromDqlQuery() + public function testOrderedResultFromDqlQuery(): void { $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()); + $this->assertEquals('Berlin', $route->legs[0]->fromLocation->getName()); + $this->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 166187af973..43e4c530cd7 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OrderedJoinedTableInheritanceCollectionTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OrderedJoinedTableInheritanceCollectionTest.php @@ -1,39 +1,41 @@ */ class OrderedJoinedTableInheritanceCollectionTest extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { parent::setUp(); try { $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) { + } catch (Exception $e) { // Swallow all exceptions. We do not test the schema tool here. } - $dog = new OJTIC_Dog(); - $dog->name = "Poofy"; + $dog = new OJTIC_Dog(); + $dog->name = 'Poofy'; - $dog1 = new OJTIC_Dog(); - $dog1->name = "Zampa"; - $dog2 = new OJTIC_Dog(); - $dog2->name = "Aari"; + $dog1 = new OJTIC_Dog(); + $dog1->name = 'Zampa'; + $dog2 = new OJTIC_Dog(); + $dog2->name = 'Aari'; $dog1->mother = $dog; $dog2->mother = $dog; @@ -48,7 +50,7 @@ protected function setUp() : void $this->_em->clear(); } - public function testOrderdOneToManyCollection() + public function testOrderdOneToManyCollection(): void { $poofy = $this->_em->createQuery("SELECT p FROM Doctrine\Tests\ORM\Functional\OJTIC_Pet p WHERE p.name = 'Poofy'")->getSingleResult(); @@ -58,7 +60,8 @@ public function testOrderdOneToManyCollection() $this->_em->clear(); $result = $this->_em->createQuery( - "SELECT p, c FROM Doctrine\Tests\ORM\Functional\OJTIC_Pet p JOIN p.children c WHERE p.name = 'Poofy'") + "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)); @@ -86,15 +89,10 @@ abstract class OJTIC_Pet */ public $id; - /** - * - * @Column - */ + /** @Column */ public $name; - /** - * @ManyToOne(targetEntity="OJTIC_PET") - */ + /** @ManyToOne(targetEntity="OJTIC_PET") */ public $mother; /** @@ -123,7 +121,6 @@ public function getName() */ class OJTIC_Cat extends OJTIC_Pet { - } /** @@ -131,5 +128,4 @@ class OJTIC_Cat extends OJTIC_Pet */ 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 36959743ee5..823f5c11d79 100644 --- a/tests/Doctrine/Tests/ORM/Functional/PaginationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/PaginationTest.php @@ -1,5 +1,7 @@ useModelSet('cms'); $this->useModelSet('pagination'); @@ -46,9 +51,9 @@ protected function setUp() : void /** * @dataProvider useOutputWalkers */ - public function testCountSimpleWithoutJoin($useOutputWalkers) + public function testCountSimpleWithoutJoin($useOutputWalkers): void { - $dql = 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u'; + $dql = 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u'; $query = $this->_em->createQuery($dql); $paginator = new Paginator($query); @@ -59,9 +64,9 @@ public function testCountSimpleWithoutJoin($useOutputWalkers) /** * @dataProvider useOutputWalkers */ - public function testCountWithFetchJoin($useOutputWalkers) + public function testCountWithFetchJoin($useOutputWalkers): void { - $dql = 'SELECT u,g FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.groups g'; + $dql = 'SELECT u,g FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.groups g'; $query = $this->_em->createQuery($dql); $paginator = new Paginator($query); @@ -69,9 +74,9 @@ public function testCountWithFetchJoin($useOutputWalkers) $this->assertCount(9, $paginator); } - public function testCountComplexWithOutputWalker() + public function testCountComplexWithOutputWalker(): void { - $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'; + $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); $paginator = new Paginator($query); @@ -79,15 +84,15 @@ public function testCountComplexWithOutputWalker() $this->assertCount(3, $paginator); } - public function testCountComplexWithoutOutputWalker() + public function testCountComplexWithoutOutputWalker(): void { - $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'; + $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); $paginator = new Paginator($query); $paginator->setUseOutputWalkers(false); - $this->expectException(\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Cannot count query that uses a HAVING clause. Use the output walkers for pagination'); $this->assertCount(3, $paginator); @@ -96,9 +101,9 @@ public function testCountComplexWithoutOutputWalker() /** * @dataProvider useOutputWalkers */ - public function testCountWithComplexScalarOrderBy($useOutputWalkers) + public function testCountWithComplexScalarOrderBy($useOutputWalkers): void { - $dql = 'SELECT l FROM Doctrine\Tests\Models\Pagination\Logo l ORDER BY l.image_width * l.image_height DESC'; + $dql = 'SELECT l FROM Doctrine\Tests\Models\Pagination\Logo l ORDER BY l.image_width * l.image_height DESC'; $query = $this->_em->createQuery($dql); $paginator = new Paginator($query); @@ -109,9 +114,9 @@ public function testCountWithComplexScalarOrderBy($useOutputWalkers) /** * @dataProvider useOutputWalkersAndFetchJoinCollection */ - public function testIterateSimpleWithoutJoin($useOutputWalkers, $fetchJoinCollection) + public function testIterateSimpleWithoutJoin($useOutputWalkers, $fetchJoinCollection): void { - $dql = 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u'; + $dql = 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u'; $query = $this->_em->createQuery($dql); $paginator = new Paginator($query, $fetchJoinCollection); @@ -131,10 +136,10 @@ public function testIterateSimpleWithoutJoin($useOutputWalkers, $fetchJoinCollec $this->assertCount(3, $paginator->getIterator()); } - private function iterateWithOrderAsc($useOutputWalkers, $fetchJoinCollection, $baseDql, $checkField) + private function iterateWithOrderAsc($useOutputWalkers, $fetchJoinCollection, $baseDql, $checkField): void { // Ascending - $dql = "$baseDql ASC"; + $dql = "$baseDql ASC"; $query = $this->_em->createQuery($dql); $paginator = new Paginator($query, $fetchJoinCollection); @@ -142,13 +147,13 @@ private function iterateWithOrderAsc($useOutputWalkers, $fetchJoinCollection, $b $iter = $paginator->getIterator(); $this->assertCount(9, $iter); $result = iterator_to_array($iter); - $this->assertEquals($checkField . "0", $result[0]->$checkField); + $this->assertEquals($checkField . '0', $result[0]->$checkField); } - private function iterateWithOrderAscWithLimit($useOutputWalkers, $fetchJoinCollection, $baseDql, $checkField) + private function iterateWithOrderAscWithLimit($useOutputWalkers, $fetchJoinCollection, $baseDql, $checkField): void { // Ascending - $dql = "$baseDql ASC"; + $dql = "$baseDql ASC"; $query = $this->_em->createQuery($dql); // With limit @@ -158,13 +163,13 @@ private function iterateWithOrderAscWithLimit($useOutputWalkers, $fetchJoinColle $iter = $paginator->getIterator(); $this->assertCount(3, $iter); $result = iterator_to_array($iter); - $this->assertEquals($checkField . "0", $result[0]->$checkField); + $this->assertEquals($checkField . '0', $result[0]->$checkField); } - private function iterateWithOrderAscWithLimitAndOffset($useOutputWalkers, $fetchJoinCollection, $baseDql, $checkField) + private function iterateWithOrderAscWithLimitAndOffset($useOutputWalkers, $fetchJoinCollection, $baseDql, $checkField): void { // Ascending - $dql = "$baseDql ASC"; + $dql = "$baseDql ASC"; $query = $this->_em->createQuery($dql); // With offset @@ -174,12 +179,12 @@ private function iterateWithOrderAscWithLimitAndOffset($useOutputWalkers, $fetch $iter = $paginator->getIterator(); $this->assertCount(3, $iter); $result = iterator_to_array($iter); - $this->assertEquals($checkField . "3", $result[0]->$checkField); + $this->assertEquals($checkField . '3', $result[0]->$checkField); } - private function iterateWithOrderDesc($useOutputWalkers, $fetchJoinCollection, $baseDql, $checkField) + private function iterateWithOrderDesc($useOutputWalkers, $fetchJoinCollection, $baseDql, $checkField): void { - $dql = "$baseDql DESC"; + $dql = "$baseDql DESC"; $query = $this->_em->createQuery($dql); $paginator = new Paginator($query, $fetchJoinCollection); @@ -187,12 +192,12 @@ private function iterateWithOrderDesc($useOutputWalkers, $fetchJoinCollection, $ $iter = $paginator->getIterator(); $this->assertCount(9, $iter); $result = iterator_to_array($iter); - $this->assertEquals($checkField . "8", $result[0]->$checkField); + $this->assertEquals($checkField . '8', $result[0]->$checkField); } - private function iterateWithOrderDescWithLimit($useOutputWalkers, $fetchJoinCollection, $baseDql, $checkField) + private function iterateWithOrderDescWithLimit($useOutputWalkers, $fetchJoinCollection, $baseDql, $checkField): void { - $dql = "$baseDql DESC"; + $dql = "$baseDql DESC"; $query = $this->_em->createQuery($dql); // With limit @@ -202,12 +207,12 @@ private function iterateWithOrderDescWithLimit($useOutputWalkers, $fetchJoinColl $iter = $paginator->getIterator(); $this->assertCount(3, $iter); $result = iterator_to_array($iter); - $this->assertEquals($checkField . "8", $result[0]->$checkField); + $this->assertEquals($checkField . '8', $result[0]->$checkField); } - private function iterateWithOrderDescWithLimitAndOffset($useOutputWalkers, $fetchJoinCollection, $baseDql, $checkField) + private function iterateWithOrderDescWithLimitAndOffset($useOutputWalkers, $fetchJoinCollection, $baseDql, $checkField): void { - $dql = "$baseDql DESC"; + $dql = "$baseDql DESC"; $query = $this->_em->createQuery($dql); // With offset @@ -217,81 +222,81 @@ private function iterateWithOrderDescWithLimitAndOffset($useOutputWalkers, $fetc $iter = $paginator->getIterator(); $this->assertCount(3, $iter); $result = iterator_to_array($iter); - $this->assertEquals($checkField . "5", $result[0]->$checkField); + $this->assertEquals($checkField . '5', $result[0]->$checkField); } /** * @dataProvider useOutputWalkersAndFetchJoinCollection */ - public function testIterateSimpleWithoutJoinWithOrder($useOutputWalkers, $fetchJoinCollection) + public function testIterateSimpleWithoutJoinWithOrder($useOutputWalkers, $fetchJoinCollection): void { // Ascending $dql = 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.username'; - $this->iterateWithOrderAsc($useOutputWalkers, $fetchJoinCollection, $dql, "username"); - $this->iterateWithOrderDesc($useOutputWalkers, $fetchJoinCollection, $dql, "username"); + $this->iterateWithOrderAsc($useOutputWalkers, $fetchJoinCollection, $dql, 'username'); + $this->iterateWithOrderDesc($useOutputWalkers, $fetchJoinCollection, $dql, 'username'); } /** * @dataProvider useOutputWalkersAndFetchJoinCollection */ - public function testIterateSimpleWithoutJoinWithOrderAndLimit($useOutputWalkers, $fetchJoinCollection) + public function testIterateSimpleWithoutJoinWithOrderAndLimit($useOutputWalkers, $fetchJoinCollection): void { // Ascending $dql = 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.username'; - $this->iterateWithOrderAscWithLimit($useOutputWalkers, $fetchJoinCollection, $dql, "username"); - $this->iterateWithOrderDescWithLimit($useOutputWalkers, $fetchJoinCollection, $dql, "username"); + $this->iterateWithOrderAscWithLimit($useOutputWalkers, $fetchJoinCollection, $dql, 'username'); + $this->iterateWithOrderDescWithLimit($useOutputWalkers, $fetchJoinCollection, $dql, 'username'); } /** * @dataProvider useOutputWalkersAndFetchJoinCollection */ - public function testIterateSimpleWithoutJoinWithOrderAndLimitAndOffset($useOutputWalkers, $fetchJoinCollection) + public function testIterateSimpleWithoutJoinWithOrderAndLimitAndOffset($useOutputWalkers, $fetchJoinCollection): void { // Ascending $dql = 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.username'; - $this->iterateWithOrderAscWithLimitAndOffset($useOutputWalkers, $fetchJoinCollection, $dql, "username"); - $this->iterateWithOrderDescWithLimitAndOffset($useOutputWalkers, $fetchJoinCollection, $dql, "username"); + $this->iterateWithOrderAscWithLimitAndOffset($useOutputWalkers, $fetchJoinCollection, $dql, 'username'); + $this->iterateWithOrderDescWithLimitAndOffset($useOutputWalkers, $fetchJoinCollection, $dql, 'username'); } /** * @dataProvider fetchJoinCollection */ - public function testIterateSimpleWithOutputWalkerWithoutJoinWithComplexOrder($fetchJoinCollection) + public function testIterateSimpleWithOutputWalkerWithoutJoinWithComplexOrder($fetchJoinCollection): void { // Ascending $dql = 'SELECT l FROM Doctrine\Tests\Models\Pagination\Logo l ORDER BY l.image_width * l.image_height'; - $this->iterateWithOrderAsc(true, $fetchJoinCollection, $dql, "image"); - $this->iterateWithOrderDesc(true, $fetchJoinCollection, $dql, "image"); + $this->iterateWithOrderAsc(true, $fetchJoinCollection, $dql, 'image'); + $this->iterateWithOrderDesc(true, $fetchJoinCollection, $dql, 'image'); } /** * @dataProvider fetchJoinCollection */ - public function testIterateSimpleWithOutputWalkerWithoutJoinWithComplexOrderAndLimit($fetchJoinCollection) + public function testIterateSimpleWithOutputWalkerWithoutJoinWithComplexOrderAndLimit($fetchJoinCollection): void { // Ascending $dql = 'SELECT l FROM Doctrine\Tests\Models\Pagination\Logo l ORDER BY l.image_width * l.image_height'; - $this->iterateWithOrderAscWithLimit(true, $fetchJoinCollection, $dql, "image"); - $this->iterateWithOrderDescWithLimit(true, $fetchJoinCollection, $dql, "image"); + $this->iterateWithOrderAscWithLimit(true, $fetchJoinCollection, $dql, 'image'); + $this->iterateWithOrderDescWithLimit(true, $fetchJoinCollection, $dql, 'image'); } /** * @dataProvider fetchJoinCollection */ - public function testIterateSimpleWithOutputWalkerWithoutJoinWithComplexOrderAndLimitAndOffset($fetchJoinCollection) + public function testIterateSimpleWithOutputWalkerWithoutJoinWithComplexOrderAndLimitAndOffset($fetchJoinCollection): void { // Ascending $dql = 'SELECT l FROM Doctrine\Tests\Models\Pagination\Logo l ORDER BY l.image_width * l.image_height'; - $this->iterateWithOrderAscWithLimitAndOffset(true, $fetchJoinCollection, $dql, "image"); - $this->iterateWithOrderDescWithLimitAndOffset(true, $fetchJoinCollection, $dql, "image"); + $this->iterateWithOrderAscWithLimitAndOffset(true, $fetchJoinCollection, $dql, 'image'); + $this->iterateWithOrderDescWithLimitAndOffset(true, $fetchJoinCollection, $dql, 'image'); } /** * @dataProvider useOutputWalkers */ - public function testIterateWithFetchJoin($useOutputWalkers) + public function testIterateWithFetchJoin($useOutputWalkers): void { - $dql = 'SELECT u,g FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.groups g'; + $dql = 'SELECT u,g FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.groups g'; $query = $this->_em->createQuery($dql); $paginator = new Paginator($query, true); @@ -302,172 +307,172 @@ public function testIterateWithFetchJoin($useOutputWalkers) /** * @dataProvider useOutputWalkers */ - public function testIterateWithFetchJoinWithOrder($useOutputWalkers) + public function testIterateWithFetchJoinWithOrder($useOutputWalkers): void { $dql = 'SELECT u,g FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.groups g ORDER BY u.username'; - $this->iterateWithOrderAsc($useOutputWalkers, true, $dql, "username"); - $this->iterateWithOrderDesc($useOutputWalkers, true, $dql, "username"); + $this->iterateWithOrderAsc($useOutputWalkers, true, $dql, 'username'); + $this->iterateWithOrderDesc($useOutputWalkers, true, $dql, 'username'); } /** * @dataProvider useOutputWalkers */ - public function testIterateWithFetchJoinWithOrderAndLimit($useOutputWalkers) + public function testIterateWithFetchJoinWithOrderAndLimit($useOutputWalkers): void { $dql = 'SELECT u,g FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.groups g ORDER BY u.username'; - $this->iterateWithOrderAscWithLimit($useOutputWalkers, true, $dql, "username"); - $this->iterateWithOrderDescWithLimit($useOutputWalkers, true, $dql, "username"); + $this->iterateWithOrderAscWithLimit($useOutputWalkers, true, $dql, 'username'); + $this->iterateWithOrderDescWithLimit($useOutputWalkers, true, $dql, 'username'); } /** * @dataProvider useOutputWalkers */ - public function testIterateWithFetchJoinWithOrderAndLimitAndOffset($useOutputWalkers) + public function testIterateWithFetchJoinWithOrderAndLimitAndOffset($useOutputWalkers): void { $dql = 'SELECT u,g FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.groups g ORDER BY u.username'; - $this->iterateWithOrderAscWithLimitAndOffset($useOutputWalkers, true, $dql, "username"); - $this->iterateWithOrderDescWithLimitAndOffset($useOutputWalkers, true, $dql, "username"); + $this->iterateWithOrderAscWithLimitAndOffset($useOutputWalkers, true, $dql, 'username'); + $this->iterateWithOrderDescWithLimitAndOffset($useOutputWalkers, true, $dql, 'username'); } /** * @dataProvider useOutputWalkersAndFetchJoinCollection */ - public function testIterateWithRegularJoinWithOrderByColumnFromJoined($useOutputWalkers, $fetchJoinCollection) + public function testIterateWithRegularJoinWithOrderByColumnFromJoined($useOutputWalkers, $fetchJoinCollection): void { $dql = 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.email e ORDER BY e.email'; - $this->iterateWithOrderAsc($useOutputWalkers, $fetchJoinCollection, $dql, "username"); - $this->iterateWithOrderDesc($useOutputWalkers, $fetchJoinCollection, $dql, "username"); + $this->iterateWithOrderAsc($useOutputWalkers, $fetchJoinCollection, $dql, 'username'); + $this->iterateWithOrderDesc($useOutputWalkers, $fetchJoinCollection, $dql, 'username'); } /** * @dataProvider useOutputWalkersAndFetchJoinCollection */ - public function testIterateWithRegularJoinWithOrderByColumnFromJoinedWithLimit($useOutputWalkers, $fetchJoinCollection) + public function testIterateWithRegularJoinWithOrderByColumnFromJoinedWithLimit($useOutputWalkers, $fetchJoinCollection): void { $dql = 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.email e ORDER BY e.email'; - $this->iterateWithOrderAscWithLimit($useOutputWalkers, $fetchJoinCollection, $dql, "username"); - $this->iterateWithOrderDescWithLimit($useOutputWalkers, $fetchJoinCollection, $dql, "username"); + $this->iterateWithOrderAscWithLimit($useOutputWalkers, $fetchJoinCollection, $dql, 'username'); + $this->iterateWithOrderDescWithLimit($useOutputWalkers, $fetchJoinCollection, $dql, 'username'); } /** * @dataProvider useOutputWalkersAndFetchJoinCollection */ - public function testIterateWithRegularJoinWithOrderByColumnFromJoinedWithLimitAndOffset($useOutputWalkers, $fetchJoinCollection) + public function testIterateWithRegularJoinWithOrderByColumnFromJoinedWithLimitAndOffset($useOutputWalkers, $fetchJoinCollection): void { $dql = 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.email e ORDER BY e.email'; - $this->iterateWithOrderAscWithLimitAndOffset($useOutputWalkers, $fetchJoinCollection, $dql, "username"); - $this->iterateWithOrderDescWithLimitAndOffset($useOutputWalkers, $fetchJoinCollection, $dql, "username"); + $this->iterateWithOrderAscWithLimitAndOffset($useOutputWalkers, $fetchJoinCollection, $dql, 'username'); + $this->iterateWithOrderDescWithLimitAndOffset($useOutputWalkers, $fetchJoinCollection, $dql, 'username'); } /** * @dataProvider fetchJoinCollection */ - public function testIterateWithOutputWalkersWithRegularJoinWithComplexOrderByReferencingJoined($fetchJoinCollection) + public function testIterateWithOutputWalkersWithRegularJoinWithComplexOrderByReferencingJoined($fetchJoinCollection): void { // long function name is loooooooooooong $dql = 'SELECT c FROM Doctrine\Tests\Models\Pagination\Company c JOIN c.logo l ORDER BY l.image_height * l.image_width'; - $this->iterateWithOrderAsc(true, $fetchJoinCollection, $dql, "name"); - $this->iterateWithOrderDesc(true, $fetchJoinCollection, $dql, "name"); + $this->iterateWithOrderAsc(true, $fetchJoinCollection, $dql, 'name'); + $this->iterateWithOrderDesc(true, $fetchJoinCollection, $dql, 'name'); } /** * @dataProvider fetchJoinCollection */ - public function testIterateWithOutputWalkersWithRegularJoinWithComplexOrderByReferencingJoinedWithLimit($fetchJoinCollection) + public function testIterateWithOutputWalkersWithRegularJoinWithComplexOrderByReferencingJoinedWithLimit($fetchJoinCollection): void { // long function name is loooooooooooong $dql = 'SELECT c FROM Doctrine\Tests\Models\Pagination\Company c JOIN c.logo l ORDER BY l.image_height * l.image_width'; - $this->iterateWithOrderAscWithLimit(true, $fetchJoinCollection, $dql, "name"); - $this->iterateWithOrderDescWithLimit(true, $fetchJoinCollection, $dql, "name"); + $this->iterateWithOrderAscWithLimit(true, $fetchJoinCollection, $dql, 'name'); + $this->iterateWithOrderDescWithLimit(true, $fetchJoinCollection, $dql, 'name'); } /** * @dataProvider fetchJoinCollection */ - public function testIterateWithOutputWalkersWithRegularJoinWithComplexOrderByReferencingJoinedWithLimitAndOffset($fetchJoinCollection) + public function testIterateWithOutputWalkersWithRegularJoinWithComplexOrderByReferencingJoinedWithLimitAndOffset($fetchJoinCollection): void { // long function name is loooooooooooong $dql = 'SELECT c FROM Doctrine\Tests\Models\Pagination\Company c JOIN c.logo l ORDER BY l.image_height * l.image_width'; - $this->iterateWithOrderAscWithLimitAndOffset(true, $fetchJoinCollection, $dql, "name"); - $this->iterateWithOrderDescWithLimitAndOffset(true, $fetchJoinCollection, $dql, "name"); + $this->iterateWithOrderAscWithLimitAndOffset(true, $fetchJoinCollection, $dql, 'name'); + $this->iterateWithOrderDescWithLimitAndOffset(true, $fetchJoinCollection, $dql, 'name'); } /** * @dataProvider useOutputWalkers */ - public function testIterateWithFetchJoinWithOrderByColumnFromJoined($useOutputWalkers) + public function testIterateWithFetchJoinWithOrderByColumnFromJoined($useOutputWalkers): void { $dql = 'SELECT u,g,e FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.groups g JOIN u.email e ORDER BY e.email'; - $this->iterateWithOrderAsc($useOutputWalkers, true, $dql, "username"); - $this->iterateWithOrderDesc($useOutputWalkers, true, $dql, "username"); + $this->iterateWithOrderAsc($useOutputWalkers, true, $dql, 'username'); + $this->iterateWithOrderDesc($useOutputWalkers, true, $dql, 'username'); } /** * @dataProvider useOutputWalkers */ - public function testIterateWithFetchJoinWithOrderByColumnFromJoinedWithLimit($useOutputWalkers) + public function testIterateWithFetchJoinWithOrderByColumnFromJoinedWithLimit($useOutputWalkers): void { $dql = 'SELECT u,g,e FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.groups g JOIN u.email e ORDER BY e.email'; - $this->iterateWithOrderAscWithLimit($useOutputWalkers, true, $dql, "username"); - $this->iterateWithOrderDescWithLimit($useOutputWalkers, true, $dql, "username"); + $this->iterateWithOrderAscWithLimit($useOutputWalkers, true, $dql, 'username'); + $this->iterateWithOrderDescWithLimit($useOutputWalkers, true, $dql, 'username'); } /** * @dataProvider useOutputWalkers */ - public function testIterateWithFetchJoinWithOrderByColumnFromJoinedWithLimitAndOffset($useOutputWalkers) + public function testIterateWithFetchJoinWithOrderByColumnFromJoinedWithLimitAndOffset($useOutputWalkers): void { $dql = 'SELECT u,g,e FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.groups g JOIN u.email e ORDER BY e.email'; - $this->iterateWithOrderAscWithLimitAndOffset($useOutputWalkers, true, $dql, "username"); - $this->iterateWithOrderDescWithLimitAndOffset($useOutputWalkers, true, $dql, "username"); + $this->iterateWithOrderAscWithLimitAndOffset($useOutputWalkers, true, $dql, 'username'); + $this->iterateWithOrderDescWithLimitAndOffset($useOutputWalkers, true, $dql, 'username'); } /** * @dataProvider fetchJoinCollection */ - public function testIterateWithOutputWalkersWithFetchJoinWithComplexOrderByReferencingJoined($fetchJoinCollection) + public function testIterateWithOutputWalkersWithFetchJoinWithComplexOrderByReferencingJoined($fetchJoinCollection): void { $dql = 'SELECT c,l FROM Doctrine\Tests\Models\Pagination\Company c JOIN c.logo l ORDER BY l.image_width * l.image_height'; - $this->iterateWithOrderAsc(true, $fetchJoinCollection, $dql, "name"); - $this->iterateWithOrderDesc(true, $fetchJoinCollection, $dql, "name"); + $this->iterateWithOrderAsc(true, $fetchJoinCollection, $dql, 'name'); + $this->iterateWithOrderDesc(true, $fetchJoinCollection, $dql, 'name'); } /** * @dataProvider fetchJoinCollection */ - public function testIterateWithOutputWalkersWithFetchJoinWithComplexOrderByReferencingJoinedWithLimit($fetchJoinCollection) + public function testIterateWithOutputWalkersWithFetchJoinWithComplexOrderByReferencingJoinedWithLimit($fetchJoinCollection): void { $dql = 'SELECT c,l FROM Doctrine\Tests\Models\Pagination\Company c JOIN c.logo l ORDER BY l.image_width * l.image_height'; - $this->iterateWithOrderAscWithLimit(true, $fetchJoinCollection, $dql, "name"); - $this->iterateWithOrderDescWithLimit(true, $fetchJoinCollection, $dql, "name"); + $this->iterateWithOrderAscWithLimit(true, $fetchJoinCollection, $dql, 'name'); + $this->iterateWithOrderDescWithLimit(true, $fetchJoinCollection, $dql, 'name'); } /** * @dataProvider fetchJoinCollection */ - public function testIterateWithOutputWalkersWithFetchJoinWithComplexOrderByReferencingJoinedWithLimitAndOffset($fetchJoinCollection) + public function testIterateWithOutputWalkersWithFetchJoinWithComplexOrderByReferencingJoinedWithLimitAndOffset($fetchJoinCollection): void { $dql = 'SELECT c,l FROM Doctrine\Tests\Models\Pagination\Company c JOIN c.logo l ORDER BY l.image_width * l.image_height'; - $this->iterateWithOrderAscWithLimitAndOffset(true, $fetchJoinCollection, $dql, "name"); - $this->iterateWithOrderDescWithLimitAndOffset(true, $fetchJoinCollection, $dql, "name"); + $this->iterateWithOrderAscWithLimitAndOffset(true, $fetchJoinCollection, $dql, 'name'); + $this->iterateWithOrderDescWithLimitAndOffset(true, $fetchJoinCollection, $dql, 'name'); } /** * @dataProvider fetchJoinCollection */ - public function testIterateWithOutputWalkersWithFetchJoinWithComplexOrderByReferencingJoinedWithLimitAndOffsetWithInheritanceType($fetchJoinCollection) + public function testIterateWithOutputWalkersWithFetchJoinWithComplexOrderByReferencingJoinedWithLimitAndOffsetWithInheritanceType($fetchJoinCollection): void { $dql = 'SELECT u FROM Doctrine\Tests\Models\Pagination\User u ORDER BY u.id'; - $this->iterateWithOrderAscWithLimit(true, $fetchJoinCollection, $dql, "name"); - $this->iterateWithOrderDescWithLimit(true, $fetchJoinCollection, $dql, "name"); + $this->iterateWithOrderAscWithLimit(true, $fetchJoinCollection, $dql, 'name'); + $this->iterateWithOrderDescWithLimit(true, $fetchJoinCollection, $dql, 'name'); } - public function testIterateComplexWithOutputWalker() + public function testIterateComplexWithOutputWalker(): void { - $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'; + $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); $paginator = new Paginator($query); @@ -475,9 +480,9 @@ public function testIterateComplexWithOutputWalker() $this->assertCount(3, $paginator->getIterator()); } - public function testJoinedClassTableInheritance() + public function testJoinedClassTableInheritance(): void { - $dql = 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyManager c ORDER BY c.startDate'; + $dql = 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyManager c ORDER BY c.startDate'; $query = $this->_em->createQuery($dql); $paginator = new Paginator($query); @@ -487,97 +492,97 @@ public function testJoinedClassTableInheritance() /** * @dataProvider useOutputWalkers */ - public function testIterateWithFetchJoinOneToManyWithOrderByColumnFromBoth($useOutputWalkers) + public function testIterateWithFetchJoinOneToManyWithOrderByColumnFromBoth($useOutputWalkers): void { - $dql = 'SELECT c, d FROM Doctrine\Tests\Models\Pagination\Company c JOIN c.departments d ORDER BY c.name'; - $dqlAsc = $dql . " ASC, d.name"; - $dqlDesc = $dql . " DESC, d.name"; - $this->iterateWithOrderAsc($useOutputWalkers, true, $dqlAsc, "name"); - $this->iterateWithOrderDesc($useOutputWalkers, true, $dqlDesc, "name"); + $dql = 'SELECT c, d FROM Doctrine\Tests\Models\Pagination\Company c JOIN c.departments d ORDER BY c.name'; + $dqlAsc = $dql . ' ASC, d.name'; + $dqlDesc = $dql . ' DESC, d.name'; + $this->iterateWithOrderAsc($useOutputWalkers, true, $dqlAsc, 'name'); + $this->iterateWithOrderDesc($useOutputWalkers, true, $dqlDesc, 'name'); } - public function testIterateWithFetchJoinOneToManyWithOrderByColumnFromBothWithLimitWithOutputWalker() + public function testIterateWithFetchJoinOneToManyWithOrderByColumnFromBothWithLimitWithOutputWalker(): void { - $dql = 'SELECT c, d FROM Doctrine\Tests\Models\Pagination\Company c JOIN c.departments d ORDER BY c.name'; - $dqlAsc = $dql . " ASC, d.name"; - $dqlDesc = $dql . " DESC, d.name"; - $this->iterateWithOrderAscWithLimit(true, true, $dqlAsc, "name"); - $this->iterateWithOrderDescWithLimit(true, true, $dqlDesc, "name"); + $dql = 'SELECT c, d FROM Doctrine\Tests\Models\Pagination\Company c JOIN c.departments d ORDER BY c.name'; + $dqlAsc = $dql . ' ASC, d.name'; + $dqlDesc = $dql . ' DESC, d.name'; + $this->iterateWithOrderAscWithLimit(true, true, $dqlAsc, 'name'); + $this->iterateWithOrderDescWithLimit(true, true, $dqlDesc, 'name'); } - public function testIterateWithFetchJoinOneToManyWithOrderByColumnFromBothWithLimitWithoutOutputWalker() + public function testIterateWithFetchJoinOneToManyWithOrderByColumnFromBothWithLimitWithoutOutputWalker(): void { - $this->expectException(\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Cannot select distinct identifiers from query with LIMIT and ORDER BY on a column from a fetch joined to-many association. Use output walkers.'); - $dql = 'SELECT c, d FROM Doctrine\Tests\Models\Pagination\Company c JOIN c.departments d ORDER BY c.name'; - $dqlAsc = $dql . " ASC, d.name"; - $dqlDesc = $dql . " DESC, d.name"; - $this->iterateWithOrderAscWithLimit(false, true, $dqlAsc, "name"); - $this->iterateWithOrderDescWithLimit(false, true, $dqlDesc, "name"); + $dql = 'SELECT c, d FROM Doctrine\Tests\Models\Pagination\Company c JOIN c.departments d ORDER BY c.name'; + $dqlAsc = $dql . ' ASC, d.name'; + $dqlDesc = $dql . ' DESC, d.name'; + $this->iterateWithOrderAscWithLimit(false, true, $dqlAsc, 'name'); + $this->iterateWithOrderDescWithLimit(false, true, $dqlDesc, 'name'); } /** * @dataProvider useOutputWalkers */ - public function testIterateWithFetchJoinOneToManyWithOrderByColumnFromRoot($useOutputWalkers) + public function testIterateWithFetchJoinOneToManyWithOrderByColumnFromRoot($useOutputWalkers): void { $dql = 'SELECT c, d FROM Doctrine\Tests\Models\Pagination\Company c JOIN c.departments d ORDER BY c.name'; - $this->iterateWithOrderAsc($useOutputWalkers, true, $dql, "name"); - $this->iterateWithOrderDesc($useOutputWalkers, true, $dql, "name"); + $this->iterateWithOrderAsc($useOutputWalkers, true, $dql, 'name'); + $this->iterateWithOrderDesc($useOutputWalkers, true, $dql, 'name'); } /** * @dataProvider useOutputWalkers */ - public function testIterateWithFetchJoinOneToManyWithOrderByColumnFromRootWithLimit($useOutputWalkers) + public function testIterateWithFetchJoinOneToManyWithOrderByColumnFromRootWithLimit($useOutputWalkers): void { $dql = 'SELECT c, d FROM Doctrine\Tests\Models\Pagination\Company c JOIN c.departments d ORDER BY c.name'; - $this->iterateWithOrderAscWithLimit($useOutputWalkers, true, $dql, "name"); - $this->iterateWithOrderDescWithLimit($useOutputWalkers, true, $dql, "name"); + $this->iterateWithOrderAscWithLimit($useOutputWalkers, true, $dql, 'name'); + $this->iterateWithOrderDescWithLimit($useOutputWalkers, true, $dql, 'name'); } /** * @dataProvider useOutputWalkers */ - public function testIterateWithFetchJoinOneToManyWithOrderByColumnFromRootWithLimitAndOffset($useOutputWalkers) + public function testIterateWithFetchJoinOneToManyWithOrderByColumnFromRootWithLimitAndOffset($useOutputWalkers): void { $dql = 'SELECT c, d FROM Doctrine\Tests\Models\Pagination\Company c JOIN c.departments d ORDER BY c.name'; - $this->iterateWithOrderAscWithLimitAndOffset($useOutputWalkers, true, $dql, "name"); - $this->iterateWithOrderDescWithLimitAndOffset($useOutputWalkers, true, $dql, "name"); + $this->iterateWithOrderAscWithLimitAndOffset($useOutputWalkers, true, $dql, 'name'); + $this->iterateWithOrderDescWithLimitAndOffset($useOutputWalkers, true, $dql, 'name'); } /** * @dataProvider useOutputWalkers */ - public function testIterateWithFetchJoinOneToManyWithOrderByColumnFromJoined($useOutputWalkers) + public function testIterateWithFetchJoinOneToManyWithOrderByColumnFromJoined($useOutputWalkers): void { $dql = 'SELECT c, d FROM Doctrine\Tests\Models\Pagination\Company c JOIN c.departments d ORDER BY d.name'; - $this->iterateWithOrderAsc($useOutputWalkers, true, $dql, "name"); - $this->iterateWithOrderDesc($useOutputWalkers, true, $dql, "name"); + $this->iterateWithOrderAsc($useOutputWalkers, true, $dql, 'name'); + $this->iterateWithOrderDesc($useOutputWalkers, true, $dql, 'name'); } - public function testIterateWithFetchJoinOneToManyWithOrderByColumnFromJoinedWithLimitWithOutputWalker() + public function testIterateWithFetchJoinOneToManyWithOrderByColumnFromJoinedWithLimitWithOutputWalker(): void { $dql = 'SELECT c, d FROM Doctrine\Tests\Models\Pagination\Company c JOIN c.departments d ORDER BY d.name'; - $this->iterateWithOrderAscWithLimit(true, true, $dql, "name"); - $this->iterateWithOrderDescWithLimit(true, true, $dql, "name"); + $this->iterateWithOrderAscWithLimit(true, true, $dql, 'name'); + $this->iterateWithOrderDescWithLimit(true, true, $dql, 'name'); } - public function testIterateWithFetchJoinOneToManyWithOrderByColumnFromJoinedWithLimitWithoutOutputWalker() + public function testIterateWithFetchJoinOneToManyWithOrderByColumnFromJoinedWithLimitWithoutOutputWalker(): void { - $this->expectException(\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Cannot select distinct identifiers from query with LIMIT and ORDER BY on a column from a fetch joined to-many association. Use output walkers.'); $dql = 'SELECT c, d FROM Doctrine\Tests\Models\Pagination\Company c JOIN c.departments d ORDER BY d.name'; - $this->iterateWithOrderAscWithLimit(false, true, $dql, "name"); - $this->iterateWithOrderDescWithLimit(false, true, $dql, "name"); + $this->iterateWithOrderAscWithLimit(false, true, $dql, 'name'); + $this->iterateWithOrderDescWithLimit(false, true, $dql, 'name'); } - public function testCountWithCountSubqueryInWhereClauseWithOutputWalker() + public function testCountWithCountSubqueryInWhereClauseWithOutputWalker(): void { - $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"; + $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); $paginator = new Paginator($query, true); @@ -585,9 +590,9 @@ public function testCountWithCountSubqueryInWhereClauseWithOutputWalker() $this->assertCount(9, $paginator); } - public function testIterateWithCountSubqueryInWhereClause() + public function testIterateWithCountSubqueryInWhereClause(): void { - $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"; + $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); $paginator = new Paginator($query, true); @@ -596,14 +601,14 @@ public function testIterateWithCountSubqueryInWhereClause() $users = iterator_to_array($paginator->getIterator()); $this->assertCount(9, $users); foreach ($users as $i => $user) { - $this->assertEquals("username" . (8 - $i), $user->username); + $this->assertEquals('username' . (8 - $i), $user->username); } } - public function testDetectOutputWalker() + public function testDetectOutputWalker(): void { // 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'; + $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); // If the Paginator detects the custom output walker it should fall back to using the @@ -611,7 +616,7 @@ public function testDetectOutputWalker() $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, Query\SqlWalker::class); $paginator = new Paginator($query); - $this->expectException(\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Cannot count query that uses a HAVING clause. Use the output walkers for pagination'); count($paginator); @@ -620,9 +625,9 @@ public function testDetectOutputWalker() /** * Test using a paginator when the entity attribute name and corresponding column name are not the same. */ - public function testPaginationWithColumnAttributeNameDifference() + public function testPaginationWithColumnAttributeNameDifference(): void { - $dql = 'SELECT c FROM Doctrine\Tests\Models\Pagination\Company c ORDER BY c.id'; + $dql = 'SELECT c FROM Doctrine\Tests\Models\Pagination\Company c ORDER BY c.id'; $query = $this->_em->createQuery($dql); $paginator = new Paginator($query); @@ -631,9 +636,9 @@ public function testPaginationWithColumnAttributeNameDifference() $this->assertCount(9, $paginator->getIterator()); } - public function testCloneQuery() + public function testCloneQuery(): void { - $dql = 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u'; + $dql = 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u'; $query = $this->_em->createQuery($dql); $paginator = new Paginator($query); @@ -642,9 +647,9 @@ public function testCloneQuery() $this->assertTrue($query->getParameters()->isEmpty()); } - public function testQueryWalkerIsKept() + public function testQueryWalkerIsKept(): void { - $dql = 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u'; + $dql = 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u'; $query = $this->_em->createQuery($dql); $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [CustomPaginationTestTreeWalker::class]); @@ -657,7 +662,7 @@ public function testQueryWalkerIsKept() /** * @group GH-7890 */ - public function testCustomIdTypeWithoutOutputWalker() + public function testCustomIdTypeWithoutOutputWalker(): void { $this->_em->persist(new CustomIdObjectTypeParent(new CustomIdObject('foo'))); $this->_em->flush(); @@ -675,7 +680,7 @@ public function testCustomIdTypeWithoutOutputWalker() self::assertSame('foo', (string) $matchedItems[0]->id); } - public function testCountQueryStripsParametersInSelect() + public function testCountQueryStripsParametersInSelect(): void { $query = $this->_em->createQuery( 'SELECT u, (CASE WHEN u.id < :vipMaxId THEN 1 ELSE 0 END) AS hidden promotedFirst @@ -708,7 +713,7 @@ public function testCountQueryStripsParametersInSelect() /** * @dataProvider useOutputWalkersAndFetchJoinCollection */ - public function testPaginationWithSubSelectOrderByExpression($useOutputWalker, $fetchJoinCollection) + public function testPaginationWithSubSelectOrderByExpression($useOutputWalker, $fetchJoinCollection): void { $query = $this->_em->createQuery( <<<'SQL' @@ -729,32 +734,33 @@ public function testPaginationWithSubSelectOrderByExpression($useOutputWalker, $ $this->assertCount(9, $paginator->getIterator()); } - public function populate() + public function populate(): void { $groups = []; - for ($j = 0; $j < 3; $j++) {; - $group = new CmsGroup(); + for ($j = 0; $j < 3; $j++) { + $group = new CmsGroup(); $group->name = "group$j"; - $groups[] = $group; + $groups[] = $group; $this->_em->persist($group); } for ($i = 0; $i < 9; $i++) { - $user = new CmsUser(); - $user->name = "Name$i"; - $user->username = "username$i"; - $user->status = "active"; - $user->email = new CmsEmail(); - $user->email->user = $user; + $user = new CmsUser(); + $user->name = "Name$i"; + $user->username = "username$i"; + $user->status = 'active'; + $user->email = new CmsEmail(); + $user->email->user = $user; $user->email->email = "email$i"; for ($j = 0; $j < 3; $j++) { $user->addGroup($groups[$j]); } + $this->_em->persist($user); for ($j = 0; $j < $i + 1; $j++) { - $article = new CmsArticle(); + $article = new CmsArticle(); $article->topic = "topic$i$j"; - $article->text = "text$i$j"; + $article->text = "text$i$j"; $article->setAuthor($user); $article->version = 0; $this->_em->persist($article); @@ -762,25 +768,26 @@ public function populate() } for ($i = 0; $i < 9; $i++) { - $company = new Company(); - $company->name = "name$i"; - $company->logo = new Logo(); - $company->logo->image = "image$i"; - $company->logo->image_width = 100 + $i; + $company = new Company(); + $company->name = "name$i"; + $company->logo = new Logo(); + $company->logo->image = "image$i"; + $company->logo->image_width = 100 + $i; $company->logo->image_height = 100 + $i; - $company->logo->company = $company; - for($j=0;$j<3;$j++) { - $department = new Department(); - $department->name = "name$i$j"; - $department->company = $company; + $company->logo->company = $company; + for ($j = 0; $j < 3; $j++) { + $department = new Department(); + $department->name = "name$i$j"; + $department->company = $company; $company->departments[] = $department; } + $this->_em->persist($company); } for ($i = 0; $i < 9; $i++) { - $user = new User1(); - $user->name = "name$i"; + $user = new User1(); + $user->name = "name$i"; $user->email = "email$i"; $this->_em->persist($user); } @@ -825,11 +832,11 @@ public function useOutputWalkersAndFetchJoinCollection() class CustomPaginationTestTreeWalker extends Query\TreeWalkerAdapter { - public function walkSelectStatement(Query\AST\SelectStatement $selectStatement) + public function walkSelectStatement(Query\AST\SelectStatement $selectStatement): void { $condition = new Query\AST\ConditionalPrimary(); - $path = new Query\AST\PathExpression(Query\AST\PathExpression::TYPE_STATE_FIELD, 'u', 'name'); + $path = new Query\AST\PathExpression(Query\AST\PathExpression::TYPE_STATE_FIELD, 'u', 'name'); $path->type = Query\AST\PathExpression::TYPE_STATE_FIELD; $condition->simpleConditionalExpression = new Query\AST\ComparisonExpression( diff --git a/tests/Doctrine/Tests/ORM/Functional/PersistentCollectionCriteriaTest.php b/tests/Doctrine/Tests/ORM/Functional/PersistentCollectionCriteriaTest.php index aea051e2c92..5e360d85db1 100644 --- a/tests/Doctrine/Tests/ORM/Functional/PersistentCollectionCriteriaTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/PersistentCollectionCriteriaTest.php @@ -1,5 +1,7 @@ - */ class PersistentCollectionCriteriaTest extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { $this->useModelSet('tweet'); $this->useModelSet('quote'); parent::setUp(); } - public function tearDown() : void + public function tearDown(): void { if ($this->_em) { $this->_em->getConfiguration()->setEntityNamespaces([]); } + parent::tearDown(); } - public function loadTweetFixture() + public function loadTweetFixture(): void { - $author = new TweetUser(); + $author = new TweetUser(); $author->name = 'ngal'; $this->_em->persist($author); - $tweet1 = new Tweet(); + $tweet1 = new Tweet(); $tweet1->content = 'Foo'; $author->addTweet($tweet1); - $tweet2 = new Tweet(); + $tweet2 = new Tweet(); $tweet2->content = 'Bar'; $author->addTweet($tweet2); @@ -54,9 +54,9 @@ public function loadTweetFixture() $this->_em->clear(); } - public function loadQuoteFixture() + public function loadQuoteFixture(): void { - $user = new QuoteUser(); + $user = new QuoteUser(); $user->name = 'mgal'; $this->_em->persist($user); @@ -71,7 +71,7 @@ public function loadQuoteFixture() $this->_em->clear(); } - public function testCanCountWithoutLoadingPersistentCollection() + public function testCanCountWithoutLoadingPersistentCollection(): void { $this->loadTweetFixture(); diff --git a/tests/Doctrine/Tests/ORM/Functional/PersistentCollectionTest.php b/tests/Doctrine/Tests/ORM/Functional/PersistentCollectionTest.php index 1c9601e8b69..d264b49a74a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/PersistentCollectionTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/PersistentCollectionTest.php @@ -1,34 +1,38 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(PersistentCollectionHolder::class), - $this->_em->getClassMetadata(PersistentCollectionContent::class), + $this->_em->getClassMetadata(PersistentCollectionHolder::class), + $this->_em->getClassMetadata(PersistentCollectionContent::class), ] ); - } catch (\Exception $e) { - + } catch (Exception $e) { } + PersistentObject::setObjectManager($this->_em); } - public function testPersist() + public function testPersist(): void { $collectionHolder = new PersistentCollectionHolder(); - $content = new PersistentCollectionContent('first element'); + $content = new PersistentCollectionContent('first element'); $collectionHolder->addElement($content); $this->_em->persist($collectionHolder); @@ -47,7 +51,7 @@ public function testPersist() /** * Tests that PersistentCollection::isEmpty() does not initialize the collection when FETCH_EXTRA_LAZY is used. */ - public function testExtraLazyIsEmptyDoesNotInitializeCollection() + public function testExtraLazyIsEmptyDoesNotInitializeCollection(): void { $collectionHolder = new PersistentCollectionHolder(); @@ -56,7 +60,7 @@ public function testExtraLazyIsEmptyDoesNotInitializeCollection() $this->_em->clear(); $collectionHolder = $this->_em->find(PersistentCollectionHolder::class, $collectionHolder->getId()); - $collection = $collectionHolder->getRawCollection(); + $collection = $collectionHolder->getRawCollection(); $this->assertTrue($collection->isEmpty()); $this->assertFalse($collection->isInitialized()); @@ -67,7 +71,7 @@ public function testExtraLazyIsEmptyDoesNotInitializeCollection() $this->_em->clear(); $collectionHolder = $this->_em->find(PersistentCollectionHolder::class, $collectionHolder->getId()); - $collection = $collectionHolder->getRawCollection(); + $collection = $collectionHolder->getRawCollection(); $this->assertFalse($collection->isEmpty()); $this->assertFalse($collection->isInitialized()); @@ -77,7 +81,7 @@ public function testExtraLazyIsEmptyDoesNotInitializeCollection() * @group #1206 * @group DDC-3430 */ - public function testMatchingDoesNotModifyTheGivenCriteria() + public function testMatchingDoesNotModifyTheGivenCriteria(): void { $collectionHolder = new PersistentCollectionHolder(); @@ -109,7 +113,7 @@ class PersistentCollectionHolder extends PersistentObject protected $id; /** - * @var \Doctrine\Common\Collections\Collection + * @var Collection * @ManyToMany(targetEntity="PersistentCollectionContent", cascade={"all"}, fetch="EXTRA_LAZY") */ protected $collection; @@ -119,26 +123,23 @@ public function __construct() $this->collection = new ArrayCollection(); } - /** - * @param PersistentCollectionContent $element - */ - public function addElement(PersistentCollectionContent $element) + public function addElement(PersistentCollectionContent $element): void { $this->collection->add($element); } /** - * @return \Doctrine\Common\Collections\Collection + * @return Collection */ - public function getCollection() + public function getCollection(): Collection { return clone $this->collection; } /** - * @return \Doctrine\Common\Collections\Collection + * @return Collection */ - public function getRawCollection() + public function getRawCollection(): Collection { return $this->collection; } diff --git a/tests/Doctrine/Tests/ORM/Functional/PersistentObjectTest.php b/tests/Doctrine/Tests/ORM/Functional/PersistentObjectTest.php index cfbeb5041f8..ec922d357c4 100644 --- a/tests/Doctrine/Tests/ORM/Functional/PersistentObjectTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/PersistentObjectTest.php @@ -1,9 +1,12 @@ _em->getClassMetadata(PersistentEntity::class), ] ); - } catch (\Exception $e) { + } catch (Exception $e) { } PersistentObject::setObjectManager($this->_em); } - public function testPersist() + public function testPersist(): void { $entity = new PersistentEntity(); - $entity->setName("test"); + $entity->setName('test'); $this->_em->persist($entity); $this->_em->flush(); @@ -40,10 +43,10 @@ public function testPersist() $this->addToAssertionCount(1); } - public function testFind() + public function testFind(): void { $entity = new PersistentEntity(); - $entity->setName("test"); + $entity->setName('test'); $this->_em->persist($entity); $this->_em->flush(); @@ -57,10 +60,10 @@ public function testFind() $this->_em->flush(); } - public function testGetReference() + public function testGetReference(): void { $entity = new PersistentEntity(); - $entity->setName("test"); + $entity->setName('test'); $this->_em->persist($entity); $this->_em->flush(); @@ -71,10 +74,10 @@ public function testGetReference() $this->assertEquals('test', $entity->getName()); } - public function testSetAssociation() + public function testSetAssociation(): void { $entity = new PersistentEntity(); - $entity->setName("test"); + $entity->setName('test'); $entity->setParent($entity); $this->_em->persist($entity); diff --git a/tests/Doctrine/Tests/ORM/Functional/PostFlushEventTest.php b/tests/Doctrine/Tests/ORM/Functional/PostFlushEventTest.php index c2506bafbe4..3bf1a13c526 100644 --- a/tests/Doctrine/Tests/ORM/Functional/PostFlushEventTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/PostFlushEventTest.php @@ -1,50 +1,49 @@ */ class PostFlushEventTest extends OrmFunctionalTestCase { - /** - * @var PostFlushListener - */ + /** @var PostFlushListener */ private $listener; - protected function setUp() : void + protected function setUp(): void { $this->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() + public function testListenerShouldBeNotified(): void { $this->_em->persist($this->createNewValidUser()); $this->_em->flush(); $this->assertTrue($this->listener->wasNotified); } - public function testListenerShouldNotBeNotifiedWhenFlushThrowsException() + public function testListenerShouldNotBeNotifiedWhenFlushThrowsException(): void { - $user = new CmsUser(); + $user = new CmsUser(); $user->username = 'dfreudenberger'; $this->_em->persist($user); $exceptionRaised = false; try { $this->_em->flush(); - } catch (\Exception $ex) { + } catch (Exception $ex) { $exceptionRaised = true; } @@ -52,7 +51,7 @@ public function testListenerShouldNotBeNotifiedWhenFlushThrowsException() $this->assertFalse($this->listener->wasNotified); } - public function testListenerShouldReceiveEntityManagerThroughArgs() + public function testListenerShouldReceiveEntityManagerThroughArgs(): void { $this->_em->persist($this->createNewValidUser()); $this->_em->flush(); @@ -60,36 +59,27 @@ public function testListenerShouldReceiveEntityManagerThroughArgs() $this->assertSame($this->_em, $receivedEm); } - /** - * @return CmsUser - */ - private function createNewValidUser() + private function createNewValidUser(): CmsUser { - $user = new CmsUser(); + $user = new CmsUser(); $user->username = 'dfreudenberger'; - $user->name = 'Daniel Freudenberger'; + $user->name = 'Daniel Freudenberger'; + return $user; } } class PostFlushListener { - /** - * @var bool - */ + /** @var bool */ public $wasNotified = false; - /** - * @var PostFlushEventArgs - */ + /** @var PostFlushEventArgs */ public $receivedArgs; - /** - * @param PostFlushEventArgs $args - */ - public function postFlush(PostFlushEventArgs $args) + public function postFlush(PostFlushEventArgs $args): void { - $this->wasNotified = true; + $this->wasNotified = true; $this->receivedArgs = $args; } } diff --git a/tests/Doctrine/Tests/ORM/Functional/PostLoadEventTest.php b/tests/Doctrine/Tests/ORM/Functional/PostLoadEventTest.php index cfd7db235ef..e05ea93b710 100644 --- a/tests/Doctrine/Tests/ORM/Functional/PostLoadEventTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/PostLoadEventTest.php @@ -1,4 +1,7 @@ */ class PostLoadEventTest extends OrmFunctionalTestCase { - /** - * @var integer - */ + /** @var int */ private $userId; - /** - * {@inheritdoc} - */ - protected function setUp() : void + protected function setUp(): void { $this->useModelSet('cms'); @@ -34,7 +31,7 @@ protected function setUp() : void $this->loadFixture(); } - public function testLoadedEntityUsingFindShouldTriggerEvent() + public function testLoadedEntityUsingFindShouldTriggerEvent(): void { $mockListener = $this->createMock(PostLoadListener::class); @@ -51,7 +48,7 @@ public function testLoadedEntityUsingFindShouldTriggerEvent() $this->_em->find(CmsUser::class, $this->userId); } - public function testLoadedEntityUsingQueryShouldTriggerEvent() + public function testLoadedEntityUsingQueryShouldTriggerEvent(): void { $mockListener = $this->createMock(PostLoadListener::class); @@ -71,7 +68,7 @@ public function testLoadedEntityUsingQueryShouldTriggerEvent() $query->getResult(); } - public function testLoadedAssociationToOneShouldTriggerEvent() + public function testLoadedAssociationToOneShouldTriggerEvent(): void { $mockListener = $this->createMock(PostLoadListener::class); @@ -91,7 +88,7 @@ public function testLoadedAssociationToOneShouldTriggerEvent() $query->getResult(); } - public function testLoadedAssociationToManyShouldTriggerEvent() + public function testLoadedAssociationToManyShouldTriggerEvent(): void { $mockListener = $this->createMock(PostLoadListener::class); @@ -111,7 +108,7 @@ public function testLoadedAssociationToManyShouldTriggerEvent() $query->getResult(); } - public function testLoadedProxyEntityShouldTriggerEvent() + public function testLoadedProxyEntityShouldTriggerEvent(): void { $eventManager = $this->_em->getEventManager(); @@ -142,7 +139,7 @@ public function testLoadedProxyEntityShouldTriggerEvent() $userProxy->getName(); } - public function testLoadedProxyPartialShouldTriggerEvent() + public function testLoadedProxyPartialShouldTriggerEvent(): void { $eventManager = $this->_em->getEventManager(); @@ -163,7 +160,7 @@ public function testLoadedProxyPartialShouldTriggerEvent() $query->getResult(); } - public function testLoadedProxyAssociationToOneShouldTriggerEvent() + public function testLoadedProxyAssociationToOneShouldTriggerEvent(): void { $user = $this->_em->find(CmsUser::class, $this->userId); @@ -184,7 +181,7 @@ public function testLoadedProxyAssociationToOneShouldTriggerEvent() $emailProxy->getEmail(); } - public function testLoadedProxyAssociationToManyShouldTriggerEvent() + public function testLoadedProxyAssociationToManyShouldTriggerEvent(): void { $user = $this->_em->find(CmsUser::class, $this->userId); @@ -208,7 +205,7 @@ public function testLoadedProxyAssociationToManyShouldTriggerEvent() /** * @group DDC-3005 */ - public function testAssociationsArePopulatedWhenEventIsFired() + public function testAssociationsArePopulatedWhenEventIsFired(): void { $checkerListener = new PostLoadListenerCheckAssociationsArePopulated(); $this->_em->getEventManager()->addEventListener([Events::postLoad], $checkerListener); @@ -225,10 +222,10 @@ public function testAssociationsArePopulatedWhenEventIsFired() /** * @group DDC-3005 */ - public function testEventRaisedCorrectTimesWhenOtherEntityLoadedInEventHandler() + public function testEventRaisedCorrectTimesWhenOtherEntityLoadedInEventHandler(): void { $eventManager = $this->_em->getEventManager(); - $listener = new PostLoadListenerLoadEntityInEventHandler(); + $listener = new PostLoadListenerLoadEntityInEventHandler(); $eventManager->addEventListener([Events::postLoad], $listener); $this->_em->find(CmsUser::class, $this->userId); @@ -236,30 +233,30 @@ public function testEventRaisedCorrectTimesWhenOtherEntityLoadedInEventHandler() $this->assertSame(1, $listener->countHandledEvents(CmsEmail::class), CmsEmail::class . ' should be handled once!'); } - private function loadFixture() + private function loadFixture(): void { - $user = new CmsUser; - $user->name = 'Roman'; + $user = new CmsUser(); + $user->name = 'Roman'; $user->username = 'romanb'; - $user->status = 'developer'; + $user->status = 'developer'; - $address = new CmsAddress; + $address = new CmsAddress(); $address->country = 'Germany'; - $address->city = 'Berlin'; - $address->zip = '12345'; + $address->city = 'Berlin'; + $address->zip = '12345'; $user->setAddress($address); - $email = new CmsEmail; + $email = new CmsEmail(); $email->setEmail('roman@domain.com'); $user->setEmail($email); - $ph1 = new CmsPhonenumber; - $ph1->phonenumber = "0301234"; + $ph1 = new CmsPhonenumber(); + $ph1->phonenumber = '0301234'; - $ph2 = new CmsPhonenumber; - $ph2->phonenumber = "987654321"; + $ph2 = new CmsPhonenumber(); + $ph2->phonenumber = '987654321'; $user->addPhonenumber($ph1); $user->addPhonenumber($ph2); @@ -275,7 +272,7 @@ private function loadFixture() class PostLoadListener { - public function postLoad(LifecycleEventArgs $event) + public function postLoad(LifecycleEventArgs $event): void { // Expected to be mocked out echo 'Should never be called!'; @@ -288,15 +285,16 @@ class PostLoadListenerCheckAssociationsArePopulated public $populated = false; - public function postLoad(LifecycleEventArgs $event) + public function postLoad(LifecycleEventArgs $event): void { $object = $event->getObject(); if ($object instanceof CmsUser) { if ($this->checked) { - throw new \RuntimeException('Expected to be one user!'); + throw new RuntimeException('Expected to be one user!'); } - $this->checked = true; - $this->populated = null !== $object->getEmail(); + + $this->checked = true; + $this->populated = $object->getEmail() !== null; } } } @@ -305,15 +303,16 @@ class PostLoadListenerLoadEntityInEventHandler { private $firedByClasses = []; - public function postLoad(LifecycleEventArgs $event) + public function postLoad(LifecycleEventArgs $event): void { $object = $event->getObject(); - $class = ClassUtils::getClass($object); - if (!isset($this->firedByClasses[$class])) { + $class = ClassUtils::getClass($object); + if (! isset($this->firedByClasses[$class])) { $this->firedByClasses[$class] = 1; } else { $this->firedByClasses[$class]++; } + if ($object instanceof CmsUser) { $object->getEmail()->getEmail(); } @@ -321,6 +320,6 @@ public function postLoad(LifecycleEventArgs $event) public function countHandledEvents($className) { - return isset($this->firedByClasses[$className]) ? $this->firedByClasses[$className] : 0; + return $this->firedByClasses[$className] ?? 0; } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ProxiesLikeEntitiesTest.php b/tests/Doctrine/Tests/ORM/Functional/ProxiesLikeEntitiesTest.php index ca29a0495cf..1178523cead 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ProxiesLikeEntitiesTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ProxiesLikeEntitiesTest.php @@ -1,5 +1,7 @@ _em->getClassMetadata(CmsGroup::class), ] ); - } catch (\Exception $e) { + } catch (Exception $e) { } - $this->user = new CmsUser(); + + $this->user = new CmsUser(); $this->user->username = 'ocramius'; - $this->user->name = 'Marco'; + $this->user->name = 'Marco'; $this->_em->persist($this->user); $this->_em->flush(); $this->_em->clear(); @@ -55,14 +60,14 @@ protected function setUp() : void /** * Verifies that a proxy can be successfully persisted and updated */ - public function testPersistUpdate() + public function testPersistUpdate(): void { // Considering case (a) - $proxy = $this->_em->getProxyFactory()->getProxy(CmsUser::class, ['id' => 123]); + $proxy = $this->_em->getProxyFactory()->getProxy(CmsUser::class, ['id' => 123]); $proxy->__isInitialized__ = true; - $proxy->id = null; - $proxy->username = 'ocra'; - $proxy->name = 'Marco'; + $proxy->id = null; + $proxy->username = 'ocra'; + $proxy->name = 'Marco'; $this->_em->persist($proxy); $this->_em->flush(); $this->assertNotNull($proxy->getId()); @@ -75,11 +80,11 @@ public function testPersistUpdate() $this->_em->flush(); } - public function testEntityWithIdentifier() + public function testEntityWithIdentifier(): void { - $userId = $this->user->getId(); - /* @var $uninitializedProxy CmsUserProxy */ + $userId = $this->user->getId(); $uninitializedProxy = $this->_em->getReference(CmsUser::class, $userId); + assert($uninitializedProxy instanceof CmsUserProxy); $this->assertInstanceOf(CmsUserProxy::class, $uninitializedProxy); $this->_em->persist($uninitializedProxy); @@ -93,12 +98,11 @@ public function testEntityWithIdentifier() /** * Verifying that proxies can be used without problems as query parameters */ - public function testProxyAsDqlParameterPersist() + public function testProxyAsDqlParameterPersist(): void { - $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 + $result = $this ->_em ->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u = ?1') ->setParameter(1, $proxy) @@ -111,7 +115,7 @@ public function testProxyAsDqlParameterPersist() /** * Verifying that proxies can be used without problems as query parameters */ - public function testFindWithProxyName() + public function testFindWithProxyName(): void { $result = $this->_em->find(CmsUserProxy::class, $this->user->getId()); $this->assertSame($this->user->getId(), $result->getId()); @@ -134,7 +138,7 @@ public function testFindWithProxyName() $this->_em->clear(); } - protected function tearDown() : void + protected function tearDown(): void { $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 2124f9846e0..d2ae7f65043 100644 --- a/tests/Doctrine/Tests/ORM/Functional/QueryCacheTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/QueryCacheTest.php @@ -1,5 +1,7 @@ cacheDataReflection = new \ReflectionProperty(ArrayCache::class, "data"); + $this->cacheDataReflection = new ReflectionProperty(ArrayCache::class, 'data'); $this->cacheDataReflection->setAccessible(true); $this->useModelSet('cms'); @@ -31,16 +32,11 @@ protected function setUp() : void parent::setUp(); } - /** - * @param ArrayCache $cache - * @return integer - */ - private function getCacheSize(ArrayCache $cache) + private function getCacheSize(ArrayCache $cache): int { return sizeof($this->cacheDataReflection->getValue($cache)); } - public function testQueryCache_DependsOnHints() { $query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); @@ -61,11 +57,12 @@ public function testQueryCache_DependsOnHints() /** * @param $query + * * @depends testQueryCache_DependsOnHints */ - public function testQueryCache_DependsOnFirstResult($query) + public function testQueryCache_DependsOnFirstResult($query): void { - $cache = $query->getQueryCacheDriver(); + $cache = $query->getQueryCacheDriver(); $cacheCount = $this->getCacheSize($cache); $query->setFirstResult(10); @@ -77,11 +74,12 @@ public function testQueryCache_DependsOnFirstResult($query) /** * @param $query + * * @depends testQueryCache_DependsOnHints */ - public function testQueryCache_DependsOnMaxResults($query) + public function testQueryCache_DependsOnMaxResults($query): void { - $cache = $query->getQueryCacheDriver(); + $cache = $query->getQueryCacheDriver(); $cacheCount = $this->getCacheSize($cache); $query->setMaxResults(10); @@ -92,18 +90,19 @@ public function testQueryCache_DependsOnMaxResults($query) /** * @param $query + * * @depends testQueryCache_DependsOnHints */ - public function testQueryCache_DependsOnHydrationMode($query) + public function testQueryCache_DependsOnHydrationMode($query): void { - $cache = $query->getQueryCacheDriver(); + $cache = $query->getQueryCacheDriver(); $cacheCount = $this->getCacheSize($cache); $query->getArrayResult(); $this->assertEquals($cacheCount + 1, $this->getCacheSize($cache)); } - public function testQueryCache_NoHitSaveParserResult() + public function testQueryCache_NoHitSaveParserResult(): void { $this->_em->getConfiguration()->setQueryCacheImpl(new ArrayCache()); @@ -121,7 +120,7 @@ public function testQueryCache_NoHitSaveParserResult() $query->getResult(); } - public function testQueryCache_HitDoesNotSaveParserResult() + public function testQueryCache_HitDoesNotSaveParserResult(): void { $this->_em->getConfiguration()->setQueryCacheImpl(new ArrayCache()); @@ -133,7 +132,7 @@ public function testQueryCache_HitDoesNotSaveParserResult() $sqlExecMock->expects($this->once()) ->method('execute') - ->will($this->returnValue( 10 )); + ->will($this->returnValue(10)); $parserResultMock = $this->getMockBuilder(ParserResult::class) ->setMethods(['getSqlExecutor']) @@ -160,4 +159,3 @@ public function testQueryCache_HitDoesNotSaveParserResult() $users = $query->getResult(); } } - diff --git a/tests/Doctrine/Tests/ORM/Functional/QueryDqlFunctionTest.php b/tests/Doctrine/Tests/ORM/Functional/QueryDqlFunctionTest.php index 3bb3d3378d0..1cbf7d46e4b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/QueryDqlFunctionTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/QueryDqlFunctionTest.php @@ -1,20 +1,24 @@ useModelSet('company'); parent::setUp(); @@ -22,7 +26,7 @@ protected function setUp() : void $this->generateFixture(); } - public function testAggregateSum() + public function testAggregateSum(): void { $salarySum = $this->_em->createQuery('SELECT SUM(m.salary) AS salary FROM Doctrine\Tests\Models\Company\CompanyManager m') ->getSingleResult(); @@ -30,7 +34,7 @@ public function testAggregateSum() $this->assertEquals(1500000, $salarySum['salary']); } - public function testAggregateAvg() + public function testAggregateAvg(): void { $salaryAvg = $this->_em->createQuery('SELECT AVG(m.salary) AS salary FROM Doctrine\Tests\Models\Company\CompanyManager m') ->getSingleResult(); @@ -38,7 +42,7 @@ public function testAggregateAvg() $this->assertEquals(375000, round($salaryAvg['salary'], 0)); } - public function testAggregateMin() + public function testAggregateMin(): void { $salary = $this->_em->createQuery('SELECT MIN(m.salary) AS salary FROM Doctrine\Tests\Models\Company\CompanyManager m') ->getSingleResult(); @@ -46,7 +50,7 @@ public function testAggregateMin() $this->assertEquals(100000, $salary['salary']); } - public function testAggregateMax() + public function testAggregateMax(): void { $salary = $this->_em->createQuery('SELECT MAX(m.salary) AS salary FROM Doctrine\Tests\Models\Company\CompanyManager m') ->getSingleResult(); @@ -54,7 +58,7 @@ public function testAggregateMax() $this->assertEquals(800000, $salary['salary']); } - public function testAggregateCount() + public function testAggregateCount(): void { $managerCount = $this->_em->createQuery('SELECT COUNT(m.id) AS managers FROM Doctrine\Tests\Models\Company\CompanyManager m') ->getSingleResult(); @@ -62,7 +66,7 @@ public function testAggregateCount() $this->assertEquals(4, $managerCount['managers']); } - public function testFunctionAbs() + public function testFunctionAbs(): void { $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(); @@ -74,7 +78,7 @@ public function testFunctionAbs() $this->assertEquals(800000, $result[3]['abs']); } - public function testFunctionConcat() + public function testFunctionConcat(): void { $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(); @@ -86,7 +90,7 @@ public function testFunctionConcat() $this->assertEquals('Jonathan W.Administration', $arg[3]['namedep']); } - public function testFunctionLength() + public function testFunctionLength(): void { $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(); @@ -98,10 +102,10 @@ public function testFunctionLength() $this->assertEquals(25, $result[3]['namedeplength']); } - public function testFunctionLocate() + public function testFunctionLocate(): void { - $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"; + $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) ->getArrayResult(); @@ -117,9 +121,9 @@ public function testFunctionLocate() $this->assertEquals(0, $result[3]['loc2']); } - public function testFunctionLower() + public function testFunctionLower(): void { - $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)); @@ -129,9 +133,9 @@ public function testFunctionLower() $this->assertEquals('jonathan w.', $result[3]['lowername']); } - public function testFunctionMod() + public function testFunctionMod(): void { - $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)); @@ -141,21 +145,21 @@ public function testFunctionMod() $this->assertEquals(2000, $result[3]['amod']); } - public function testFunctionSqrt() + public function testFunctionSqrt(): void { - $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(447, round($result[1]['sqrtsalary'])); $this->assertEquals(632, round($result[2]['sqrtsalary'])); $this->assertEquals(894, round($result[3]['sqrtsalary'])); } - public function testFunctionUpper() + public function testFunctionUpper(): void { - $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)); @@ -165,10 +169,10 @@ public function testFunctionUpper() $this->assertEquals('JONATHAN W.', $result[3]['uppername']); } - public function testFunctionSubstring() + public function testFunctionSubstring(): void { - $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"; + $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) ->getArrayResult(); @@ -185,11 +189,11 @@ public function testFunctionSubstring() $this->assertEquals('n B.', $result[3]['str2']); } - public function testFunctionTrim() + public function testFunctionTrim(): void { - $dql = "SELECT m, TRIM(TRAILING '.' FROM m.name) AS str1, ". - " 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"; + $dql = "SELECT m, TRIM(TRAILING '.' FROM m.name) AS str1, " . + " 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(); @@ -208,7 +212,7 @@ public function testFunctionTrim() $this->assertEquals('Jonathan W.', $result[3]['str3']); } - public function testOperatorAdd() + public function testOperatorAdd(): void { $result = $this->_em->createQuery('SELECT m, m.salary+2500 AS add FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC') ->getResult(); @@ -220,7 +224,7 @@ public function testOperatorAdd() $this->assertEquals(802500, $result[3]['add']); } - public function testOperatorSub() + public function testOperatorSub(): void { $result = $this->_em->createQuery('SELECT m, m.salary-2500 AS sub FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC') ->getResult(); @@ -232,7 +236,7 @@ public function testOperatorSub() $this->assertEquals(797500, $result[3]['sub']); } - public function testOperatorMultiply() + public function testOperatorMultiply(): void { $result = $this->_em->createQuery('SELECT m, m.salary*2 AS op FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC') ->getResult(); @@ -247,7 +251,7 @@ public function testOperatorMultiply() /** * @group test */ - public function testOperatorDiv() + public function testOperatorDiv(): void { $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(); @@ -259,7 +263,7 @@ public function testOperatorDiv() $this->assertEquals(1600000, $result[3]['op']); } - public function testConcatFunction() + public function testConcatFunction(): void { $arg = $this->_em->createQuery('SELECT CONCAT(m.name, m.department) AS namedep FROM Doctrine\Tests\Models\Company\CompanyManager m order by namedep desc') ->getArrayResult(); @@ -274,15 +278,15 @@ public function testConcatFunction() /** * @group DDC-1014 */ - public function testDateDiff() + public function testDateDiff(): void { $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(); + $arg = $query->getArrayResult(); $this->assertEqualsWithDelta(-10, $arg[0]['diff'], 1, 'Should be roughly -10 (or -9)'); $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(); + $arg = $query->getArrayResult(); $this->assertEqualsWithDelta(10, $arg[0]['diff'], 1, 'Should be roughly 10 (or 9)'); } @@ -290,10 +294,9 @@ public function testDateDiff() /** * @group DDC-1014 * @group DDC-2938 - * * @dataProvider dateAddSubProvider */ - public function testDateAdd(string $unit, int $amount, int $delta = 0) : void + public function testDateAdd(string $unit, int $amount, int $delta = 0): void { $query = sprintf( 'SELECT CURRENT_TIMESTAMP() as now, DATE_ADD(CURRENT_TIMESTAMP(), %d, \'%s\') AS add FROM %s m', @@ -310,8 +313,8 @@ public function testDateAdd(string $unit, int $amount, int $delta = 0) : void self::assertArrayHasKey('add', $result); self::assertEqualsWithDelta( - (new \DateTimeImmutable($result['now']))->modify(sprintf('+%d %s', $amount, $unit)), - new \DateTimeImmutable($result['add']), + (new DateTimeImmutable($result['now']))->modify(sprintf('+%d %s', $amount, $unit)), + new DateTimeImmutable($result['add']), $delta ); } @@ -319,10 +322,9 @@ public function testDateAdd(string $unit, int $amount, int $delta = 0) : void /** * @group DDC-1014 * @group DDC-2938 - * * @dataProvider dateAddSubProvider */ - public function testDateSub(string $unit, int $amount, int $delta = 0) : void + public function testDateSub(string $unit, int $amount, int $delta = 0): void { $query = sprintf( 'SELECT CURRENT_TIMESTAMP() as now, DATE_SUB(CURRENT_TIMESTAMP(), %d, \'%s\') AS sub FROM %s m', @@ -339,13 +341,13 @@ public function testDateSub(string $unit, int $amount, int $delta = 0) : void self::assertArrayHasKey('sub', $result); self::assertEqualsWithDelta( - (new \DateTimeImmutable($result['now']))->modify(sprintf('-%d %s', $amount, $unit)), - new \DateTimeImmutable($result['sub']), + (new DateTimeImmutable($result['now']))->modify(sprintf('-%d %s', $amount, $unit)), + new DateTimeImmutable($result['sub']), $delta ); } - public function dateAddSubProvider() : array + public function dateAddSubProvider(): array { $secondsInDay = 86400; @@ -363,14 +365,14 @@ public function dateAddSubProvider() : array /** * @group DDC-1213 */ - public function testBitOrComparison() + public function testBitOrComparison(): void { $dql = 'SELECT m, ' . 'BIT_OR(4, 2) AS bit_or,' . 'BIT_OR( (m.salary/100000) , 2 ) AS salary_bit_or ' . 'FROM Doctrine\Tests\Models\Company\CompanyManager m ' . 'ORDER BY ' . - 'm.id ' ; + 'm.id '; $result = $this->_em->createQuery($dql)->getArrayResult(); $this->assertEquals(4 | 2, $result[0]['bit_or']); @@ -378,23 +380,23 @@ public function testBitOrComparison() $this->assertEquals(4 | 2, $result[2]['bit_or']); $this->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']); + $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']); } /** - * @group DDC-1213 - */ - public function testBitAndComparison() + * @group DDC-1213 + */ + public function testBitAndComparison(): void { $dql = 'SELECT m, ' . 'BIT_AND(4, 2) AS bit_and,' . 'BIT_AND( (m.salary/100000) , 2 ) AS salary_bit_and ' . 'FROM Doctrine\Tests\Models\Company\CompanyManager m ' . 'ORDER BY ' . - 'm.id ' ; + 'm.id '; $result = $this->_em->createQuery($dql)->getArrayResult(); $this->assertEquals(4 & 2, $result[0]['bit_and']); @@ -402,13 +404,13 @@ public function testBitAndComparison() $this->assertEquals(4 & 2, $result[2]['bit_and']); $this->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']); + $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']); } - protected function generateFixture() + protected function generateFixture(): void { $manager1 = new CompanyManager(); $manager1->setName('Roman B.'); diff --git a/tests/Doctrine/Tests/ORM/Functional/QueryIterableTest.php b/tests/Doctrine/Tests/ORM/Functional/QueryIterableTest.php index 03e1282fee7..43a2cedafd8 100644 --- a/tests/Doctrine/Tests/ORM/Functional/QueryIterableTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/QueryIterableTest.php @@ -11,13 +11,13 @@ final class QueryIterableTest extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { $this->useModelSet('cms'); parent::setUp(); } - public function testAlias() : void + public function testAlias(): void { $user = new CmsUser(); $user->name = 'Guilherme'; @@ -37,7 +37,7 @@ public function testAlias() : void IterableTester::assertResultsAreTheSame($query); } - public function testAliasInnerJoin() : void + public function testAliasInnerJoin(): void { $user = new CmsUser(); $user->name = 'Guilherme'; diff --git a/tests/Doctrine/Tests/ORM/Functional/QueryTest.php b/tests/Doctrine/Tests/ORM/Functional/QueryTest.php index d7eaecbfc2c..2e6fbb1441a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/QueryTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/QueryTest.php @@ -1,44 +1,45 @@ useModelSet('cms'); parent::setUp(); } - public function testSimpleQueries() + public function testSimpleQueries(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; $this->_em->persist($user); $this->_em->flush(); $this->_em->clear(); @@ -73,21 +74,21 @@ public function testSimpleQueries() $this->assertEquals('GUILHERME', $query->getSingleScalarResult()); } - public function testJoinQueries() + public function testJoinQueries(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; - $article1 = new CmsArticle; - $article1->topic = "Doctrine 2"; - $article1->text = "This is an introduction to Doctrine 2."; + $article1 = new CmsArticle(); + $article1->topic = 'Doctrine 2'; + $article1->text = 'This is an introduction to Doctrine 2.'; $user->addArticle($article1); - $article2 = new CmsArticle; - $article2->topic = "Symfony 2"; - $article2->text = "This is an introduction to Symfony 2."; + $article2 = new CmsArticle(); + $article2->topic = 'Symfony 2'; + $article2->text = 'This is an introduction to Symfony 2.'; $user->addArticle($article2); $this->_em->persist($user); @@ -106,12 +107,12 @@ public function testJoinQueries() $this->assertEquals('Symfony 2', $users[0]->articles[1]->topic); } - public function testUsingZeroBasedQueryParameterShouldWork() + public function testUsingZeroBasedQueryParameterShouldWork(): void { - $user = new CmsUser; - $user->name = 'Jonathan'; + $user = new CmsUser(); + $user->name = 'Jonathan'; $user->username = 'jwage'; - $user->status = 'developer'; + $user->status = 'developer'; $this->_em->persist($user); $this->_em->flush(); $this->_em->clear(); @@ -123,7 +124,7 @@ public function testUsingZeroBasedQueryParameterShouldWork() $this->assertNotNull($user); } - public function testUsingUnknownQueryParameterShouldThrowException() + public function testUsingUnknownQueryParameterShouldThrowException(): void { $this->expectException(QueryException::class); $this->expectExceptionMessage('Invalid parameter: token 2 is not defined in the query.'); @@ -133,7 +134,7 @@ public function testUsingUnknownQueryParameterShouldThrowException() $user = $q->getSingleResult(); } - public function testTooManyParametersShouldThrowException() + public function testTooManyParametersShouldThrowException(): void { $this->expectException(QueryException::class); $this->expectExceptionMessage('Too many parameters: the query defines 1 parameters and you bound 2'); @@ -145,7 +146,7 @@ public function testTooManyParametersShouldThrowException() $user = $q->getSingleResult(); } - public function testTooFewParametersShouldThrowException() + public function testTooFewParametersShouldThrowException(): void { $this->expectException(QueryException::class); $this->expectExceptionMessage('Too few parameters: the query defines 1 parameters but you only bound 0'); @@ -154,7 +155,7 @@ public function testTooFewParametersShouldThrowException() ->getSingleResult(); } - public function testInvalidInputParameterThrowsException() + public function testInvalidInputParameterThrowsException(): void { $this->expectException(QueryException::class); @@ -163,7 +164,7 @@ public function testInvalidInputParameterThrowsException() ->getSingleResult(); } - public function testSetParameters() + public function testSetParameters(): void { $parameters = new ArrayCollection(); $parameters->add(new Parameter(1, 'jwage')); @@ -173,7 +174,7 @@ public function testSetParameters() ->setParameters($parameters) ->getResult(); - $extractValue = function (Parameter $parameter) { + $extractValue = static function (Parameter $parameter) { return $parameter->getValue(); }; @@ -183,7 +184,7 @@ public function testSetParameters() ); } - public function testSetParametersBackwardsCompatible() + public function testSetParametersBackwardsCompatible(): void { $parameters = [1 => 'jwage', 2 => 'active']; @@ -200,15 +201,15 @@ public function testSetParametersBackwardsCompatible() /** * @group DDC-1070 */ - public function testIterateResultAsArrayAndParams() + public function testIterateResultAsArrayAndParams(): void { - $article1 = new CmsArticle; - $article1->topic = "Doctrine 2"; - $article1->text = "This is an introduction to Doctrine 2."; + $article1 = new CmsArticle(); + $article1->topic = 'Doctrine 2'; + $article1->text = 'This is an introduction to Doctrine 2.'; - $article2 = new CmsArticle; - $article2->topic = "Symfony 2"; - $article2->text = "This is an introduction to Symfony 2."; + $article2 = new CmsArticle(); + $article2->topic = 'Symfony 2'; + $article2->text = 'This is an introduction to Symfony 2.'; $this->_em->persist($article1); $this->_em->persist($article2); @@ -217,7 +218,7 @@ public function testIterateResultAsArrayAndParams() $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); $expectedArticle = [ @@ -243,15 +244,15 @@ public function testIterateResultAsArrayAndParams() self::assertEquals([$expectedArticle], $articles); } - public function testIterateResult_IterativelyBuildUpUnitOfWork() + public function testIterateResult_IterativelyBuildUpUnitOfWork(): void { - $article1 = new CmsArticle; - $article1->topic = "Doctrine 2"; - $article1->text = "This is an introduction to Doctrine 2."; + $article1 = new CmsArticle(); + $article1->topic = 'Doctrine 2'; + $article1->text = 'This is an introduction to Doctrine 2.'; - $article2 = new CmsArticle; - $article2->topic = "Symfony 2"; - $article2->text = "This is an introduction to Symfony 2."; + $article2 = new CmsArticle(); + $article2->topic = 'Symfony 2'; + $article2->text = 'This is an introduction to Symfony 2.'; $this->_em->persist($article1); $this->_em->persist($article2); @@ -259,24 +260,24 @@ public function testIterateResult_IterativelyBuildUpUnitOfWork() $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; - $topics = []; + $topics = []; - foreach($articles AS $row) { - $article = $row[0]; + foreach ($articles as $row) { + $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); + $this->assertTrue($identityMapCount > $iteratedCount); $iteratedCount++; } - $this->assertSame(["Doctrine 2", "Symfony 2"], $topics); + $this->assertSame(['Doctrine 2', 'Symfony 2'], $topics); $this->assertSame(2, $iteratedCount); $articles = $query->toIterable(); @@ -298,15 +299,15 @@ public function testIterateResult_IterativelyBuildUpUnitOfWork() self::assertSame(2, $iteratedCount); } - public function testIterateResultClearEveryCycle() + public function testIterateResultClearEveryCycle(): void { - $article1 = new CmsArticle; - $article1->topic = "Doctrine 2"; - $article1->text = "This is an introduction to Doctrine 2."; + $article1 = new CmsArticle(); + $article1->topic = 'Doctrine 2'; + $article1->text = 'This is an introduction to Doctrine 2.'; - $article2 = new CmsArticle; - $article2->topic = "Symfony 2"; - $article2->text = "This is an introduction to Symfony 2."; + $article2 = new CmsArticle(); + $article2->topic = 'Symfony 2'; + $article2->text = 'This is an introduction to Symfony 2.'; $this->_em->persist($article1); $this->_em->persist($article2); @@ -318,8 +319,8 @@ public function testIterateResultClearEveryCycle() $articles = $query->iterate(); $iteratedCount = 0; - $topics = []; - foreach($articles AS $row) { + $topics = []; + foreach ($articles as $row) { $article = $row[0]; $topics[] = $article->topic; @@ -342,20 +343,20 @@ public function testIterateResultClearEveryCycle() $iteratedCount++; } - $this->assertSame(["Doctrine 2", "Symfony 2"], $topics); + $this->assertSame(['Doctrine 2', 'Symfony 2'], $topics); $this->assertSame(2, $iteratedCount); $this->_em->flush(); } - public function testIterateResult_FetchJoinedCollection_ThrowsException() + public function testIterateResult_FetchJoinedCollection_ThrowsException(): void { $this->expectException(QueryException::class); $query = $this->_em->createQuery("SELECT u, a FROM ' . CmsUser::class . ' u JOIN u.articles a"); $query->iterate(); } - public function testToIterableResultFetchJoinedCollectionThrowsException() : void + public function testToIterableResultFetchJoinedCollectionThrowsException(): void { $this->expectException(QueryException::class); @@ -363,36 +364,36 @@ public function testToIterableResultFetchJoinedCollectionThrowsException() : voi $query->toIterable(); } - public function testGetSingleResultThrowsExceptionOnNoResult() + public function testGetSingleResultThrowsExceptionOnNoResult(): void { $this->expectException('Doctrine\ORM\NoResultException'); - $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(); } - public function testGetSingleScalarResultThrowsExceptionOnNoResult() + public function testGetSingleScalarResultThrowsExceptionOnNoResult(): void { $this->expectException('Doctrine\ORM\NoResultException'); - $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(); } - public function testGetSingleScalarResultThrowsExceptionOnNonUniqueResult() + public function testGetSingleScalarResultThrowsExceptionOnNonUniqueResult(): void { $this->expectException('Doctrine\ORM\NonUniqueResultException'); - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; - $article1 = new CmsArticle; - $article1->topic = "Doctrine 2"; - $article1->text = "This is an introduction to Doctrine 2."; + $article1 = new CmsArticle(); + $article1->topic = 'Doctrine 2'; + $article1->text = 'This is an introduction to Doctrine 2.'; $user->addArticle($article1); - $article2 = new CmsArticle; - $article2->topic = "Symfony 2"; - $article2->text = "This is an introduction to Symfony 2."; + $article2 = new CmsArticle(); + $article2->topic = 'Symfony 2'; + $article2->text = 'This is an introduction to Symfony 2.'; $user->addArticle($article2); $this->_em->persist($user); @@ -402,17 +403,17 @@ public function testGetSingleScalarResultThrowsExceptionOnNonUniqueResult() $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(); } - public function testModifiedLimitQuery() + public function testModifiedLimitQuery(): void { for ($i = 0; $i < 5; $i++) { - $user = new CmsUser; - $user->name = 'Guilherme' . $i; + $user = new CmsUser(); + $user->name = 'Guilherme' . $i; $user->username = 'gblanco' . $i; - $user->status = 'developer'; + $user->status = 'developer'; $this->_em->persist($user); } @@ -443,7 +444,7 @@ public function testModifiedLimitQuery() ->getScalarResult(); } - public function testSupportsQueriesWithEntityNamespaces() + public function testSupportsQueriesWithEntityNamespaces(): void { $this->_em->getConfiguration()->addEntityNamespace('CMS', 'Doctrine\Tests\Models\CMS'); @@ -451,7 +452,7 @@ public function testSupportsQueriesWithEntityNamespaces() $query = $this->_em->createQuery('UPDATE CMS:CmsUser u SET u.name = ?1'); $this->assertEquals('UPDATE cms_users SET name = ?', $query->getSQL()); $query->free(); - } catch (\Exception $e) { + } catch (Exception $e) { $this->fail($e->getMessage()); } @@ -461,29 +462,29 @@ public function testSupportsQueriesWithEntityNamespaces() /** * @group DDC-604 */ - public function testEntityParameters() - { - $article = new CmsArticle; - $article->topic = "dr. dolittle"; - $article->text = "Once upon a time ..."; - $author = new CmsUser; - $author->name = "anonymous"; - $author->username = "anon"; - $author->status = "here"; - $article->user = $author; + public function testEntityParameters(): void + { + $article = new CmsArticle(); + $article->topic = 'dr. dolittle'; + $article->text = 'Once upon a time ...'; + $author = new CmsUser(); + $author->name = 'anonymous'; + $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)) - ->setParameter("topic", "dr. dolittle"); + $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->assertEquals('dr. dolittle', $result[0]->topic); $this->assertInstanceOf(Proxy::class, $result[0]->user); $this->assertFalse($result[0]->user->__isInitialized__); } @@ -491,20 +492,21 @@ public function testEntityParameters() /** * @group DDC-952 */ - public function testEnableFetchEagerMode() + public function testEnableFetchEagerMode(): void { 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; + $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->flush(); $this->_em->clear(); @@ -513,7 +515,7 @@ public function testEnableFetchEagerMode() ->getResult(); $this->assertEquals(10, count($articles)); - foreach ($articles AS $article) { + foreach ($articles as $article) { $this->assertNotInstanceOf(Proxy::class, $article); } } @@ -521,23 +523,23 @@ public function testEnableFetchEagerMode() /** * @group DDC-991 */ - public function testgetOneOrNullResult() + public function testgetOneOrNullResult(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $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'"); + $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'"); + $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); } @@ -545,22 +547,22 @@ public function testgetOneOrNullResult() /** * @group DDC-991 */ - public function testgetOneOrNullResultSeveralRows() + public function testgetOneOrNullResultSeveralRows(): void { - $user = new CmsUser; - $user->name = 'Guilherme'; + $user = new CmsUser(); + $user->name = 'Guilherme'; $user->username = 'gblanco'; - $user->status = 'developer'; + $user->status = 'developer'; $this->_em->persist($user); - $user = new CmsUser; - $user->name = 'Roman'; + $user = new CmsUser(); + $user->name = 'Roman'; $user->username = 'romanb'; - $user->status = 'developer'; + $user->status = 'developer'; $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); @@ -570,9 +572,9 @@ public function testgetOneOrNullResultSeveralRows() /** * @group DDC-991 */ - public function testgetOneOrNullResultNoRows() + public function testgetOneOrNullResultNoRows(): void { - $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->assertNull($query->getOneOrNullResult()); $query = $this->_em->createQuery("select u.username from Doctrine\Tests\Models\CMS\CmsUser u where u.username = 'gblanco'"); @@ -582,34 +584,34 @@ public function testgetOneOrNullResultNoRows() /** * @group DBAL-171 */ - public function testParameterOrder() + public function testParameterOrder(): void { - $user1 = new CmsUser; - $user1->name = 'Benjamin'; + $user1 = new CmsUser(); + $user1->name = 'Benjamin'; $user1->username = 'beberlei'; - $user1->status = 'developer'; + $user1->status = 'developer'; $this->_em->persist($user1); - $user2 = new CmsUser; - $user2->name = 'Roman'; + $user2 = new CmsUser(); + $user2->name = 'Roman'; $user2->username = 'romanb'; - $user2->status = 'developer'; + $user2->status = 'developer'; $this->_em->persist($user2); - $user3 = new CmsUser; - $user3->name = 'Jonathan'; + $user3 = new CmsUser(); + $user3->name = 'Jonathan'; $user3->username = 'jwage'; - $user3->status = 'developer'; + $user3->status = 'developer'; $this->_em->persist($user3); $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]), - new Parameter('a', 'developer') + new Parameter('b', [$user1->id, $user2->id, $user3->id]), + new Parameter('a', 'developer'), ] )); $result = $query->getResult(); @@ -617,30 +619,30 @@ public function testParameterOrder() $this->assertEquals(3, count($result)); } - public function testDqlWithAutoInferOfParameters() + public function testDqlWithAutoInferOfParameters(): void { - $user = new CmsUser; - $user->name = 'Benjamin'; + $user = new CmsUser(); + $user->name = 'Benjamin'; $user->username = 'beberlei'; - $user->status = 'developer'; + $user->status = 'developer'; $this->_em->persist($user); - $user = new CmsUser; - $user->name = 'Roman'; + $user = new CmsUser(); + $user->name = 'Roman'; $user->username = 'romanb'; - $user->status = 'developer'; + $user->status = 'developer'; $this->_em->persist($user); - $user = new CmsUser; - $user->name = 'Jonathan'; + $user = new CmsUser(); + $user->name = 'Jonathan'; $user->username = 'jwage'; - $user->status = 'developer'; + $user->status = 'developer'; $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 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(); @@ -648,7 +650,7 @@ public function testDqlWithAutoInferOfParameters() $this->assertEquals(2, count($users)); } - public function testQueryBuilderWithStringWhereClauseContainingOrAndConditionalPrimary() + public function testQueryBuilderWithStringWhereClauseContainingOrAndConditionalPrimary(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('u') @@ -662,30 +664,30 @@ public function testQueryBuilderWithStringWhereClauseContainingOrAndConditionalP $this->assertEquals(0, count($users)); } - public function testQueryWithArrayOfEntitiesAsParameter() + public function testQueryWithArrayOfEntitiesAsParameter(): void { - $userA = new CmsUser; - $userA->name = 'Benjamin'; + $userA = new CmsUser(); + $userA->name = 'Benjamin'; $userA->username = 'beberlei'; - $userA->status = 'developer'; + $userA->status = 'developer'; $this->_em->persist($userA); - $userB = new CmsUser; - $userB->name = 'Roman'; + $userB = new CmsUser(); + $userB->name = 'Roman'; $userB->username = 'romanb'; - $userB->status = 'developer'; + $userB->status = 'developer'; $this->_em->persist($userB); - $userC = new CmsUser; - $userC->name = 'Jonathan'; + $userC = new CmsUser(); + $userC->name = 'Jonathan'; $userC->username = 'jwage'; - $userC->status = 'developer'; + $userC->status = 'developer'; $this->_em->persist($userC); $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'); @@ -694,30 +696,30 @@ public function testQueryWithArrayOfEntitiesAsParameter() $this->assertEquals(2, count($users)); } - public function testQueryWithHiddenAsSelectExpression() + public function testQueryWithHiddenAsSelectExpression(): void { - $userA = new CmsUser; - $userA->name = 'Benjamin'; + $userA = new CmsUser(); + $userA->name = 'Benjamin'; $userA->username = 'beberlei'; - $userA->status = 'developer'; + $userA->status = 'developer'; $this->_em->persist($userA); - $userB = new CmsUser; - $userB->name = 'Roman'; + $userB = new CmsUser(); + $userB->name = 'Roman'; $userB->username = 'romanb'; - $userB->status = 'developer'; + $userB->status = 'developer'; $this->_em->persist($userB); - $userC = new CmsUser; - $userC->name = 'Jonathan'; + $userC = new CmsUser(); + $userC->name = 'Jonathan'; $userC->username = 'jwage'; - $userC->status = 'developer'; + $userC->status = 'developer'; $this->_em->persist($userC); $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)); @@ -727,18 +729,18 @@ public function testQueryWithHiddenAsSelectExpression() /** * @group DDC-1651 */ - public function testSetParameterBindingSingleIdentifierObject() + public function testSetParameterBindingSingleIdentifierObject(): void { - $userC = new CmsUser; - $userC->name = 'Jonathan'; + $userC = new CmsUser(); + $userC->name = 'Jonathan'; $userC->username = 'jwage'; - $userC->status = 'developer'; + $userC->status = 'developer'; $this->_em->persist($userC); $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()); @@ -750,24 +752,24 @@ public function testSetParameterBindingSingleIdentifierObject() /** * @group DDC-2319 */ - public function testSetCollectionParameterBindingSingleIdentifierObject() + public function testSetCollectionParameterBindingSingleIdentifierObject(): void { - $u1 = new CmsUser; - $u1->name = 'Name1'; + $u1 = new CmsUser(); + $u1->name = 'Name1'; $u1->username = 'username1'; - $u1->status = 'developer'; + $u1->status = 'developer'; $this->_em->persist($u1); - $u2 = new CmsUser; - $u2->name = 'Name2'; + $u2 = new CmsUser(); + $u2->name = 'Name2'; $u2->username = 'username2'; - $u2->status = 'tester'; + $u2->status = 'tester'; $this->_em->persist($u2); - $u3 = new CmsUser; - $u3->name = 'Name3'; + $u3 = new CmsUser(); + $u3->name = 'Name3'; $u3->username = 'username3'; - $u3->status = 'tester'; + $u3->status = 'tester'; $this->_em->persist($u3); $this->_em->flush(); @@ -779,7 +781,7 @@ 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(); @@ -800,17 +802,17 @@ public function testSetCollectionParameterBindingSingleIdentifierObject() /** * @group DDC-1822 */ - public function testUnexpectedResultException() - { - $dql = "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u"; - $u1 = new CmsUser; - $u2 = new CmsUser; - $u1->name = 'Fabio B. Silva'; - $u1->username = 'FabioBatSilva'; - $u1->status = 'developer'; - $u2->name = 'Test'; - $u2->username = 'test'; - $u2->status = 'tester'; + public function testUnexpectedResultException(): void + { + $dql = 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u'; + $u1 = new CmsUser(); + $u2 = new CmsUser(); + $u1->name = 'Fabio B. Silva'; + $u1->username = 'FabioBatSilva'; + $u1->status = 'developer'; + $u2->name = 'Test'; + $u2->username = 'test'; + $u2->status = 'tester'; try { $this->_em->createQuery($dql)->getSingleResult(); @@ -819,7 +821,6 @@ public function testUnexpectedResultException() $this->assertInstanceOf('\Doctrine\ORM\NoResultException', $exc); } - $this->_em->persist($u1); $this->_em->persist($u2); $this->_em->flush(); @@ -833,32 +834,32 @@ public function testUnexpectedResultException() } } - public function testMultipleJoinComponentsUsingInnerJoin() + public function testMultipleJoinComponentsUsingInnerJoin(): void { - $userA = new CmsUser; - $userA->name = 'Benjamin'; + $userA = new CmsUser(); + $userA->name = 'Benjamin'; $userA->username = 'beberlei'; - $userA->status = 'developer'; + $userA->status = 'developer'; - $phonenumberA = new CmsPhonenumber; + $phonenumberA = new CmsPhonenumber(); $phonenumberA->phonenumber = '111111'; $userA->addPhonenumber($phonenumberA); - $userB = new CmsUser; - $userB->name = 'Alexander'; + $userB = new CmsUser(); + $userB->name = 'Alexander'; $userB->username = 'asm89'; - $userB->status = 'developer'; + $userB->status = 'developer'; $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)); @@ -866,32 +867,32 @@ public function testMultipleJoinComponentsUsingInnerJoin() $this->assertInstanceOf(CmsPhonenumber::class, $users[1]); } - public function testMultipleJoinComponentsUsingLeftJoin() + public function testMultipleJoinComponentsUsingLeftJoin(): void { - $userA = new CmsUser; - $userA->name = 'Benjamin'; + $userA = new CmsUser(); + $userA->name = 'Benjamin'; $userA->username = 'beberlei'; - $userA->status = 'developer'; + $userA->status = 'developer'; - $phonenumberA = new CmsPhonenumber; + $phonenumberA = new CmsPhonenumber(); $phonenumberA->phonenumber = '111111'; $userA->addPhonenumber($phonenumberA); - $userB = new CmsUser; - $userB->name = 'Alexander'; + $userB = new CmsUser(); + $userB->name = 'Alexander'; $userB->username = 'asm89'; - $userB->status = 'developer'; + $userB->status = 'developer'; $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)); diff --git a/tests/Doctrine/Tests/ORM/Functional/ReadOnlyTest.php b/tests/Doctrine/Tests/ORM/Functional/ReadOnlyTest.php index 570a56d6251..5f9345501ab 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ReadOnlyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ReadOnlyTest.php @@ -1,8 +1,13 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(ReadOnlyEntity::class), + $this->_em->getClassMetadata(ReadOnlyEntity::class), ] ); - } catch(\Exception $e) { + } catch (Exception $e) { } } - public function testReadOnlyEntityNeverChangeTracked() + public function testReadOnlyEntityNeverChangeTracked(): void { - $readOnly = new ReadOnlyEntity("Test1", 1234); + $readOnly = new ReadOnlyEntity('Test1', 1234); $this->_em->persist($readOnly); $this->_em->flush(); - $readOnly->name = "Test2"; + $readOnly->name = 'Test2'; $readOnly->numericValue = 4321; $this->_em->flush(); $this->_em->clear(); $dbReadOnly = $this->_em->find(ReadOnlyEntity::class, $readOnly->id); - $this->assertEquals("Test1", $dbReadOnly->name); + $this->assertEquals('Test1', $dbReadOnly->name); $this->assertEquals(1234, $dbReadOnly->numericValue); } /** * @group DDC-1659 */ - public function testClearReadOnly() + public function testClearReadOnly(): void { - $readOnly = new ReadOnlyEntity("Test1", 1234); + $readOnly = new ReadOnlyEntity('Test1', 1234); $this->_em->persist($readOnly); $this->_em->flush(); $this->_em->getUnitOfWork()->markReadOnly($readOnly); @@ -60,9 +65,9 @@ public function testClearReadOnly() /** * @group DDC-1659 */ - public function testClearEntitiesReadOnly() + public function testClearEntitiesReadOnly(): void { - $readOnly = new ReadOnlyEntity("Test1", 1234); + $readOnly = new ReadOnlyEntity('Test1', 1234); $this->_em->persist($readOnly); $this->_em->flush(); $this->_em->getUnitOfWork()->markReadOnly($readOnly); @@ -90,7 +95,7 @@ class ReadOnlyEntity public function __construct($name, $number) { - $this->name = $name; + $this->name = $name; $this->numericValue = $number; } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ReferenceProxyTest.php b/tests/Doctrine/Tests/ORM/Functional/ReferenceProxyTest.php index a59903054c5..dd3f196c151 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ReferenceProxyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ReferenceProxyTest.php @@ -1,5 +1,7 @@ - * @author Benjamin Eberlei */ class ReferenceProxyTest extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { $this->useModelSet('ecommerce'); $this->useModelSet('company'); parent::setUp(); $this->_factory = new ProxyFactory( - $this->_em, - __DIR__ . '/../../Proxies', - 'Doctrine\Tests\Proxies', - true); + $this->_em, + __DIR__ . '/../../Proxies', + 'Doctrine\Tests\Proxies', + true + ); } public function createProduct() @@ -53,7 +63,7 @@ public function createAuction() return $event->getId(); } - public function testLazyLoadsFieldValuesFromDatabase() + public function testLazyLoadsFieldValuesFromDatabase(): void { $id = $this->createProduct(); @@ -64,12 +74,12 @@ public function testLazyLoadsFieldValuesFromDatabase() /** * @group DDC-727 */ - public function testAccessMetatadaForProxy() + public function testAccessMetatadaForProxy(): void { $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); } @@ -77,12 +87,12 @@ public function testAccessMetatadaForProxy() /** * @group DDC-1033 */ - public function testReferenceFind() + public function testReferenceFind(): void { $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()); @@ -91,22 +101,22 @@ public function testReferenceFind() /** * @group DDC-1033 */ - public function testCloneProxy() + public function testCloneProxy(): void { $id = $this->createProduct(); - /* @var $entity ECommerceProduct */ - $entity = $this->_em->getReference(ECommerceProduct::class , $id); + $entity = $this->_em->getReference(ECommerceProduct::class, $id); + assert($entity instanceof ECommerceProduct); - /* @var $clone ECommerceProduct */ $clone = clone $entity; + assert($clone instanceof ECommerceProduct); $this->assertEquals($id, $entity->getId()); $this->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."); + $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.'); // domain logic, Product::__clone sets isCloned public property $this->assertTrue($clone->isCloned); @@ -116,61 +126,61 @@ public function testCloneProxy() /** * @group DDC-733 */ - public function testInitializeProxy() + public function testInitializeProxy(): void { $id = $this->createProduct(); - /* @var $entity ECommerceProduct */ - $entity = $this->_em->getReference(ECommerceProduct::class , $id); + $entity = $this->_em->getReference(ECommerceProduct::class, $id); + assert($entity instanceof ECommerceProduct); - $this->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->assertTrue($entity->__isInitialized__, 'Should be initialized after called UnitOfWork::initializeObject()'); } /** * @group DDC-1163 */ - public function testInitializeChangeAndFlushProxy() + public function testInitializeChangeAndFlushProxy(): void { $id = $this->createProduct(); - /* @var $entity ECommerceProduct */ - $entity = $this->_em->getReference(ECommerceProduct::class , $id); + $entity = $this->_em->getReference(ECommerceProduct::class, $id); + assert($entity instanceof ECommerceProduct); $entity->setName('Doctrine 2 Cookbook'); $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()); } /** * @group DDC-1022 */ - public function testWakeupCalledOnProxy() + public function testWakeupCalledOnProxy(): void { $id = $this->createProduct(); - /* @var $entity ECommerceProduct */ - $entity = $this->_em->getReference(ECommerceProduct::class , $id); + $entity = $this->_em->getReference(ECommerceProduct::class, $id); + assert($entity instanceof ECommerceProduct); $this->assertFalse($entity->wakeUp); $entity->setName('Doctrine 2 Cookbook'); - $this->assertTrue($entity->wakeUp, "Loading the proxy should call __wakeup()."); + $this->assertTrue($entity->wakeUp, 'Loading the proxy should call __wakeup().'); } - public function testDoNotInitializeProxyOnGettingTheIdentifier() + public function testDoNotInitializeProxyOnGettingTheIdentifier(): void { $id = $this->createProduct(); - /* @var $entity ECommerceProduct */ - $entity = $this->_em->getReference(ECommerceProduct::class , $id); + $entity = $this->_em->getReference(ECommerceProduct::class, $id); + assert($entity instanceof ECommerceProduct); - $this->assertFalse($entity->__isInitialized__, "Pre-Condition: Object is unitialized proxy."); + $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."); } @@ -178,19 +188,19 @@ public function testDoNotInitializeProxyOnGettingTheIdentifier() /** * @group DDC-1625 */ - public function testDoNotInitializeProxyOnGettingTheIdentifier_DDC_1625() + public function testDoNotInitializeProxyOnGettingTheIdentifier_DDC_1625(): void { $id = $this->createAuction(); - /* @var $entity CompanyAuction */ - $entity = $this->_em->getReference(CompanyAuction::class , $id); + $entity = $this->_em->getReference(CompanyAuction::class, $id); + assert($entity instanceof CompanyAuction); - $this->assertFalse($entity->__isInitialized__, "Pre-Condition: Object is unitialized proxy."); + $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."); } - public function testDoNotInitializeProxyOnGettingTheIdentifierAndReturnTheRightType() + public function testDoNotInitializeProxyOnGettingTheIdentifierAndReturnTheRightType(): void { $product = new ECommerceProduct(); $product->setName('Doctrine Cookbook'); @@ -207,43 +217,43 @@ public function testDoNotInitializeProxyOnGettingTheIdentifierAndReturnTheRightT $product = $this->_em->getRepository(ECommerceProduct::class)->find($product->getId()); $entity = $product->getShipping(); - $this->assertFalse($entity->__isInitialized__, "Pre-Condition: Object is unitialized proxy."); + $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."); } - public function testInitializeProxyOnGettingSomethingOtherThanTheIdentifier() + public function testInitializeProxyOnGettingSomethingOtherThanTheIdentifier(): void { $id = $this->createProduct(); - /* @var $entity ECommerceProduct */ - $entity = $this->_em->getReference(ECommerceProduct::class , $id); + $entity = $this->_em->getReference(ECommerceProduct::class, $id); + assert($entity instanceof ECommerceProduct); - $this->assertFalse($entity->__isInitialized__, "Pre-Condition: Object is unitialized proxy."); + $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."); + $this->assertTrue($entity->__isInitialized__, 'Getting something other than the identifier initializes the proxy.'); } /** * @group DDC-1604 */ - public function testCommonPersistenceProxy() + public function testCommonPersistenceProxy(): void { $id = $this->createProduct(); - /* @var $entity ECommerceProduct */ - $entity = $this->_em->getReference(ECommerceProduct::class , $id); + $entity = $this->_em->getReference(ECommerceProduct::class, $id); + assert($entity instanceof ECommerceProduct); $className = ClassUtils::getClass($entity); $this->assertInstanceOf(Proxy::class, $entity); $this->assertFalse($entity->__isInitialized()); $this->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."); + $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.'); $entity->__load(); $this->assertTrue($entity->__isInitialized()); diff --git a/tests/Doctrine/Tests/ORM/Functional/ResultCacheTest.php b/tests/Doctrine/Tests/ORM/Functional/ResultCacheTest.php index b74b82cbdae..8694a520e14 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ResultCacheTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ResultCacheTest.php @@ -1,51 +1,48 @@ cacheDataReflection = new \ReflectionProperty(ArrayCache::class, "data"); + $this->cacheDataReflection = new ReflectionProperty(ArrayCache::class, 'data'); $this->cacheDataReflection->setAccessible(true); $this->useModelSet('cms'); parent::setUp(); } - /** - * @param ArrayCache $cache - * @return integer - */ - private function getCacheSize(ArrayCache $cache) + private function getCacheSize(ArrayCache $cache): int { return sizeof($this->cacheDataReflection->getValue($cache)); } - public function testResultCache() + public function testResultCache(): void { - $user = new CmsUser; + $user = new CmsUser(); - $user->name = 'Roman'; + $user->name = 'Roman'; $user->username = 'romanb'; - $user->status = 'dev'; + $user->status = 'dev'; $this->_em->persist($user); $this->_em->flush(); @@ -76,9 +73,9 @@ public function testResultCache() $this->assertEquals('Roman', $users[0]->name); } - public function testSetResultCacheId() + public function testSetResultCacheId(): void { - $cache = new ArrayCache; + $cache = new ArrayCache(); $query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); $query->setResultCacheDriver($cache); @@ -91,7 +88,7 @@ public function testSetResultCacheId() $this->assertTrue($cache->contains('testing_result_cache_id')); } - public function testUseResultCacheTrue() + public function testUseResultCacheTrue(): void { $cache = new ArrayCache(); $query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); @@ -106,7 +103,7 @@ public function testUseResultCacheTrue() $this->_em->getConfiguration()->setResultCacheImpl(new ArrayCache()); } - public function testUseResultCacheFalse() + public function testUseResultCacheFalse(): void { $cache = new ArrayCache(); $query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); @@ -121,11 +118,10 @@ public function testUseResultCacheFalse() $this->_em->getConfiguration()->setResultCacheImpl(new ArrayCache()); } - /** * @group DDC-1026 */ - public function testUseResultCacheParams() + public function testUseResultCacheParams(): void { $cache = new ArrayCache(); $sqlCount = count($this->_sqlLoggerStack->queries); @@ -159,7 +155,7 @@ public function testUseResultCacheParams() ); } - public function testEnableResultCache() : void + public function testEnableResultCache(): void { $cache = new ArrayCache(); $query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); @@ -177,7 +173,7 @@ public function testEnableResultCache() : void /** * @group DDC-1026 */ - public function testEnableResultCacheParams() : void + public function testEnableResultCacheParams(): void { $cache = new ArrayCache(); $sqlCount = count($this->_sqlLoggerStack->queries); @@ -211,7 +207,7 @@ public function testEnableResultCacheParams() : void ); } - public function testDisableResultCache() : void + public function testDisableResultCache(): void { $cache = new ArrayCache(); $query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); @@ -248,12 +244,11 @@ public function testNativeQueryResultCaching() } /** - * @param string $query * @depends testNativeQueryResultCaching */ - public function testResultCacheNotDependsOnQueryHints($query) + public function testResultCacheNotDependsOnQueryHints(string $query): void { - $cache = $query->getResultCacheDriver(); + $cache = $query->getResultCacheDriver(); $cacheCount = $this->getCacheSize($cache); $query->setHint('foo', 'bar'); @@ -264,11 +259,12 @@ public function testResultCacheNotDependsOnQueryHints($query) /** * @param $query + * * @depends testNativeQueryResultCaching */ - public function testResultCacheDependsOnParameters($query) + public function testResultCacheDependsOnParameters($query): void { - $cache = $query->getResultCacheDriver(); + $cache = $query->getResultCacheDriver(); $cacheCount = $this->getCacheSize($cache); $query->setParameter(1, 50); @@ -279,11 +275,12 @@ public function testResultCacheDependsOnParameters($query) /** * @param $query + * * @depends testNativeQueryResultCaching */ - public function testResultCacheNotDependsOnHydrationMode($query) + public function testResultCacheNotDependsOnHydrationMode($query): void { - $cache = $query->getResultCacheDriver(); + $cache = $query->getResultCacheDriver(); $cacheCount = $this->getCacheSize($cache); $this->assertNotEquals(Query::HYDRATE_ARRAY, $query->getHydrationMode()); @@ -295,22 +292,22 @@ public function testResultCacheNotDependsOnHydrationMode($query) /** * @group DDC-909 */ - public function testResultCacheWithObjectParameter() + public function testResultCacheWithObjectParameter(): void { - $user1 = new CmsUser; - $user1->name = 'Roman'; + $user1 = new CmsUser(); + $user1->name = 'Roman'; $user1->username = 'romanb'; - $user1->status = 'dev'; + $user1->status = 'dev'; - $user2 = new CmsUser; - $user2->name = 'Benjamin'; + $user2 = new CmsUser(); + $user2->name = 'Benjamin'; $user2->username = 'beberlei'; - $user2->status = 'dev'; + $user2->status = 'dev'; - $article = new CmsArticle(); - $article->text = "foo"; - $article->topic = "baz"; - $article->user = $user1; + $article = new CmsArticle(); + $article->text = 'foo'; + $article->topic = 'baz'; + $article->user = $user1; $this->_em->persist($article); $this->_em->persist($user1); diff --git a/tests/Doctrine/Tests/ORM/Functional/SQLFilterTest.php b/tests/Doctrine/Tests/ORM/Functional/SQLFilterTest.php index 35b5459fc6b..8c516bdefe4 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SQLFilterTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SQLFilterTest.php @@ -1,5 +1,7 @@ - * * @group non-cacheable */ class SQLFilterTest extends OrmFunctionalTestCase @@ -39,56 +47,57 @@ class SQLFilterTest extends OrmFunctionalTestCase private $managerId, $managerId2, $contractId1, $contractId2; private $organizationId, $eventId1, $eventId2; - protected function setUp() : void + protected function setUp(): void { $this->useModelSet('cms'); $this->useModelSet('company'); parent::setUp(); } - public function tearDown() : void + public function tearDown(): void { parent::tearDown(); - $class = $this->_em->getClassMetadata(CmsUser::class); - $class->associationMappings['groups']['fetch'] = ClassMetadataInfo::FETCH_LAZY; + $class = $this->_em->getClassMetadata(CmsUser::class); + $class->associationMappings['groups']['fetch'] = ClassMetadataInfo::FETCH_LAZY; $class->associationMappings['articles']['fetch'] = ClassMetadataInfo::FETCH_LAZY; } - public function testConfigureFilter() + public function testConfigureFilter(): void { $config = new Configuration(); - $config->addFilter("locale", "\Doctrine\Tests\ORM\Functional\MyLocaleFilter"); + $config->addFilter('locale', '\Doctrine\Tests\ORM\Functional\MyLocaleFilter'); - $this->assertEquals("\Doctrine\Tests\ORM\Functional\MyLocaleFilter", $config->getFilterClassName("locale")); - $this->assertNull($config->getFilterClassName("foo")); + $this->assertEquals('\Doctrine\Tests\ORM\Functional\MyLocaleFilter', $config->getFilterClassName('locale')); + $this->assertNull($config->getFilterClassName('foo')); } - public function testEntityManagerEnableFilter() + public function testEntityManagerEnableFilter(): void { $em = $this->_getEntityManager(); $this->configureFilters($em); // Enable an existing filter - $filter = $em->getFilters()->enable("locale"); + $filter = $em->getFilters()->enable('locale'); $this->assertTrue($filter instanceof MyLocaleFilter); // Enable the filter again - $filter2 = $em->getFilters()->enable("locale"); + $filter2 = $em->getFilters()->enable('locale'); $this->assertEquals($filter, $filter2); // Enable a non-existing filter $exceptionThrown = false; try { - $filter = $em->getFilters()->enable("foo"); - } catch (\InvalidArgumentException $e) { + $filter = $em->getFilters()->enable('foo'); + } catch (InvalidArgumentException $e) { $exceptionThrown = true; } + $this->assertTrue($exceptionThrown); } - public function testEntityManagerEnabledFilters() + public function testEntityManagerEnabledFilters(): void { $em = $this->_getEntityManager(); @@ -96,112 +105,110 @@ public function testEntityManagerEnabledFilters() $this->assertEquals([], $em->getFilters()->getEnabledFilters()); $this->configureFilters($em); - $filter = $em->getFilters()->enable("locale"); - $filter = $em->getFilters()->enable("soft_delete"); + $filter = $em->getFilters()->enable('locale'); + $filter = $em->getFilters()->enable('soft_delete'); // Two enabled filters $this->assertEquals(2, count($em->getFilters()->getEnabledFilters())); - } - public function testEntityManagerDisableFilter() + public function testEntityManagerDisableFilter(): void { $em = $this->_getEntityManager(); $this->configureFilters($em); // Enable the filter - $filter = $em->getFilters()->enable("locale"); + $filter = $em->getFilters()->enable('locale'); // Disable it - $this->assertEquals($filter, $em->getFilters()->disable("locale")); + $this->assertEquals($filter, $em->getFilters()->disable('locale')); $this->assertEquals(0, count($em->getFilters()->getEnabledFilters())); // Disable a non-existing filter $exceptionThrown = false; try { - $filter = $em->getFilters()->disable("foo"); - } catch (\InvalidArgumentException $e) { + $filter = $em->getFilters()->disable('foo'); + } catch (InvalidArgumentException $e) { $exceptionThrown = true; } + $this->assertTrue($exceptionThrown); // Disable a non-enabled filter $exceptionThrown = false; try { - $filter = $em->getFilters()->disable("locale"); - } catch (\InvalidArgumentException $e) { + $filter = $em->getFilters()->disable('locale'); + } catch (InvalidArgumentException $e) { $exceptionThrown = true; } + $this->assertTrue($exceptionThrown); } - public function testEntityManagerGetFilter() + public function testEntityManagerGetFilter(): void { $em = $this->_getEntityManager(); $this->configureFilters($em); // Enable the filter - $filter = $em->getFilters()->enable("locale"); + $filter = $em->getFilters()->enable('locale'); // Get the filter - $this->assertEquals($filter, $em->getFilters()->getFilter("locale")); + $this->assertEquals($filter, $em->getFilters()->getFilter('locale')); // Get a non-enabled filter $exceptionThrown = false; try { - $filter = $em->getFilters()->getFilter("soft_delete"); - } catch (\InvalidArgumentException $e) { + $filter = $em->getFilters()->getFilter('soft_delete'); + } catch (InvalidArgumentException $e) { $exceptionThrown = true; } + $this->assertTrue($exceptionThrown); } /** * @group DDC-2203 */ - public function testEntityManagerIsFilterEnabled() + public function testEntityManagerIsFilterEnabled(): void { $em = $this->_getEntityManager(); $this->configureFilters($em); // Check for an enabled filter - $em->getFilters()->enable("locale"); - $this->assertTrue($em->getFilters()->isEnabled("locale")); + $em->getFilters()->enable('locale'); + $this->assertTrue($em->getFilters()->isEnabled('locale')); // Check for a disabled filter - $em->getFilters()->disable("locale"); - $this->assertFalse($em->getFilters()->isEnabled("locale")); + $em->getFilters()->disable('locale'); + $this->assertFalse($em->getFilters()->isEnabled('locale')); // Check a non-existing filter - $this->assertFalse($em->getFilters()->isEnabled("foo_filter")); + $this->assertFalse($em->getFilters()->isEnabled('foo_filter')); } - protected function configureFilters($em) + protected function configureFilters($em): void { // Add filters to the configuration of the EM $config = $em->getConfiguration(); - $config->addFilter("locale", "\Doctrine\Tests\ORM\Functional\MyLocaleFilter"); - $config->addFilter("soft_delete", "\Doctrine\Tests\ORM\Functional\MySoftDeleteFilter"); + $config->addFilter('locale', '\Doctrine\Tests\ORM\Functional\MyLocaleFilter'); + $config->addFilter('soft_delete', '\Doctrine\Tests\ORM\Functional\MySoftDeleteFilter'); } protected function getMockConnection() { // Setup connection mock - $conn = $this->getMockBuilder(Connection::class) + return $this->getMockBuilder(Connection::class) ->disableOriginalConstructor() ->getMock(); - - return $conn; } protected function getMockEntityManager() { // Setup connection mock - $em = $this->getMockBuilder(EntityManager::class) + return $this->getMockBuilder(EntityManager::class) ->disableOriginalConstructor() ->getMock(); - - return $em; } protected function addMockFilterCollection($em) @@ -217,7 +224,7 @@ protected function addMockFilterCollection($em) return $filterCollection; } - public function testSQLFilterGetSetParameter() + public function testSQLFilterGetSetParameter(): void { // Setup mock connection $conn = $this->getMockConnection(); @@ -247,7 +254,7 @@ public function testSQLFilterGetSetParameter() * @group DDC-3161 * @group 1054 */ - public function testSQLFilterGetConnection() + public function testSQLFilterGetConnection(): void { // Setup mock connection $conn = $this->getMockConnection(); @@ -259,13 +266,13 @@ public function testSQLFilterGetConnection() $filter = new MyLocaleFilter($em); - $reflMethod = new \ReflectionMethod(SQLFilter::class, 'getConnection'); + $reflMethod = new ReflectionMethod(SQLFilter::class, 'getConnection'); $reflMethod->setAccessible(true); $this->assertSame($conn, $reflMethod->invoke($filter)); } - public function testSQLFilterSetParameterInfersType() + public function testSQLFilterSetParameterInfersType(): void { // Setup mock connection $conn = $this->getMockConnection(); @@ -291,7 +298,7 @@ public function testSQLFilterSetParameterInfersType() $this->assertEquals("'en'", $filter->getParameter('locale')); } - public function testSQLFilterAddConstraint() + public function testSQLFilterAddConstraint(): void { // Set up metadata mock $targetEntity = $this->getMockBuilder(ClassMetadata::class) @@ -307,12 +314,11 @@ public function testSQLFilterAddConstraint() // Test for an entity that doesn't get extra filter data $targetEntity->name = 'MyEntity\NoSoftDeleteNewsItem'; $this->assertEquals('', $filter->addFilterConstraint($targetEntity, 't1_')); - } - public function testSQLFilterToString() + public function testSQLFilterToString(): void { - $em = $this->getMockEntityManager(); + $em = $this->getMockEntityManager(); $filterCollection = $this->addMockFilterCollection($em); $filter = new MyLocaleFilter($em); @@ -328,13 +334,13 @@ public function testSQLFilterToString() 'locale' => ['value' => 'en', 'type' => DBALType::STRING], ]; - $this->assertEquals(serialize($parameters), ''.$filter); - $this->assertEquals(''.$filter, ''.$filter2); + $this->assertEquals(serialize($parameters), '' . $filter); + $this->assertEquals('' . $filter, '' . $filter2); } - public function testQueryCache_DependsOnFilters() + public function testQueryCache_DependsOnFilters(): void { - $cacheDataReflection = new \ReflectionProperty(ArrayCache::class, "data"); + $cacheDataReflection = new ReflectionProperty(ArrayCache::class, 'data'); $cacheDataReflection->setAccessible(true); $query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); @@ -346,8 +352,8 @@ public function testQueryCache_DependsOnFilters() $this->assertEquals(1, sizeof($cacheDataReflection->getValue($cache))); $conf = $this->_em->getConfiguration(); - $conf->addFilter("locale", "\Doctrine\Tests\ORM\Functional\MyLocaleFilter"); - $this->_em->getFilters()->enable("locale"); + $conf->addFilter('locale', '\Doctrine\Tests\ORM\Functional\MyLocaleFilter'); + $this->_em->getFilters()->enable('locale'); $query->getResult(); $this->assertEquals(2, sizeof($cacheDataReflection->getValue($cache))); @@ -357,20 +363,20 @@ public function testQueryCache_DependsOnFilters() $this->assertEquals(2, sizeof($cacheDataReflection->getValue($cache))); } - public function testQueryGeneration_DependsOnFilters() + public function testQueryGeneration_DependsOnFilters(): void { - $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->addFilter("country", "\Doctrine\Tests\ORM\Functional\CMSCountryFilter"); - $this->_em->getFilters()->enable("country") - ->setParameter("country", "en", DBALType::STRING); + $conf->addFilter('country', '\Doctrine\Tests\ORM\Functional\CMSCountryFilter'); + $this->_em->getFilters()->enable('country') + ->setParameter('country', 'en', DBALType::STRING); $this->assertNotEquals($firstSQLQuery, $query->getSQL()); } - public function testRepositoryFind() + public function testRepositoryFind(): void { $this->loadFixtureData(); @@ -384,7 +390,7 @@ public function testRepositoryFind() $this->assertNull($this->_em->getRepository(CmsGroup::class)->find($this->groupId2)); } - public function testRepositoryFindAll() + public function testRepositoryFindAll(): void { $this->loadFixtureData(); @@ -396,7 +402,7 @@ public function testRepositoryFindAll() $this->assertCount(1, $this->_em->getRepository(CmsGroup::class)->findAll()); } - public function testRepositoryFindBy() + public function testRepositoryFindBy(): void { $this->loadFixtureData(); @@ -412,7 +418,7 @@ public function testRepositoryFindBy() )); } - public function testRepositoryFindByX() + public function testRepositoryFindByX(): void { $this->loadFixtureData(); @@ -424,7 +430,7 @@ public function testRepositoryFindByX() $this->assertCount(0, $this->_em->getRepository(CmsGroup::class)->findById($this->groupId2)); } - public function testRepositoryFindOneBy() + public function testRepositoryFindOneBy(): void { $this->loadFixtureData(); @@ -440,7 +446,7 @@ public function testRepositoryFindOneBy() )); } - public function testRepositoryFindOneByX() + public function testRepositoryFindOneByX(): void { $this->loadFixtureData(); @@ -452,7 +458,7 @@ public function testRepositoryFindOneByX() $this->assertNull($this->_em->getRepository(CmsGroup::class)->findOneById($this->groupId2)); } - public function testToOneFilter() + public function testToOneFilter(): void { //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); $this->loadFixtureData(); @@ -463,14 +469,14 @@ public function testToOneFilter() $this->assertEquals(2, count($query->getResult())); $conf = $this->_em->getConfiguration(); - $conf->addFilter("country", "\Doctrine\Tests\ORM\Functional\CMSCountryFilter"); - $this->_em->getFilters()->enable("country")->setParameter("country", "Germany", DBALType::STRING); + $conf->addFilter('country', '\Doctrine\Tests\ORM\Functional\CMSCountryFilter'); + $this->_em->getFilters()->enable('country')->setParameter('country', 'Germany', DBALType::STRING); // We get one user after enabling the filter $this->assertEquals(1, count($query->getResult())); } - public function testManyToManyFilter() + public function testManyToManyFilter(): void { $this->loadFixtureData(); $query = $this->_em->createQuery('select ux, ug from Doctrine\Tests\Models\CMS\CmsUser ux JOIN ux.groups ug'); @@ -479,15 +485,14 @@ public function testManyToManyFilter() $this->assertEquals(2, count($query->getResult())); $conf = $this->_em->getConfiguration(); - $conf->addFilter("group_prefix", "\Doctrine\Tests\ORM\Functional\CMSGroupPrefixFilter"); - $this->_em->getFilters()->enable("group_prefix")->setParameter("prefix", "bar_%", DBALType::STRING); + $conf->addFilter('group_prefix', '\Doctrine\Tests\ORM\Functional\CMSGroupPrefixFilter'); + $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())); - } - public function testWhereFilter() + public function testWhereFilter(): void { $this->loadFixtureData(); $query = $this->_em->createQuery('select ug from Doctrine\Tests\Models\CMS\CmsGroup ug WHERE 1=1'); @@ -496,14 +501,14 @@ public function testWhereFilter() $this->assertEquals(2, count($query->getResult())); $conf = $this->_em->getConfiguration(); - $conf->addFilter("group_prefix", "\Doctrine\Tests\ORM\Functional\CMSGroupPrefixFilter"); - $this->_em->getFilters()->enable("group_prefix")->setParameter("prefix", "bar_%", DBALType::STRING); + $conf->addFilter('group_prefix', '\Doctrine\Tests\ORM\Functional\CMSGroupPrefixFilter'); + $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())); } - public function testWhereOrFilter() + public function testWhereOrFilter(): void { $this->loadFixtureData(); $query = $this->_em->createQuery('select ug from Doctrine\Tests\Models\CMS\CmsGroup ug WHERE 1=1 OR 1=1'); @@ -512,30 +517,29 @@ public function testWhereOrFilter() $this->assertEquals(2, count($query->getResult())); $conf = $this->_em->getConfiguration(); - $conf->addFilter("group_prefix", "\Doctrine\Tests\ORM\Functional\CMSGroupPrefixFilter"); - $this->_em->getFilters()->enable("group_prefix")->setParameter("prefix", "bar_%", DBALType::STRING); + $conf->addFilter('group_prefix', '\Doctrine\Tests\ORM\Functional\CMSGroupPrefixFilter'); + $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())); } - - private function loadLazyFixtureData() + private function loadLazyFixtureData(): void { - $class = $this->_em->getClassMetadata(CmsUser::class); + $class = $this->_em->getClassMetadata(CmsUser::class); $class->associationMappings['articles']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY; - $class->associationMappings['groups']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY; + $class->associationMappings['groups']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY; $this->loadFixtureData(); } - private function useCMSArticleTopicFilter() + private function useCMSArticleTopicFilter(): void { $conf = $this->_em->getConfiguration(); - $conf->addFilter("article_topic", "\Doctrine\Tests\ORM\Functional\CMSArticleTopicFilter"); - $this->_em->getFilters()->enable("article_topic")->setParameter("topic", "Test1", DBALType::STRING); + $conf->addFilter('article_topic', '\Doctrine\Tests\ORM\Functional\CMSArticleTopicFilter'); + $this->_em->getFilters()->enable('article_topic')->setParameter('topic', 'Test1', DBALType::STRING); } - public function testOneToMany_ExtraLazyCountWithFilter() + public function testOneToMany_ExtraLazyCountWithFilter(): void { $this->loadLazyFixtureData(); $user = $this->_em->find(CmsUser::class, $this->userId); @@ -548,10 +552,10 @@ public function testOneToMany_ExtraLazyCountWithFilter() $this->assertEquals(1, count($user->articles)); } - public function testOneToMany_ExtraLazyContainsWithFilter() + public function testOneToMany_ExtraLazyContainsWithFilter(): void { $this->loadLazyFixtureData(); - $user = $this->_em->find(CmsUser::class, $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $filteredArticle = $this->_em->find(CmsArticle::class, $this->articleId2); $this->assertFalse($user->articles->isInitialized()); @@ -562,27 +566,27 @@ public function testOneToMany_ExtraLazyContainsWithFilter() $this->assertFalse($user->articles->contains($filteredArticle)); } - public function testOneToMany_ExtraLazySliceWithFilter() + public function testOneToMany_ExtraLazySliceWithFilter(): void { $this->loadLazyFixtureData(); $user = $this->_em->find(CmsUser::class, $this->userId); $this->assertFalse($user->articles->isInitialized()); - $this->assertEquals(2, count($user->articles->slice(0,10))); + $this->assertEquals(2, count($user->articles->slice(0, 10))); $this->useCMSArticleTopicFilter(); - $this->assertEquals(1, count($user->articles->slice(0,10))); + $this->assertEquals(1, count($user->articles->slice(0, 10))); } - private function useCMSGroupPrefixFilter() + private function useCMSGroupPrefixFilter(): void { $conf = $this->_em->getConfiguration(); - $conf->addFilter("group_prefix", "\Doctrine\Tests\ORM\Functional\CMSGroupPrefixFilter"); - $this->_em->getFilters()->enable("group_prefix")->setParameter("prefix", "foo%", DBALType::STRING); + $conf->addFilter('group_prefix', '\Doctrine\Tests\ORM\Functional\CMSGroupPrefixFilter'); + $this->_em->getFilters()->enable('group_prefix')->setParameter('prefix', 'foo%', DBALType::STRING); } - public function testManyToMany_ExtraLazyCountWithFilter() + public function testManyToMany_ExtraLazyCountWithFilter(): void { $this->loadLazyFixtureData(); @@ -596,10 +600,10 @@ public function testManyToMany_ExtraLazyCountWithFilter() $this->assertEquals(1, count($user->groups)); } - public function testManyToMany_ExtraLazyContainsWithFilter() + public function testManyToMany_ExtraLazyContainsWithFilter(): void { $this->loadLazyFixtureData(); - $user = $this->_em->find(CmsUser::class, $this->userId2); + $user = $this->_em->find(CmsUser::class, $this->userId2); $filteredArticle = $this->_em->find(CmsGroup::class, $this->groupId2); $this->assertFalse($user->groups->isInitialized()); @@ -610,46 +614,46 @@ public function testManyToMany_ExtraLazyContainsWithFilter() $this->assertFalse($user->groups->contains($filteredArticle)); } - public function testManyToMany_ExtraLazySliceWithFilter() + public function testManyToMany_ExtraLazySliceWithFilter(): void { $this->loadLazyFixtureData(); $user = $this->_em->find(CmsUser::class, $this->userId2); $this->assertFalse($user->groups->isInitialized()); - $this->assertEquals(2, count($user->groups->slice(0,10))); + $this->assertEquals(2, count($user->groups->slice(0, 10))); $this->useCMSGroupPrefixFilter(); - $this->assertEquals(1, count($user->groups->slice(0,10))); + $this->assertEquals(1, count($user->groups->slice(0, 10))); } - private function loadFixtureData() + private function loadFixtureData(): void { - $user = new CmsUser; - $user->name = 'Roman'; + $user = new CmsUser(); + $user->name = 'Roman'; $user->username = 'romanb'; - $user->status = 'developer'; + $user->status = 'developer'; - $address = new CmsAddress; + $address = new CmsAddress(); $address->country = 'Germany'; - $address->city = 'Berlin'; - $address->zip = '12345'; + $address->city = 'Berlin'; + $address->zip = '12345'; $user->address = $address; // inverse side $address->user = $user; // owning side! - $group = new CmsGroup; + $group = new CmsGroup(); $group->name = 'foo_group'; $user->addGroup($group); - $article1 = new CmsArticle; - $article1->topic = "Test1"; - $article1->text = "Test"; + $article1 = new CmsArticle(); + $article1->topic = 'Test1'; + $article1->text = 'Test'; $article1->setAuthor($user); - $article2 = new CmsArticle; - $article2->topic = "Test2"; - $article2->text = "Test"; + $article2 = new CmsArticle(); + $article2->topic = 'Test2'; + $article2->text = 'Test'; $article2->setAuthor($user); $this->_em->persist($article1); @@ -657,21 +661,21 @@ private function loadFixtureData() $this->_em->persist($user); - $user2 = new CmsUser; - $user2->name = 'Guilherme'; + $user2 = new CmsUser(); + $user2->name = 'Guilherme'; $user2->username = 'gblanco'; - $user2->status = 'developer'; + $user2->status = 'developer'; - $address2 = new CmsAddress; + $address2 = new CmsAddress(); $address2->country = 'France'; - $address2->city = 'Paris'; - $address2->zip = '12345'; + $address2->city = 'Paris'; + $address2->zip = '12345'; - $user->address = $address2; // inverse side + $user->address = $address2; // inverse side $address2->user = $user2; // owning side! $user2->addGroup($group); - $group2 = new CmsGroup; + $group2 = new CmsGroup(); $group2->name = 'bar_group'; $user2->addGroup($group2); @@ -679,63 +683,63 @@ private function loadFixtureData() $this->_em->flush(); $this->_em->clear(); - $this->userId = $user->getId(); - $this->userId2 = $user2->getId(); - $this->articleId = $article1->id; + $this->userId = $user->getId(); + $this->userId2 = $user2->getId(); + $this->articleId = $article1->id; $this->articleId2 = $article2->id; - $this->groupId = $group->id; - $this->groupId2 = $group2->id; + $this->groupId = $group->id; + $this->groupId2 = $group2->id; } - public function testJoinSubclassPersister_FilterOnlyOnRootTableWhenFetchingSubEntity() + public function testJoinSubclassPersister_FilterOnlyOnRootTableWhenFetchingSubEntity(): void { $this->loadCompanyJoinedSubclassFixtureData(); // Persister $this->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())); + $this->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()); + $this->assertEquals('Guilherme', $managers[0]->getName()); - $this->assertEquals(1, count($this->_em->createQuery("SELECT cm FROM Doctrine\Tests\Models\Company\CompanyManager cm")->getResult())); + $this->assertEquals(1, count($this->_em->createQuery('SELECT cm FROM Doctrine\Tests\Models\Company\CompanyManager cm')->getResult())); } - public function testJoinSubclassPersister_FilterOnlyOnRootTableWhenFetchingRootEntity() + public function testJoinSubclassPersister_FilterOnlyOnRootTableWhenFetchingRootEntity(): void { $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())); + $this->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()); + $this->assertEquals('Guilherme', $persons[0]->getName()); - $this->assertEquals(1, count($this->_em->createQuery("SELECT cp FROM Doctrine\Tests\Models\Company\CompanyPerson cp")->getResult())); + $this->assertEquals(1, count($this->_em->createQuery('SELECT cp FROM Doctrine\Tests\Models\Company\CompanyPerson cp')->getResult())); } - private function loadCompanyJoinedSubclassFixtureData() + private function loadCompanyJoinedSubclassFixtureData(): void { - $manager = new CompanyManager; + $manager = new CompanyManager(); $manager->setName('Roman'); $manager->setTitle('testlead'); $manager->setSalary(42); $manager->setDepartment('persisters'); - $manager2 = new CompanyManager; + $manager2 = new CompanyManager(); $manager2->setName('Guilherme'); $manager2->setTitle('devlead'); $manager2->setSalary(42); $manager2->setDepartment('parsers'); - $person = new CompanyPerson; + $person = new CompanyPerson(); $person->setName('Benjamin'); $this->_em->persist($manager); @@ -745,59 +749,59 @@ private function loadCompanyJoinedSubclassFixtureData() $this->_em->clear(); } - public function testSingleTableInheritance_FilterOnlyOnRootTableWhenFetchingSubEntity() + public function testSingleTableInheritance_FilterOnlyOnRootTableWhenFetchingSubEntity(): void { $this->loadCompanySingleTableInheritanceFixtureData(); // Persister $this->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())); + $this->assertEquals(2, count($this->_em->createQuery('SELECT cfc FROM Doctrine\Tests\Models\Company\CompanyFlexUltraContract cfc')->getResult())); // Enable the filter $conf = $this->_em->getConfiguration(); - $conf->addFilter("completed_contract", "\Doctrine\Tests\ORM\Functional\CompletedContractFilter"); + $conf->addFilter('completed_contract', '\Doctrine\Tests\ORM\Functional\CompletedContractFilter'); $this->_em->getFilters() - ->enable("completed_contract") - ->setParameter("completed", true, DBALType::BOOLEAN); + ->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())); + $this->assertEquals(1, count($this->_em->createQuery('SELECT cfc FROM Doctrine\Tests\Models\Company\CompanyFlexUltraContract cfc')->getResult())); } - public function testSingleTableInheritance_FilterOnlyOnRootTableWhenFetchingRootEntity() + public function testSingleTableInheritance_FilterOnlyOnRootTableWhenFetchingRootEntity(): void { $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())); + $this->assertEquals(4, count($this->_em->createQuery('SELECT cfc FROM Doctrine\Tests\Models\Company\CompanyFlexContract cfc')->getResult())); // Enable the filter $conf = $this->_em->getConfiguration(); - $conf->addFilter("completed_contract", "\Doctrine\Tests\ORM\Functional\CompletedContractFilter"); + $conf->addFilter('completed_contract', '\Doctrine\Tests\ORM\Functional\CompletedContractFilter'); $this->_em->getFilters() - ->enable("completed_contract") - ->setParameter("completed", true, DBALType::BOOLEAN); + ->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())); + $this->assertEquals(2, count($this->_em->createQuery('SELECT cfc FROM Doctrine\Tests\Models\Company\CompanyFlexContract cfc')->getResult())); } - private function loadCompanySingleTableInheritanceFixtureData() + private function loadCompanySingleTableInheritanceFixtureData(): void { - $contract1 = new CompanyFlexUltraContract; - $contract2 = new CompanyFlexUltraContract; + $contract1 = new CompanyFlexUltraContract(); + $contract2 = new CompanyFlexUltraContract(); $contract2->markCompleted(); - $contract3 = new CompanyFlexContract; - $contract4 = new CompanyFlexContract; + $contract3 = new CompanyFlexContract(); + $contract4 = new CompanyFlexContract(); $contract4->markCompleted(); - $manager = new CompanyManager; + $manager = new CompanyManager(); $manager->setName('Alexander'); $manager->setSalary(42); $manager->setDepartment('Doctrine'); $manager->setTitle('Filterer'); - $manager2 = new CompanyManager; + $manager2 = new CompanyManager(); $manager2->setName('Benjamin'); $manager2->setSalary(1337); $manager2->setDepartment('Doctrine'); @@ -822,22 +826,22 @@ private function loadCompanySingleTableInheritanceFixtureData() $this->_em->flush(); $this->_em->clear(); - $this->managerId = $manager->getId(); - $this->managerId2 = $manager2->getId(); + $this->managerId = $manager->getId(); + $this->managerId2 = $manager2->getId(); $this->contractId1 = $contract1->getId(); $this->contractId2 = $contract2->getId(); } - private function useCompletedContractFilter() + private function useCompletedContractFilter(): void { $conf = $this->_em->getConfiguration(); - $conf->addFilter("completed_contract", "\Doctrine\Tests\ORM\Functional\CompletedContractFilter"); + $conf->addFilter('completed_contract', '\Doctrine\Tests\ORM\Functional\CompletedContractFilter'); $this->_em->getFilters() - ->enable("completed_contract") - ->setParameter("completed", true, DBALType::BOOLEAN); + ->enable('completed_contract') + ->setParameter('completed', true, DBALType::BOOLEAN); } - public function testManyToMany_ExtraLazyCountWithFilterOnSTI() + public function testManyToMany_ExtraLazyCountWithFilterOnSTI(): void { $this->loadCompanySingleTableInheritanceFixtureData(); @@ -853,11 +857,11 @@ public function testManyToMany_ExtraLazyCountWithFilterOnSTI() $this->assertEquals(2, count($manager->managedContracts)); } - public function testManyToMany_ExtraLazyContainsWithFilterOnSTI() + public function testManyToMany_ExtraLazyContainsWithFilterOnSTI(): void { $this->loadCompanySingleTableInheritanceFixtureData(); - $manager = $this->_em->find(CompanyManager::class, $this->managerId); + $manager = $this->_em->find(CompanyManager::class, $this->managerId); $contract1 = $this->_em->find(CompanyContract::class, $this->contractId1); $contract2 = $this->_em->find(CompanyContract::class, $this->contractId2); @@ -873,7 +877,7 @@ public function testManyToMany_ExtraLazyContainsWithFilterOnSTI() $this->assertTrue($manager->managedContracts->contains($contract2)); } - public function testManyToMany_ExtraLazySliceWithFilterOnSTI() + public function testManyToMany_ExtraLazySliceWithFilterOnSTI(): void { $this->loadCompanySingleTableInheritanceFixtureData(); @@ -889,17 +893,17 @@ public function testManyToMany_ExtraLazySliceWithFilterOnSTI() $this->assertEquals(2, count($manager->managedContracts->slice(0, 10))); } - private function usePersonNameFilter($name) + private function usePersonNameFilter($name): void { // Enable the filter $conf = $this->_em->getConfiguration(); - $conf->addFilter("person_name", "\Doctrine\Tests\ORM\Functional\CompanyPersonNameFilter"); + $conf->addFilter('person_name', '\Doctrine\Tests\ORM\Functional\CompanyPersonNameFilter'); $this->_em->getFilters() - ->enable("person_name") - ->setParameter("name", $name, DBALType::STRING); + ->enable('person_name') + ->setParameter('name', $name, DBALType::STRING); } - public function testManyToMany_ExtraLazyCountWithFilterOnCTI() + public function testManyToMany_ExtraLazyCountWithFilterOnCTI(): void { $this->loadCompanySingleTableInheritanceFixtureData(); @@ -915,7 +919,7 @@ public function testManyToMany_ExtraLazyCountWithFilterOnCTI() $this->assertEquals(1, count($contract->managers)); } - public function testManyToMany_ExtraLazyContainsWithFilterOnCTI() + public function testManyToMany_ExtraLazyContainsWithFilterOnCTI(): void { $this->loadCompanySingleTableInheritanceFixtureData(); @@ -935,7 +939,7 @@ public function testManyToMany_ExtraLazyContainsWithFilterOnCTI() $this->assertTrue($contract->managers->contains($manager2)); } - public function testManyToMany_ExtraLazySliceWithFilterOnCTI() + public function testManyToMany_ExtraLazySliceWithFilterOnCTI(): void { $this->loadCompanySingleTableInheritanceFixtureData(); @@ -951,7 +955,7 @@ public function testManyToMany_ExtraLazySliceWithFilterOnCTI() $this->assertEquals(1, count($contract->managers->slice(0, 10))); } - public function testOneToMany_ExtraLazyCountWithFilterOnSTI() + public function testOneToMany_ExtraLazyCountWithFilterOnSTI(): void { $this->loadCompanySingleTableInheritanceFixtureData(); @@ -967,11 +971,11 @@ public function testOneToMany_ExtraLazyCountWithFilterOnSTI() $this->assertEquals(1, count($manager->soldContracts)); } - public function testOneToMany_ExtraLazyContainsWithFilterOnSTI() + public function testOneToMany_ExtraLazyContainsWithFilterOnSTI(): void { $this->loadCompanySingleTableInheritanceFixtureData(); - $manager = $this->_em->find(CompanyManager::class, $this->managerId); + $manager = $this->_em->find(CompanyManager::class, $this->managerId); $contract1 = $this->_em->find(CompanyContract::class, $this->contractId1); $contract2 = $this->_em->find(CompanyContract::class, $this->contractId2); @@ -987,9 +991,8 @@ public function testOneToMany_ExtraLazyContainsWithFilterOnSTI() $this->assertTrue($manager->soldContracts->contains($contract2)); } - public function testOneToMany_ExtraLazySliceWithFilterOnSTI() + public function testOneToMany_ExtraLazySliceWithFilterOnSTI(): void { - $this->loadCompanySingleTableInheritanceFixtureData(); $manager = $this->_em->find(CompanyManager::class, $this->managerId); @@ -1003,14 +1006,15 @@ public function testOneToMany_ExtraLazySliceWithFilterOnSTI() $this->assertFalse($manager->soldContracts->isInitialized()); $this->assertEquals(1, count($manager->soldContracts->slice(0, 10))); } - private function loadCompanyOrganizationEventJoinedSubclassFixtureData() + + private function loadCompanyOrganizationEventJoinedSubclassFixtureData(): void { - $organization = new CompanyOrganization; + $organization = new CompanyOrganization(); - $event1 = new CompanyAuction; + $event1 = new CompanyAuction(); $event1->setData('foo'); - $event2 = new CompanyAuction; + $event2 = new CompanyAuction(); $event2->setData('bar'); $organization->addEvent($event1); @@ -1021,22 +1025,21 @@ private function loadCompanyOrganizationEventJoinedSubclassFixtureData() $this->_em->clear(); $this->organizationId = $organization->getId(); - $this->eventId1 = $event1->getId(); - $this->eventId2 = $event2->getId(); + $this->eventId1 = $event1->getId(); + $this->eventId2 = $event2->getId(); } - private function useCompanyEventIdFilter() + private function useCompanyEventIdFilter(): void { // Enable the filter $conf = $this->_em->getConfiguration(); - $conf->addFilter("event_id", CompanyEventFilter::class); + $conf->addFilter('event_id', CompanyEventFilter::class); $this->_em->getFilters() - ->enable("event_id") - ->setParameter("id", $this->eventId2); + ->enable('event_id') + ->setParameter('id', $this->eventId2); } - - public function testOneToMany_ExtraLazyCountWithFilterOnCTI() + public function testOneToMany_ExtraLazyCountWithFilterOnCTI(): void { $this->loadCompanyOrganizationEventJoinedSubclassFixtureData(); @@ -1052,7 +1055,7 @@ public function testOneToMany_ExtraLazyCountWithFilterOnCTI() $this->assertEquals(1, count($organization->events)); } - public function testOneToMany_ExtraLazyContainsWithFilterOnCTI() + public function testOneToMany_ExtraLazyContainsWithFilterOnCTI(): void { $this->loadCompanyOrganizationEventJoinedSubclassFixtureData(); @@ -1073,7 +1076,7 @@ public function testOneToMany_ExtraLazyContainsWithFilterOnCTI() $this->assertTrue($organization->events->contains($event2)); } - public function testOneToMany_ExtraLazySliceWithFilterOnCTI() + public function testOneToMany_ExtraLazySliceWithFilterOnCTI(): void { $this->loadCompanyOrganizationEventJoinedSubclassFixtureData(); @@ -1094,11 +1097,11 @@ class MySoftDeleteFilter extends SQLFilter { public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias) { - if ($targetEntity->name != "MyEntity\SoftDeleteNewsItem") { - return ""; + if ($targetEntity->name !== 'MyEntity\SoftDeleteNewsItem') { + return ''; } - return $targetTableAlias.'.deleted = 0'; + return $targetTableAlias . '.deleted = 0'; } } @@ -1106,11 +1109,11 @@ class MyLocaleFilter extends SQLFilter { public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias) { - if (!in_array("LocaleAware", $targetEntity->reflClass->getInterfaceNames())) { - return ""; + if (! in_array('LocaleAware', $targetEntity->reflClass->getInterfaceNames())) { + return ''; } - return $targetTableAlias.'.locale = ' . $this->getParameter('locale'); // getParam uses connection to quote the value. + return $targetTableAlias . '.locale = ' . $this->getParameter('locale'); // getParam uses connection to quote the value. } } @@ -1118,11 +1121,11 @@ class CMSCountryFilter extends SQLFilter { public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias) { - if ($targetEntity->name != CmsAddress::class) { - return ""; + if ($targetEntity->name !== CmsAddress::class) { + return ''; } - return $targetTableAlias.'.country = ' . $this->getParameter('country'); // getParam uses connection to quote the value. + return $targetTableAlias . '.country = ' . $this->getParameter('country'); // getParam uses connection to quote the value. } } @@ -1130,11 +1133,11 @@ class CMSGroupPrefixFilter extends SQLFilter { public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias) { - if ($targetEntity->name != CmsGroup::class) { - return ""; + if ($targetEntity->name !== CmsGroup::class) { + return ''; } - return $targetTableAlias.'.name LIKE ' . $this->getParameter('prefix'); // getParam uses connection to quote the value. + return $targetTableAlias . '.name LIKE ' . $this->getParameter('prefix'); // getParam uses connection to quote the value. } } @@ -1142,11 +1145,11 @@ class CMSArticleTopicFilter extends SQLFilter { public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias) { - if ($targetEntity->name != CmsArticle::class) { - return ""; + if ($targetEntity->name !== CmsArticle::class) { + return ''; } - return $targetTableAlias.'.topic = ' . $this->getParameter('topic'); // getParam uses connection to quote the value. + return $targetTableAlias . '.topic = ' . $this->getParameter('topic'); // getParam uses connection to quote the value. } } @@ -1154,11 +1157,11 @@ class CompanyPersonNameFilter extends SQLFilter { public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias, $targetTable = '') { - if ($targetEntity->name != CompanyPerson::class) { - return ""; + if ($targetEntity->name !== CompanyPerson::class) { + return ''; } - return $targetTableAlias.'.name LIKE ' . $this->getParameter('name'); + return $targetTableAlias . '.name LIKE ' . $this->getParameter('name'); } } @@ -1166,11 +1169,11 @@ class CompletedContractFilter extends SQLFilter { public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias, $targetTable = '') { - if ($targetEntity->name != CompanyContract::class) { - return ""; + if ($targetEntity->name !== CompanyContract::class) { + return ''; } - return $targetTableAlias.'.completed = ' . $this->getParameter('completed'); + return $targetTableAlias . '.completed = ' . $this->getParameter('completed'); } } @@ -1178,10 +1181,10 @@ class CompanyEventFilter extends SQLFilter { public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias, $targetTable = '') { - if ($targetEntity->name != CompanyEvent::class) { - return ""; + if ($targetEntity->name !== CompanyEvent::class) { + return ''; } - return $targetTableAlias.'.id = ' . $this->getParameter('id'); + return $targetTableAlias . '.id = ' . $this->getParameter('id'); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/CompanySchemaTest.php b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/CompanySchemaTest.php index 614c7c29a96..018c2d8b39e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/CompanySchemaTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/CompanySchemaTest.php @@ -1,19 +1,21 @@ useModelSet('company'); parent::setUp(); @@ -21,9 +23,8 @@ protected function setUp() : void /** * @group DDC-966 - * @return Schema */ - public function testGeneratedSchema() + public function testGeneratedSchema(): Schema { $schema = $this->_em->getConnection()->getSchemaManager()->createSchema(); @@ -36,7 +37,7 @@ public function testGeneratedSchema() * @group DDC-966 * @depends testGeneratedSchema */ - public function testSingleTableInheritance(Schema $schema) + public function testSingleTableInheritance(Schema $schema): void { $table = $schema->getTable('company_contracts'); @@ -54,15 +55,15 @@ public function testSingleTableInheritance(Schema $schema) /** * @group DBAL-115 */ - public function testDropPartSchemaWithForeignKeys() + public function testDropPartSchemaWithForeignKeys(): void { - if (!$this->_em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { - $this->markTestSkipped("Foreign Key test"); + if (! $this->_em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { + $this->markTestSkipped('Foreign Key test'); } $sql = $this->_schemaTool->getDropSchemaSQL( [ - $this->_em->getClassMetadata(CompanyManager::class), + $this->_em->getClassMetadata(CompanyManager::class), ] ); $this->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 9fe5c602f7a..c1b3f969628 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/DBAL483Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/DBAL483Test.php @@ -1,13 +1,19 @@ _em->getClassMetadata(DBAL483Default::class); @@ -27,7 +33,7 @@ public function testDefaultValueIsComparedCorrectly() $updateSql = $this->schemaTool->getUpdateSchemaSql([$class]); - $updateSql = array_filter($updateSql, function ($sql) { + $updateSql = array_filter($updateSql, static function ($sql) { return strpos($sql, 'DBAL483') !== false; }); @@ -40,18 +46,12 @@ public function testDefaultValueIsComparedCorrectly() */ class DBAL483Default { - /** - * @Id @Column(type="integer") @GeneratedValue - */ + /** @Id @Column(type="integer") @GeneratedValue */ public $id; - /** - * @Column(type="integer", options={"default": 0}) - */ + /** @Column(type="integer", options={"default": 0}) */ public $num; - /** - * @Column(type="string", options={"default": "foo"}) - */ - public $str = "foo"; + /** @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 d38fcb51b45..5d2a43be1c2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/DDC214Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/DDC214Test.php @@ -1,36 +1,47 @@ _em->getConnection(); - if (strpos($conn->getDriver()->getName(), "sqlite") !== false) { + if (strpos($conn->getDriver()->getName(), 'sqlite') !== false) { $this->markTestSkipped('SQLite does not support ALTER TABLE statements.'); } + $this->schemaTool = new Tools\SchemaTool($this->_em); } /** * @group DDC-214 */ - public function testCmsAddressModel() + public function testCmsAddressModel(): void { $this->classes = [ Models\CMS\CmsUser::class, @@ -47,7 +58,7 @@ public function testCmsAddressModel() /** * @group DDC-214 */ - public function testCompanyModel() + public function testCompanyModel(): void { $this->classes = [ Models\Company\CompanyPerson::class, @@ -57,36 +68,38 @@ public function testCompanyModel() Models\Company\CompanyEvent::class, Models\Company\CompanyAuction::class, Models\Company\CompanyRaffle::class, - Models\Company\CompanyCar::class + Models\Company\CompanyCar::class, ]; $this->assertCreatedSchemaNeedsNoUpdates($this->classes); } - public function assertCreatedSchemaNeedsNoUpdates($classes) + public function assertCreatedSchemaNeedsNoUpdates($classes): void { $classMetadata = []; - foreach ($classes AS $class) { + foreach ($classes as $class) { $classMetadata[] = $this->_em->getClassMetadata($class); } try { $this->schemaTool->createSchema($classMetadata); - } catch(\Exception $e) { + } catch (Exception $e) { // was already created } $sm = $this->_em->getConnection()->getSchemaManager(); $fromSchema = $sm->createSchema(); - $toSchema = $this->schemaTool->getSchemaFromMetadata($classMetadata); + $toSchema = $this->schemaTool->getSchemaFromMetadata($classMetadata); $comparator = new Comparator(); $schemaDiff = $comparator->compare($fromSchema, $toSchema); $sql = $schemaDiff->toSql($this->_em->getConnection()->getDatabasePlatform()); - $sql = array_filter($sql, function($sql) { return strpos($sql, 'DROP') === false; }); + $sql = array_filter($sql, static function ($sql) { + return strpos($sql, 'DROP') === false; + }); - $this->assertEquals(0, count($sql), "SQL: " . implode(PHP_EOL, $sql)); + $this->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 3a1578e28cb..032835fd281 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/MySqlSchemaToolTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/MySqlSchemaToolTest.php @@ -1,24 +1,28 @@ _em->getConnection()->getDatabasePlatform()->getName() !== 'mysql') { - $this->markTestSkipped('The ' . __CLASS__ .' requires the use of mysql.'); + $this->markTestSkipped('The ' . self::class . ' requires the use of mysql.'); } } - public function testGetCreateSchemaSql() + public function testGetCreateSchemaSql(): void { $classes = [ $this->_em->getClassMetadata(Models\CMS\CmsGroup::class), @@ -29,8 +33,8 @@ public function testGetCreateSchemaSql() $this->_em->getClassMetadata(Models\CMS\CmsPhonenumber::class), ]; - $tool = new SchemaTool($this->_em); - $sql = $tool->getCreateSchemaSql($classes); + $tool = new SchemaTool($this->_em); + $sql = $tool->getCreateSchemaSql($classes); $collation = $this->getColumnCollationDeclarationSQL('utf8_unicode_ci'); $this->assertEquals('CREATE TABLE cms_groups (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 ' . $collation . ' ENGINE = InnoDB', $sql[0]); @@ -41,18 +45,18 @@ public function testGetCreateSchemaSql() $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 ' . $collation . ' 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 ' . $collation . ' 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 ' . $collation . ' 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('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)); } - private function getColumnCollationDeclarationSQL(string $collation) : string + private function getColumnCollationDeclarationSQL(string $collation): string { if (method_exists($this->_em->getConnection()->getDatabasePlatform(), 'getColumnCollationDeclarationSQL')) { return $this->_em->getConnection()->getDatabasePlatform()->getColumnCollationDeclarationSQL($collation); @@ -61,28 +65,24 @@ private function getColumnCollationDeclarationSQL(string $collation) : string return sprintf('COLLATE %s', $collation); } - public function testGetCreateSchemaSql2() + public function testGetCreateSchemaSql2(): void { - $classes = [ - $this->_em->getClassMetadata(Models\Generic\DecimalModel::class) - ]; + $classes = [$this->_em->getClassMetadata(Models\Generic\DecimalModel::class)]; - $tool = new SchemaTool($this->_em); - $sql = $tool->getCreateSchemaSql($classes); + $tool = new SchemaTool($this->_em); + $sql = $tool->getCreateSchemaSql($classes); $collation = $this->getColumnCollationDeclarationSQL('utf8_unicode_ci'); $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 ' . $collation . ' ENGINE = InnoDB', $sql[0]); } - public function testGetCreateSchemaSql3() + public function testGetCreateSchemaSql3(): void { - $classes = [ - $this->_em->getClassMetadata(Models\Generic\BooleanModel::class) - ]; + $classes = [$this->_em->getClassMetadata(Models\Generic\BooleanModel::class)]; - $tool = new SchemaTool($this->_em); - $sql = $tool->getCreateSchemaSql($classes); + $tool = new SchemaTool($this->_em); + $sql = $tool->getCreateSchemaSql($classes); $collation = $this->getColumnCollationDeclarationSQL('utf8_unicode_ci'); $this->assertEquals(1, count($sql)); @@ -92,18 +92,15 @@ public function testGetCreateSchemaSql3() /** * @group DBAL-204 */ - public function testGetCreateSchemaSql4() + public function testGetCreateSchemaSql4(): void { - $classes = [ - $this->_em->getClassMetadata(MysqlSchemaNamespacedEntity::class) - ]; + $classes = [$this->_em->getClassMetadata(MysqlSchemaNamespacedEntity::class)]; $tool = new SchemaTool($this->_em); - $sql = $tool->getCreateSchemaSql($classes); + $sql = $tool->getCreateSchemaSql($classes); $this->assertEquals(0, count($sql)); } - } /** @@ -115,4 +112,3 @@ class MysqlSchemaNamespacedEntity /** @Column(type="integer") @Id @GeneratedValue */ public $id; } - diff --git a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/PostgreSqlSchemaToolTest.php b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/PostgreSqlSchemaToolTest.php index b1ba7d10f3a..eb5db57593a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/PostgreSqlSchemaToolTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/PostgreSqlSchemaToolTest.php @@ -1,30 +1,38 @@ _em->getConnection()->getDatabasePlatform()->getName() !== 'postgresql') { - $this->markTestSkipped('The ' . __CLASS__ .' requires the use of postgresql.'); + $this->markTestSkipped('The ' . self::class . ' requires the use of postgresql.'); } } - public function testPostgresMetadataSequenceIncrementedBy10() + public function testPostgresMetadataSequenceIncrementedBy10(): void { $address = $this->_em->getClassMetadata(Models\CMS\CmsAddress::class); $this->assertEquals(1, $address->sequenceGeneratorDefinition['allocationSize']); } - public function testGetCreateSchemaSql() + public function testGetCreateSchemaSql(): void { $classes = [ $this->_em->getClassMetadata(Models\CMS\CmsAddress::class), @@ -32,67 +40,63 @@ public function testGetCreateSchemaSql() $this->_em->getClassMetadata(Models\CMS\CmsPhonenumber::class), ]; - $tool = new SchemaTool($this->_em); - $sql = $tool->getCreateSchemaSql($classes); + $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"); + $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'); } - public function testGetCreateSchemaSql2() + public function testGetCreateSchemaSql2(): void { - $classes = [ - $this->_em->getClassMetadata(Models\Generic\DecimalModel::class) - ]; + $classes = [$this->_em->getClassMetadata(Models\Generic\DecimalModel::class)]; $tool = new SchemaTool($this->_em); - $sql = $tool->getCreateSchemaSql($classes); + $sql = $tool->getCreateSchemaSql($classes); $this->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]); + $this->assertEquals('CREATE SEQUENCE decimal_model_id_seq INCREMENT BY 1 MINVALUE 1 START 1', $sql[1]); } - public function testGetCreateSchemaSql3() + public function testGetCreateSchemaSql3(): void { - $classes = [ - $this->_em->getClassMetadata(Models\Generic\BooleanModel::class) - ]; + $classes = [$this->_em->getClassMetadata(Models\Generic\BooleanModel::class)]; $tool = new SchemaTool($this->_em); - $sql = $tool->getCreateSchemaSql($classes); + $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]); + $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]); } - public function testGetDropSchemaSql() + public function testGetDropSchemaSql(): void { $classes = [ $this->_em->getClassMetadata(Models\CMS\CmsAddress::class), @@ -101,24 +105,25 @@ public function testGetDropSchemaSql() ]; $tool = new SchemaTool($this->_em); - $sql = $tool->getDropSchemaSQL($classes); + $sql = $tool->getDropSchemaSQL($classes); $this->assertEquals(17, count($sql)); $dropSequenceSQLs = 0; - foreach ($sql AS $stmt) { - if (strpos($stmt, "DROP SEQUENCE") === 0) { + foreach ($sql as $stmt) { + if (strpos($stmt, 'DROP SEQUENCE') === 0) { $dropSequenceSQLs++; } } - $this->assertEquals(4, $dropSequenceSQLs, "Expect 4 sequences to be dropped."); + + $this->assertEquals(4, $dropSequenceSQLs, 'Expect 4 sequences to be dropped.'); } /** * @group DDC-1657 */ - public function testUpdateSchemaWithPostgreSQLSchema() + public function testUpdateSchemaWithPostgreSQLSchema(): void { $classes = [ $this->_em->getClassMetadata(DDC1657Screen::class), @@ -129,7 +134,9 @@ public function testUpdateSchemaWithPostgreSQLSchema() $tool->createSchema($classes); $sql = $tool->getUpdateSchemaSql($classes); - $sql = array_filter($sql, function($sql) { return (strpos($sql, "DROP SEQUENCE stonewood.") === 0); }); + $sql = array_filter($sql, static function ($sql) { + return strpos($sql, 'DROP SEQUENCE stonewood.') === 0; + }); $this->assertCount(0, $sql, implode("\n", $sql)); } @@ -143,8 +150,8 @@ class DDC1657Screen { /** * Identifier - * @var int * + * @var int * @Id * @GeneratedValue(strategy="IDENTITY") * @Column(name="pk", type="integer", nullable=false) @@ -153,32 +160,32 @@ class DDC1657Screen /** * Title - * @var string * + * @var string * @Column(name="title", type="string", length=255, nullable=false) */ private $title; /** * Path - * @var string * + * @var string * @Column(name="path", type="string", length=255, nullable=false) */ private $path; /** * Register date - * @var Date * + * @var Date * @Column(name="ddate", type="date", nullable=false) */ private $ddate; /** * Avatar - * @var Stonewood\Model\Entity\Avatar * + * @var Stonewood\Model\Entity\Avatar * @ManyToOne(targetEntity="DDC1657Avatar") * @JoinColumn(name="pk_avatar", referencedColumnName="pk", nullable=true, onDelete="CASCADE") */ @@ -193,8 +200,8 @@ class DDC1657Avatar { /** * Identifier - * @var int * + * @var int * @Id * @GeneratedValue(strategy="IDENTITY") * @Column(name="pk", type="integer", nullable=false) diff --git a/tests/Doctrine/Tests/ORM/Functional/SchemaValidatorTest.php b/tests/Doctrine/Tests/ORM/Functional/SchemaValidatorTest.php index 14032646b2b..8785165b8c2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SchemaValidatorTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SchemaValidatorTest.php @@ -1,13 +1,20 @@ registerType(CustomIdObjectType::class); $this->registerType(UpperCaseStringType::class); @@ -26,18 +33,15 @@ protected function setUp() : void } /** - * @param string $className - * - * @throws \Doctrine\DBAL\DBALException - * - * @return void + * @throws DBALException */ - private function registerType(string $className) + private function registerType(string $className): void { $type = constant($className . '::NAME'); if (DBALType::hasType($type)) { DBALType::overrideType($type, $className); + return; } @@ -58,7 +62,7 @@ public static function dataValidateModelSets(): array /** * @dataProvider dataValidateModelSets */ - public function testValidateModelSets(string $modelSet) + public function testValidateModelSets(string $modelSet): void { $validator = new SchemaValidator($this->_em); $classes = []; @@ -70,7 +74,7 @@ public function testValidateModelSets(string $modelSet) foreach ($classes as $class) { $ce = $validator->validateClass($class); - $this->assertEmpty($ce, "Invalid Modelset: " . $modelSet . " class " . $class->name . ": ". implode("\n", $ce)); + $this->assertEmpty($ce, 'Invalid Modelset: ' . $modelSet . ' class ' . $class->name . ': ' . implode("\n", $ce)); } } } diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheAbstractTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheAbstractTest.php index e6ed7d79740..6e43bd8b263 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheAbstractTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheAbstractTest.php @@ -1,26 +1,25 @@ enableSecondLevelCache(); @@ -54,10 +51,10 @@ protected function setUp() : void $this->cache = $this->_em->getCache(); } - protected function loadFixturesCountries() + protected function loadFixturesCountries(): void { - $brazil = new Country("Brazil"); - $germany = new Country("Germany"); + $brazil = new Country('Brazil'); + $germany = new Country('Germany'); $this->countries[] = $brazil; $this->countries[] = $germany; @@ -67,12 +64,12 @@ protected function loadFixturesCountries() $this->_em->flush(); } - protected function loadFixturesStates() + protected function loadFixturesStates(): void { - $saopaulo = new State("São Paulo", $this->countries[0]); - $rio = new State("Rio de janeiro", $this->countries[0]); - $berlin = new State("Berlin", $this->countries[1]); - $bavaria = new State("Bavaria", $this->countries[1]); + $saopaulo = new State('São Paulo', $this->countries[0]); + $rio = new State('Rio de janeiro', $this->countries[0]); + $berlin = new State('Berlin', $this->countries[1]); + $bavaria = new State('Bavaria', $this->countries[1]); $this->states[] = $saopaulo; $this->states[] = $rio; @@ -87,12 +84,12 @@ protected function loadFixturesStates() $this->_em->flush(); } - protected function loadFixturesCities() + protected function loadFixturesCities(): void { - $saopaulo = new City("São Paulo", $this->states[0]); - $rio = new City("Rio de janeiro", $this->states[0]); - $berlin = new City("Berlin", $this->states[1]); - $munich = new City("Munich", $this->states[1]); + $saopaulo = new City('São Paulo', $this->states[0]); + $rio = new City('Rio de janeiro', $this->states[0]); + $berlin = new City('Berlin', $this->states[1]); + $munich = new City('Munich', $this->states[1]); $this->states[0]->addCity($saopaulo); $this->states[0]->addCity($rio); @@ -112,10 +109,10 @@ protected function loadFixturesCities() $this->_em->flush(); } - protected function loadFixturesTraveler() + protected function loadFixturesTraveler(): void { - $t1 = new Traveler("Fabio Silva"); - $t2 = new Traveler("Doctrine Bot"); + $t1 = new Traveler('Fabio Silva'); + $t2 = new Traveler('Doctrine Bot'); $this->_em->persist($t1); $this->_em->persist($t2); @@ -126,12 +123,12 @@ protected function loadFixturesTraveler() $this->_em->flush(); } - protected function loadFixturesTravelersWithProfile() + protected function loadFixturesTravelersWithProfile(): void { - $t1 = new Traveler("Test traveler 1"); - $t2 = new Traveler("Test traveler 2"); - $p1 = new TravelerProfile("First Traveler Profile"); - $p2 = new TravelerProfile("Second Traveler Profile"); + $t1 = new Traveler('Test traveler 1'); + $t2 = new Traveler('Test traveler 2'); + $p1 = new TravelerProfile('First Traveler Profile'); + $p2 = new TravelerProfile('Second Traveler Profile'); $t1->setProfile($p1); $t2->setProfile($p2); @@ -147,12 +144,12 @@ protected function loadFixturesTravelersWithProfile() $this->_em->flush(); } - protected function loadFixturesTravelersProfileInfo() + protected function loadFixturesTravelersProfileInfo(): void { - $p1 = $this->travelersWithProfile[0]->getProfile(); - $p2 = $this->travelersWithProfile[1]->getProfile(); - $i1 = new TravelerProfileInfo($p1, "First Profile Info ..."); - $i2 = new TravelerProfileInfo($p2, "Second Profile Info ..."); + $p1 = $this->travelersWithProfile[0]->getProfile(); + $p2 = $this->travelersWithProfile[1]->getProfile(); + $i1 = new TravelerProfileInfo($p1, 'First Profile Info ...'); + $i2 = new TravelerProfileInfo($p2, 'Second Profile Info ...'); $p1->setInfo($i1); $p2->setInfo($i2); @@ -165,11 +162,11 @@ protected function loadFixturesTravelersProfileInfo() $this->_em->flush(); } - protected function loadFixturesTravels() + protected function loadFixturesTravels(): void { - $t1 = new Travel($this->travelers[0]); - $t2 = new Travel($this->travelers[1]); - $t3 = new Travel($this->travelers[1]); + $t1 = new Travel($this->travelers[0]); + $t2 = new Travel($this->travelers[1]); + $t3 = new Travel($this->travelers[1]); $t1->addVisitedCity($this->cities[0]); $t1->addVisitedCity($this->cities[1]); @@ -189,7 +186,7 @@ protected function loadFixturesTravels() $this->_em->flush(); } - protected function loadFixturesAttractions() + protected function loadFixturesAttractions(): void { $this->attractions[] = new Bar('Boteco São Bento', $this->cities[0]); $this->attractions[] = new Bar('Prainha Paulista', $this->cities[0]); @@ -214,7 +211,7 @@ protected function loadFixturesAttractions() $this->_em->flush(); } - protected function loadFixturesAttractionsInfo() + protected function loadFixturesAttractionsInfo(): void { $this->attractionsInfo[] = new AttractionContactInfo('0000-0000', $this->attractions[0]); $this->attractionsInfo[] = new AttractionContactInfo('1111-1111', $this->attractions[1]); @@ -228,7 +225,7 @@ protected function loadFixturesAttractionsInfo() $this->_em->flush(); } - protected function loadFixturesPersonWithAddress() + protected function loadFixturesPersonWithAddress(): void { $person1 = new Person('Guilherme Blanco'); $address1 = new Address('Canada'); @@ -274,7 +271,7 @@ protected function getDefaultQueryRegionName() return $this->cache->getQueryCache()->getRegion()->getName(); } - protected function evictRegions() + protected function evictRegions(): void { $this->cache->evictQueryRegions(); $this->cache->evictEntityRegions(); diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCompositePrimaryKeyTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCompositePrimaryKeyTest.php index 9dff7df1d1c..95855ff499c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCompositePrimaryKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCompositePrimaryKeyTest.php @@ -1,7 +1,10 @@ loadFixturesCountries(); $this->loadFixturesStates(); @@ -19,17 +22,17 @@ public function testPutAndLoadCompositPrimaryKeyEntities() $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); - $flight = new Flight($leavingFrom, $goingTo); - $id = [ + $leavingFromId = $this->cities[0]->getId(); + $goingToId = $this->cities[1]->getId(); + $leavingFrom = $this->_em->find(City::class, $leavingFromId); + $goingTo = $this->_em->find(City::class, $goingToId); + $flight = new Flight($leavingFrom, $goingTo); + $id = [ 'leavingFrom' => $leavingFromId, 'goingTo' => $goingToId, ]; - $flight->setDeparture(new \DateTime('tomorrow')); + $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())); @@ -56,7 +59,7 @@ public function testPutAndLoadCompositPrimaryKeyEntities() $this->assertEquals($queryCount, $this->getCurrentQueryCount()); } - public function testRemoveCompositPrimaryKeyEntities() + public function testRemoveCompositPrimaryKeyEntities(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -65,17 +68,17 @@ public function testRemoveCompositPrimaryKeyEntities() $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); - $flight = new Flight($leavingFrom, $goingTo); - $id = [ + $leavingFromId = $this->cities[0]->getId(); + $goingToId = $this->cities[1]->getId(); + $leavingFrom = $this->_em->find(City::class, $leavingFromId); + $goingTo = $this->_em->find(City::class, $goingToId); + $flight = new Flight($leavingFrom, $goingTo); + $id = [ 'leavingFrom' => $leavingFromId, 'goingTo' => $goingToId, ]; - $flight->setDeparture(new \DateTime('tomorrow')); + $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())); @@ -98,7 +101,7 @@ public function testRemoveCompositPrimaryKeyEntities() $this->assertNull($this->_em->find(Flight::class, $id)); } - public function testUpdateCompositPrimaryKeyEntities() + public function testUpdateCompositPrimaryKeyEntities(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -107,14 +110,14 @@ public function testUpdateCompositPrimaryKeyEntities() $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); - $flight = new Flight($leavingFrom, $goingTo); - $id = [ + $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); + $flight = new Flight($leavingFrom, $goingTo); + $id = [ 'leavingFrom' => $leavingFromId, 'goingTo' => $goingToId, ]; diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCompositePrimaryKeyWithAssociationsTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCompositePrimaryKeyWithAssociationsTest.php index 8cfb8245fe1..c8ce9e725b7 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCompositePrimaryKeyWithAssociationsTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCompositePrimaryKeyWithAssociationsTest.php @@ -1,21 +1,23 @@ enableSecondLevelCache(); $this->useModelSet('geonames'); @@ -23,18 +25,18 @@ protected function setUp() : void $this->cache = $this->_em->getCache(); - $it = new Country("IT", "Italy"); + $it = new Country('IT', 'Italy'); $this->_em->persist($it); $this->_em->flush(); - $admin1 = new Admin1(1, "Rome", $it); + $admin1 = new Admin1(1, 'Rome', $it); $this->_em->persist($admin1); $this->_em->flush(); - $name1 = new Admin1AlternateName(1, "Roma", $admin1); - $name2 = new Admin1AlternateName(2, "Rome", $admin1); + $name1 = new Admin1AlternateName(1, 'Roma', $admin1); + $name2 = new Admin1AlternateName(2, 'Rome', $admin1); $admin1->names[] = $name1; $admin1->names[] = $name2; @@ -46,10 +48,9 @@ protected function setUp() : void $this->_em->flush(); $this->_em->clear(); $this->evictRegions(); - } - public function testFindByReturnsCachedEntity() + public function testFindByReturnsCachedEntity(): void { $admin1Repo = $this->_em->getRepository(Admin1::class); @@ -57,7 +58,7 @@ public function testFindByReturnsCachedEntity() $admin1Rome = $admin1Repo->findOneBy(['country' => 'IT', 'id' => 1]); - $this->assertEquals("Italy", $admin1Rome->country->name); + $this->assertEquals('Italy', $admin1Rome->country->name); $this->assertEquals(2, count($admin1Rome->names)); $this->assertEquals($queries + 3, $this->getCurrentQueryCount()); @@ -67,12 +68,12 @@ public function testFindByReturnsCachedEntity() $admin1Rome = $admin1Repo->findOneBy(['country' => 'IT', 'id' => 1]); - $this->assertEquals("Italy", $admin1Rome->country->name); + $this->assertEquals('Italy', $admin1Rome->country->name); $this->assertEquals(2, count($admin1Rome->names)); $this->assertEquals($queries, $this->getCurrentQueryCount()); } - private function evictRegions() + private function evictRegions(): void { $this->cache->evictQueryRegions(); $this->cache->evictEntityRegions(); diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheConcurrentTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheConcurrentTest.php index cafd16a872f..139b5a58723 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheConcurrentTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheConcurrentTest.php @@ -1,32 +1,32 @@ enableSecondLevelCache(); parent::setUp(); @@ -45,25 +45,25 @@ protected function setUp() : void $this->_em->getMetadataFactory()->setMetadataFor(Country::class, $countryMetadata); } - protected function tearDown() : void + protected function tearDown(): void { parent::tearDown(); $this->_em->getMetadataFactory()->setMetadataFor(Country::class, $this->countryMetadata); } - public function testBasicConcurrentEntityReadLock() + public function testBasicConcurrentEntityReadLock(): void { $this->loadFixturesCountries(); $this->_em->clear(); $countryId = $this->countries[0]->getId(); - $cacheId = new EntityCacheKey(Country::class, ['id'=>$countryId]); + $cacheId = new EntityCacheKey(Country::class, ['id' => $countryId]); $region = $this->_em->getCache()->getEntityCacheRegion(Country::class); $this->assertTrue($this->cache->containsEntity(Country::class, $countryId)); - /** @var \Doctrine\Tests\Mocks\ConcurrentRegionMock */ + /** @var ConcurrentRegionMock */ $region->setLock($cacheId, Lock::createLockRead()); // another proc lock the entity cache $this->assertFalse($this->cache->containsEntity(Country::class, $countryId)); @@ -76,7 +76,7 @@ public function testBasicConcurrentEntityReadLock() $this->assertFalse($this->cache->containsEntity(Country::class, $countryId)); } - public function testBasicConcurrentCollectionReadLock() + public function testBasicConcurrentCollectionReadLock(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -85,8 +85,8 @@ public function testBasicConcurrentCollectionReadLock() $this->_em->clear(); $this->evictRegions(); - $stateId = $this->states[0]->getId(); - $state = $this->_em->find(State::class, $stateId); + $stateId = $this->states[0]->getId(); + $state = $this->_em->find(State::class, $stateId); $this->assertInstanceOf(State::class, $state); $this->assertInstanceOf(Country::class, $state->getCountry()); @@ -96,13 +96,13 @@ public function testBasicConcurrentCollectionReadLock() $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'); + $stateId = $this->states[0]->getId(); + $cacheId = new CollectionCacheKey(State::class, 'cities', ['id' => $stateId]); + $region = $this->_em->getCache()->getCollectionCacheRegion(State::class, 'cities'); $this->assertTrue($this->cache->containsCollection(State::class, 'cities', $stateId)); - /* @var $region \Doctrine\Tests\Mocks\ConcurrentRegionMock */ + /** @var ConcurrentRegionMock $region */ $region->setLock($cacheId, Lock::createLockRead()); // another proc lock the entity cache $this->assertFalse($this->cache->containsCollection(State::class, 'cities', $stateId)); @@ -138,9 +138,8 @@ public function __construct(Cache $cache) public function getRegion(array $cache) { $region = new DefaultRegion($cache['region'], $this->cache); - $mock = new ConcurrentRegionMock($region); - return $mock; + return new ConcurrentRegionMock($region); } public function getTimestampRegion() diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCriteriaTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCriteriaTest.php index 17d0ac7fc7e..8eb498c5900 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCriteriaTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCriteriaTest.php @@ -1,5 +1,7 @@ evictRegions(); @@ -53,7 +55,7 @@ public function testMatchingPut() $this->assertEquals($result1[0]->getName(), $result2[0]->getName()); } - public function testRepositoryMatching() + public function testRepositoryMatching(): void { $this->evictRegions(); @@ -121,7 +123,7 @@ public function testRepositoryMatching() $this->assertEquals($this->countries[1]->getName(), $result4[0]->getName()); } - public function testCollectionMatching() + public function testCollectionMatching(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -154,5 +156,4 @@ public function testCollectionMatching() $this->assertInstanceOf(Collection::class, $matching); $this->assertCount(1, $matching); } - } diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheExtraLazyCollectionTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheExtraLazyCollectionTest.php index 9f438d6bc26..1c634a266df 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheExtraLazyCollectionTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheExtraLazyCollectionTest.php @@ -1,18 +1,20 @@ associationMappings['travels']['fetch'] = ClassMetadata::FETCH_EXTRA_LAZY; } - public function tearDown() : void + public function tearDown(): void { parent::tearDown(); @@ -34,7 +36,7 @@ public function tearDown() : void $targetEntity->associationMappings['travels']['fetch'] = ClassMetadata::FETCH_LAZY; } - public function testCacheCountAfterAddThenFlush() + public function testCacheCountAfterAddThenFlush(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -44,14 +46,14 @@ public function testCacheCountAfterAddThenFlush() $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()); + $ownerId = $this->travels[0]->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)); - $newItem = new City("New City", $ref); + $newItem = new City('New City', $ref); $owner->getVisitedCities()->add($newItem); $this->_em->persist($newItem); diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheJoinTableInheritanceTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheJoinTableInheritanceTest.php index f9b9542444e..3bb2093d85f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheJoinTableInheritanceTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheJoinTableInheritanceTest.php @@ -1,5 +1,7 @@ cache->getEntityCacheRegion(AttractionInfo::class); $contactRegion = $this->cache->getEntityCacheRegion(AttractionContactInfo::class); @@ -23,7 +28,7 @@ public function testUseSameRegion() $this->assertEquals($infoRegion->getName(), $locationRegion->getName()); } - public function testPutOnPersistJoinTableInheritance() + public function testPutOnPersistJoinTableInheritance(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -39,7 +44,7 @@ public function testPutOnPersistJoinTableInheritance() $this->assertTrue($this->cache->containsEntity(AttractionInfo::class, $this->attractionsInfo[3]->getId())); } - public function testJoinTableCountaisRootClass() + public function testJoinTableCountaisRootClass(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -55,7 +60,7 @@ public function testJoinTableCountaisRootClass() } } - public function testPutAndLoadJoinTableEntities() + public function testPutAndLoadJoinTableEntities(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -120,7 +125,7 @@ public function testPutAndLoadJoinTableEntities() $this->assertEquals($entity2->getFone(), $entity4->getFone()); } - public function testQueryCacheFindAllJoinTableEntities() + public function testQueryCacheFindAllJoinTableEntities(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -153,7 +158,7 @@ public function testQueryCacheFindAllJoinTableEntities() } } - public function testOneToManyRelationJoinTable() + public function testOneToManyRelationJoinTable(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -190,7 +195,7 @@ public function testOneToManyRelationJoinTable() $this->assertEquals($this->attractionsInfo[0]->getFone(), $entity->getInfos()->get(0)->getFone()); } - public function testQueryCacheShouldBeEvictedOnTimestampUpdate() + public function testQueryCacheShouldBeEvictedOnTimestampUpdate(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -203,7 +208,7 @@ public function testQueryCacheShouldBeEvictedOnTimestampUpdate() $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(); diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheManyToManyTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheManyToManyTest.php index 35bed89efbb..98440dbf653 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheManyToManyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheManyToManyTest.php @@ -1,5 +1,7 @@ evictRegions(); @@ -35,7 +37,7 @@ public function testShouldPutManyToManyCollectionOwningSideOnPersist() $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[3]->getId())); } - public function testPutAndLoadManyToManyRelation() + public function testPutAndLoadManyToManyRelation(): void { $this->evictRegions(); @@ -145,7 +147,7 @@ public function testPutAndLoadManyToManyRelation() $this->assertEquals($queryCount, $this->getCurrentQueryCount()); } - public function testStoreManyToManyAssociationWhitCascade() + public function testStoreManyToManyAssociationWhitCascade(): void { $this->evictRegions(); @@ -159,8 +161,8 @@ public function testStoreManyToManyAssociationWhitCascade() $this->cache->evictCollectionRegion(State::class, 'cities'); $this->cache->evictCollectionRegion(Traveler::class, 'travels'); - $traveler = new Traveler('Doctrine Bot'); - $travel = new Travel($traveler); + $traveler = new Traveler('Doctrine Bot'); + $travel = new Travel($traveler); $travel->addVisitedCity($this->cities[0]); $travel->addVisitedCity($this->cities[1]); @@ -186,7 +188,7 @@ public function testStoreManyToManyAssociationWhitCascade() $this->assertEquals($queryCount1, $this->getCurrentQueryCount()); } - public function testReadOnlyCollection() + public function testReadOnlyCollection(): void { $this->expectException('Doctrine\ORM\Cache\CacheException'); $this->expectExceptionMessage('Cannot update a readonly collection "Doctrine\Tests\Models\Cache\Travel#visitedCities'); @@ -213,7 +215,7 @@ public function testReadOnlyCollection() $this->_em->flush(); } - public function testManyToManyWithEmptyRelation() + public function testManyToManyWithEmptyRelation(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -226,19 +228,18 @@ public function testManyToManyWithEmptyRelation() $queryCount = $this->getCurrentQueryCount(); - $entitiId = $this->travels[2]->getId(); //empty travel - $entity = $this->_em->find(Travel::class, $entitiId); + $entitiId = $this->travels[2]->getId(); //empty travel + $entity = $this->_em->find(Travel::class, $entitiId); $this->assertEquals(0, $entity->getVisitedCities()->count()); - $this->assertEquals($queryCount+2, $this->getCurrentQueryCount()); + $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); $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()); - } } diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheManyToOneTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheManyToOneTest.php index 7af52f741c2..3a0aec32660 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheManyToOneTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheManyToOneTest.php @@ -1,5 +1,7 @@ loadFixturesCountries(); $this->loadFixturesStates(); @@ -27,7 +29,7 @@ public function testPutOnPersist() $this->assertTrue($this->cache->containsEntity(State::class, $this->states[1]->getId())); } - public function testPutAndLoadManyToOneRelation() + public function testPutAndLoadManyToOneRelation(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -99,7 +101,7 @@ public function testPutAndLoadManyToOneRelation() $this->assertEquals($this->states[1]->getCountry()->getName(), $c4->getCountry()->getName()); } - public function testInverseSidePutShouldEvictCollection() + public function testInverseSidePutShouldEvictCollection(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -113,7 +115,7 @@ public function testInverseSidePutShouldEvictCollection() $c3 = $this->_em->find(State::class, $this->states[0]->getId()); $prev = $c3->getCities(); $count = $prev->count(); - $city = new City("Buenos Aires", $c3); + $city = new City('Buenos Aires', $c3); $c3->addCity($city); @@ -133,7 +135,7 @@ public function testInverseSidePutShouldEvictCollection() $this->assertEquals($queryCount, $this->getCurrentQueryCount()); } - public function testShouldNotReloadWhenAssociationIsMissing() + public function testShouldNotReloadWhenAssociationIsMissing(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -179,7 +181,7 @@ public function testShouldNotReloadWhenAssociationIsMissing() $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); } - public function testPutAndLoadNonCacheableManyToOne() + public function testPutAndLoadNonCacheableManyToOne(): void { $this->assertNull($this->cache->getEntityCacheRegion(Action::class)); $this->assertInstanceOf(Region::class, $this->cache->getEntityCacheRegion(Token::class)); @@ -197,7 +199,7 @@ public function testPutAndLoadNonCacheableManyToOne() $this->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); @@ -208,13 +210,13 @@ public function testPutAndLoadNonCacheableManyToOne() $this->assertEquals($queryCount, $this->getCurrentQueryCount()); } - public function testPutAndLoadNonCacheableCompositeManyToOne() + public function testPutAndLoadNonCacheableCompositeManyToOne(): void { $this->assertNull($this->cache->getEntityCacheRegion(Action::class)); $this->assertNull($this->cache->getEntityCacheRegion(ComplexAction::class)); $this->assertInstanceOf(Region::class, $this->cache->getEntityCacheRegion(Token::class)); - $token = new Token('token-hash'); + $token = new Token('token-hash'); $action1 = new Action('login'); $action2 = new Action('logout'); diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheOneToManyTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheOneToManyTest.php index 9f347cc5ba1..37eba62f7f3 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheOneToManyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheOneToManyTest.php @@ -1,5 +1,7 @@ loadFixturesCountries(); $this->loadFixturesStates(); @@ -29,7 +31,7 @@ public function testShouldPutCollectionInverseSideOnPersist() $this->assertTrue($this->cache->containsCollection(State::class, 'cities', $this->states[1]->getId())); } - public function testPutAndLoadOneToManyRelation() + public function testPutAndLoadOneToManyRelation(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -127,7 +129,7 @@ public function testPutAndLoadOneToManyRelation() $this->assertEquals($queryCount, $this->getCurrentQueryCount()); } - public function testLoadOneToManyCollectionFromDatabaseWhenEntityMissing() + public function testLoadOneToManyCollectionFromDatabaseWhenEntityMissing(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -167,13 +169,12 @@ public function testLoadOneToManyCollectionFromDatabaseWhenEntityMissing() $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } - - public function testShoudNotPutOneToManyRelationOnPersist() + public function testShoudNotPutOneToManyRelationOnPersist(): void { $this->loadFixturesCountries(); $this->evictRegions(); - $state = new State("State Foo", $this->countries[0]); + $state = new State('State Foo', $this->countries[0]); $this->_em->persist($state); $this->_em->flush(); @@ -183,7 +184,7 @@ public function testShoudNotPutOneToManyRelationOnPersist() $this->assertFalse($this->cache->containsCollection(State::class, 'cities', $state->getId())); } - public function testOneToManyRemove() + public function testOneToManyRemove(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -288,7 +289,7 @@ public function testOneToManyRemove() $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getCollectionRegion(State::class, 'cities'))); } - public function testOneToManyWithEmptyRelation() + public function testOneToManyWithEmptyRelation(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -314,10 +315,9 @@ public function testOneToManyWithEmptyRelation() $this->assertEquals(0, $entity->getCities()->count()); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - } - public function testOneToManyCount() + public function testOneToManyCount(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -345,13 +345,13 @@ public function testOneToManyCount() $this->assertEquals($queryCount, $this->getCurrentQueryCount()); } - public function testCacheInitializeCollectionWithNewObjects() + public function testCacheInitializeCollectionWithNewObjects(): void { $this->_em->clear(); $this->evictRegions(); - $traveler = new Traveler("Doctrine Bot"); + $traveler = new Traveler('Doctrine Bot'); for ($i = 0; $i < 3; ++$i) { $traveler->getTravels()->add(new Travel($traveler)); @@ -387,14 +387,14 @@ public function testCacheInitializeCollectionWithNewObjects() $this->assertEquals(4, $result->getTravels()->count()); } - public function testPutAndLoadNonCacheableOneToMany() + public function testPutAndLoadNonCacheableOneToMany(): void { $this->assertNull($this->cache->getEntityCacheRegion(Login::class)); $this->assertInstanceOf(Region::class, $this->cache->getEntityCacheRegion(Token::class)); - $l1 = new Login('session1'); - $l2 = new Login('session2'); - $token = new Token('token-hash'); + $l1 = new Login('session1'); + $l2 = new Login('session2'); + $token = new Token('token-hash'); $token->addLogin($l1); $token->addLogin($l2); diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheOneToOneTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheOneToOneTest.php index 6e428814d3f..68d270f99a7 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheOneToOneTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheOneToOneTest.php @@ -1,5 +1,7 @@ loadFixturesCountries(); $this->loadFixturesStates(); @@ -34,7 +36,7 @@ public function testPutOneToOneOnUnidirectionalPersist() $this->assertTrue($this->cache->containsEntity(TravelerProfile::class, $entity2->getProfile()->getId())); } - public function testPutOneToOneOnBidirectionalPersist() + public function testPutOneToOneOnBidirectionalPersist(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -55,7 +57,7 @@ public function testPutOneToOneOnBidirectionalPersist() $this->assertTrue($this->cache->containsEntity(TravelerProfileInfo::class, $entity2->getProfile()->getInfo()->getId())); } - public function testPutAndLoadOneToOneUnidirectionalRelation() + public function testPutAndLoadOneToOneUnidirectionalRelation(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -127,7 +129,7 @@ public function testPutAndLoadOneToOneUnidirectionalRelation() $this->assertEquals($queryCount, $this->getCurrentQueryCount()); } - public function testPutAndLoadOneToOneBidirectionalRelation() + public function testPutAndLoadOneToOneBidirectionalRelation(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -192,7 +194,7 @@ public function testPutAndLoadOneToOneBidirectionalRelation() $this->assertEquals($queryCount, $this->getCurrentQueryCount()); } - public function testInverseSidePutAndLoadOneToOneBidirectionalRelation() + public function testInverseSidePutAndLoadOneToOneBidirectionalRelation(): void { $this->loadFixturesPersonWithAddress(); @@ -253,7 +255,7 @@ public function testInverseSidePutAndLoadOneToOneBidirectionalRelation() $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); } - public function testPutAndLoadNonCacheableOneToOne() + public function testPutAndLoadNonCacheableOneToOne(): void { $this->assertNull($this->cache->getEntityCacheRegion(Client::class)); $this->assertInstanceOf(Region::class, $this->cache->getEntityCacheRegion(Token::class)); diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheQueryCacheTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheQueryCacheTest.php index 5e7ca59f3d6..049bee5b8c9 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheQueryCacheTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheQueryCacheTest.php @@ -1,5 +1,7 @@ evictRegions(); $this->loadFixturesCountries(); @@ -49,7 +52,7 @@ public function testBasicQueryCache() $this->_em->clear(); - $result2 = $this->_em->createQuery($dql) + $result2 = $this->_em->createQuery($dql) ->setCacheable(true) ->getResult(); @@ -82,7 +85,7 @@ public function testBasicQueryCache() $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); } - public function testQueryCacheModeGet() + public function testQueryCacheModeGet(): void { $this->evictRegions(); $this->loadFixturesCountries(); @@ -122,7 +125,7 @@ public function testQueryCacheModeGet() $this->assertEquals($queryCount + 3, $this->getCurrentQueryCount()); } - public function testQueryCacheModePut() + public function testQueryCacheModePut(): void { $this->evictRegions(); $this->loadFixturesCountries(); @@ -162,7 +165,7 @@ public function testQueryCacheModePut() $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); } - public function testQueryCacheModeRefresh() + public function testQueryCacheModeRefresh(): void { $this->evictRegions(); $this->loadFixturesCountries(); @@ -187,15 +190,15 @@ public function testQueryCacheModeRefresh() $this->assertCount(2, $result); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $countryId1 = $this->countries[0]->getId(); - $countryId2 = $this->countries[1]->getId(); - $countryName1 = $this->countries[0]->getName(); - $countryName2 = $this->countries[1]->getName(); + $countryId1 = $this->countries[0]->getId(); + $countryId2 = $this->countries[1]->getId(); + $countryName1 = $this->countries[0]->getName(); + $countryName2 = $this->countries[1]->getName(); - $key1 = new EntityCacheKey(Country::class, ['id'=>$countryId1]); - $key2 = new EntityCacheKey(Country::class, ['id'=>$countryId2]); - $entry1 = new EntityCacheEntry(Country::class, ['id'=>$countryId1, 'name'=>'outdated']); - $entry2 = new EntityCacheEntry(Country::class, ['id'=>$countryId2, 'name'=>'outdated']); + $key1 = new EntityCacheKey(Country::class, ['id' => $countryId1]); + $key2 = new EntityCacheKey(Country::class, ['id' => $countryId2]); + $entry1 = new EntityCacheEntry(Country::class, ['id' => $countryId1, 'name' => 'outdated']); + $entry2 = new EntityCacheEntry(Country::class, ['id' => $countryId2, 'name' => 'outdated']); $region->put($key1, $entry1); $region->put($key2, $entry2); @@ -221,7 +224,7 @@ public function testQueryCacheModeRefresh() $this->assertEquals($queryCount + 3, $this->getCurrentQueryCount()); } - public function testBasicQueryCachePutEntityCache() + public function testBasicQueryCachePutEntityCache(): void { $this->evictRegions(); $this->loadFixturesCountries(); @@ -252,7 +255,7 @@ public function testBasicQueryCachePutEntityCache() $this->_em->clear(); - $result2 = $this->_em->createQuery($dql) + $result2 = $this->_em->createQuery($dql) ->setCacheable(true) ->getResult(); @@ -288,7 +291,7 @@ public function testBasicQueryCachePutEntityCache() /** * @group 5854 */ - public function testMultipleNestedDQLAliases() + public function testMultipleNestedDQLAliases(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -344,7 +347,7 @@ public function testMultipleNestedDQLAliases() $this->_em->clear(); - $result2 = $this->_em->createQuery($dql) + $result2 = $this->_em->createQuery($dql) ->setCacheable(true) ->getResult(); @@ -368,7 +371,7 @@ public function testMultipleNestedDQLAliases() $this->assertCount(1, $result2[1]->getCities()->get(1)->getAttractions()); } - public function testBasicQueryParams() + public function testBasicQueryParams(): void { $this->evictRegions(); @@ -392,7 +395,7 @@ public function testBasicQueryParams() $this->_em->clear(); - $result2 = $this->_em->createQuery($dql)->setCacheable(true) + $result2 = $this->_em->createQuery($dql)->setCacheable(true) ->setParameter('name', $name) ->getResult(); @@ -405,7 +408,7 @@ public function testBasicQueryParams() $this->assertEquals($result1[0]->getName(), $result2[0]->getName()); } - public function testLoadFromDatabaseWhenEntityMissing() + public function testLoadFromDatabaseWhenEntityMissing(): void { $this->evictRegions(); @@ -420,7 +423,7 @@ public function testLoadFromDatabaseWhenEntityMissing() $result1 = $this->_em->createQuery($dql)->setCacheable(true)->getResult(); $this->assertCount(2, $result1); - $this->assertEquals($queryCount + 1 , $this->getCurrentQueryCount()); + $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()); @@ -436,11 +439,11 @@ public function testLoadFromDatabaseWhenEntityMissing() $this->_em->clear(); - $result2 = $this->_em->createQuery($dql) + $result2 = $this->_em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertEquals($queryCount + 2 , $this->getCurrentQueryCount()); + $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); $this->assertCount(2, $result2); $this->assertEquals(5, $this->secondLevelCacheLogger->getPutCount()); @@ -457,10 +460,10 @@ public function testLoadFromDatabaseWhenEntityMissing() $this->assertEquals($result1[0]->getName(), $result2[0]->getName()); $this->assertEquals($result1[1]->getName(), $result2[1]->getName()); - $this->assertEquals($queryCount + 2 , $this->getCurrentQueryCount()); + $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); } - public function testBasicQueryFetchJoinsOneToMany() + public function testBasicQueryFetchJoinsOneToMany(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -498,7 +501,7 @@ public function testBasicQueryFetchJoinsOneToMany() $this->_em->clear(); - $result2 = $this->_em->createQuery($dql) + $result2 = $this->_em->createQuery($dql) ->setCacheable(true) ->getResult(); @@ -525,7 +528,7 @@ public function testBasicQueryFetchJoinsOneToMany() $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } - public function testBasicQueryFetchJoinsManyToOne() + public function testBasicQueryFetchJoinsManyToOne(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -564,7 +567,7 @@ public function testBasicQueryFetchJoinsManyToOne() $this->_em->clear(); $this->secondLevelCacheLogger->clearStats(); - $result2 = $this->_em->createQuery($dql) + $result2 = $this->_em->createQuery($dql) ->setCacheable(true) ->getResult(); @@ -592,7 +595,7 @@ public function testBasicQueryFetchJoinsManyToOne() $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } - public function testReloadQueryIfToOneIsNotFound() + public function testReloadQueryIfToOneIsNotFound(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -624,7 +627,7 @@ public function testReloadQueryIfToOneIsNotFound() $this->cache->evictEntityRegion(State::class); - $result2 = $this->_em->createQuery($dql) + $result2 = $this->_em->createQuery($dql) ->setCacheable(true) ->getResult(); @@ -637,7 +640,7 @@ public function testReloadQueryIfToOneIsNotFound() $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); } - public function testReloadQueryIfToManyAssociationItemIsNotFound() + public function testReloadQueryIfToManyAssociationItemIsNotFound(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -667,7 +670,7 @@ public function testReloadQueryIfToManyAssociationItemIsNotFound() $this->cache->evictEntityRegion(City::class); - $result2 = $this->_em->createQuery($dql) + $result2 = $this->_em->createQuery($dql) ->setCacheable(true) ->getResult(); @@ -684,7 +687,7 @@ public function testReloadQueryIfToManyAssociationItemIsNotFound() $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); } - public function testBasicNativeQueryCache() + public function testBasicNativeQueryCache(): void { $this->evictRegions(); $this->loadFixturesCountries(); @@ -695,7 +698,7 @@ public function testBasicNativeQueryCache() $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(Country::class, 'c'); $rsm->addFieldResult('c', 'name', 'name'); $rsm->addFieldResult('c', 'id', 'id'); @@ -718,7 +721,7 @@ public function testBasicNativeQueryCache() $this->_em->clear(); - $result2 = $this->_em->createNativeQuery($sql, $rsm) + $result2 = $this->_em->createNativeQuery($sql, $rsm) ->setCacheable(true) ->getResult(); @@ -751,7 +754,7 @@ public function testBasicNativeQueryCache() $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); } - public function testQueryDependsOnFirstAndMaxResultResult() + public function testQueryDependsOnFirstAndMaxResultResult(): void { $this->evictRegions(); $this->loadFixturesCountries(); @@ -773,7 +776,7 @@ public function testQueryDependsOnFirstAndMaxResultResult() $this->_em->clear(); - $result2 = $this->_em->createQuery($dql) + $result2 = $this->_em->createQuery($dql) ->setCacheable(true) ->setFirstResult(2) ->setMaxResults(1) @@ -785,7 +788,7 @@ public function testQueryDependsOnFirstAndMaxResultResult() $this->_em->clear(); - $result3 = $this->_em->createQuery($dql) + $result3 = $this->_em->createQuery($dql) ->setCacheable(true) ->getResult(); @@ -794,7 +797,7 @@ public function testQueryDependsOnFirstAndMaxResultResult() $this->assertEquals(3, $this->secondLevelCacheLogger->getMissCount()); } - public function testQueryCacheLifetime() + public function testQueryCacheLifetime(): void { $this->evictRegions(); $this->loadFixturesCountries(); @@ -802,8 +805,8 @@ public function testQueryCacheLifetime() $this->secondLevelCacheLogger->clearStats(); $this->_em->clear(); - $getHash = function(AbstractQuery $query){ - $method = new \ReflectionMethod($query, 'getHash'); + $getHash = static function (AbstractQuery $query) { + $method = new ReflectionMethod($query, 'getHash'); $method->setAccessible(true); return $method->invoke($query); @@ -829,13 +832,13 @@ public function testQueryCacheLifetime() ->get($key); $this->assertInstanceOf(Cache\QueryCacheEntry::class, $entry); - $entry->time = $entry->time / 2; + $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(); @@ -846,7 +849,7 @@ public function testQueryCacheLifetime() $this->assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); } - public function testQueryCacheRegion() + public function testQueryCacheRegion(): void { $this->evictRegions(); $this->loadFixturesCountries(); @@ -858,8 +861,8 @@ public function testQueryCacheRegion() $dql = 'SELECT c FROM Doctrine\Tests\Models\Cache\Country c'; $query = $this->_em->createQuery($dql); - $query1 = clone $query; - $result1 = $query1->setCacheable(true) + $query1 = clone $query; + $result1 = $query1->setCacheable(true) ->setCacheRegion('foo_region') ->getResult(); @@ -871,8 +874,8 @@ public function testQueryCacheRegion() $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount('foo_region')); $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount('foo_region')); - $query2 = clone $query; - $result2 = $query2->setCacheable(true) + $query2 = clone $query; + $result2 = $query2->setCacheable(true) ->setCacheRegion('bar_region') ->getResult(); @@ -884,8 +887,8 @@ public function testQueryCacheRegion() $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount('bar_region')); $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount('bar_region')); - $query3 = clone $query; - $result3 = $query3->setCacheable(true) + $query3 = clone $query; + $result3 = $query3->setCacheable(true) ->setCacheRegion('foo_region') ->getResult(); @@ -898,8 +901,8 @@ public function testQueryCacheRegion() $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount('foo_region')); $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount('foo_region')); - $query4 = clone $query; - $result4 = $query4->setCacheable(true) + $query4 = clone $query; + $result4 = $query4->setCacheable(true) ->setCacheRegion('bar_region') ->getResult(); @@ -913,7 +916,7 @@ public function testQueryCacheRegion() $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount('bar_region')); } - public function testResolveAssociationCacheEntry() + public function testResolveAssociationCacheEntry(): void { $this->evictRegions(); $this->loadFixturesCountries(); @@ -961,7 +964,7 @@ public function testResolveAssociationCacheEntry() $this->assertEquals($stateId, $state2->getId()); } - public function testResolveToOneAssociationCacheEntry() + public function testResolveToOneAssociationCacheEntry(): void { $this->evictRegions(); $this->loadFixturesCountries(); @@ -971,13 +974,13 @@ public function testResolveToOneAssociationCacheEntry() $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); - $queryCount = $this->getCurrentQueryCount(); + $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); + $queryCount = $this->getCurrentQueryCount(); $query1 = clone $query; - $city1 = $query1 + $city1 = $query1 ->setParameter('id', $cityId) ->setCacheable(true) ->setMaxResults(1) @@ -1006,7 +1009,7 @@ public function testResolveToOneAssociationCacheEntry() $this->assertInstanceOf(State::class, $city2->getState()->getCities()->get(0)->getState()); } - public function testResolveToManyAssociationCacheEntry() + public function testResolveToManyAssociationCacheEntry(): void { $this->evictRegions(); $this->loadFixturesCountries(); @@ -1016,10 +1019,10 @@ public function testResolveToManyAssociationCacheEntry() $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); - $queryCount = $this->getCurrentQueryCount(); + $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); + $queryCount = $this->getCurrentQueryCount(); $query1 = clone $query; $state1 = $query1 @@ -1053,7 +1056,7 @@ public function testResolveToManyAssociationCacheEntry() $this->assertSame($state2, $state2->getCities()->get(0)->getState()); } - public function testHintClearEntityRegionUpdateStatement() + public function testHintClearEntityRegionUpdateStatement(): void { $this->evictRegions(); $this->loadFixturesCountries(); @@ -1069,7 +1072,7 @@ public function testHintClearEntityRegionUpdateStatement() $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); } - public function testHintClearEntityRegionDeleteStatement() + public function testHintClearEntityRegionDeleteStatement(): void { $this->evictRegions(); $this->loadFixturesCountries(); @@ -1085,19 +1088,19 @@ public function testHintClearEntityRegionDeleteStatement() $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); } - public function testCacheablePartialQueryException() + public function testCacheablePartialQueryException(): void { $this->expectException('Doctrine\ORM\Cache\CacheException'); $this->expectExceptionMessage('Second level cache does not support partial entities.'); $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') ->setCacheable(true) ->getResult(); } - public function testCacheableForcePartialLoadHintQueryException() + public function testCacheableForcePartialLoadHintQueryException(): void { $this->expectException('Doctrine\ORM\Cache\CacheException'); $this->expectExceptionMessage('Second level cache does not support partial entities.'); @@ -1110,16 +1113,16 @@ public function testCacheableForcePartialLoadHintQueryException() ->getResult(); } - public function testNonCacheableQueryDeleteStatementException() + public function testNonCacheableQueryDeleteStatementException(): void { $this->expectException('Doctrine\ORM\Cache\CacheException'); $this->expectExceptionMessage('Second-level cache query supports only select statements.'); - $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(); } - public function testNonCacheableQueryUpdateStatementException() + public function testNonCacheableQueryUpdateStatementException(): void { $this->expectException('Doctrine\ORM\Cache\CacheException'); $this->expectExceptionMessage('Second-level cache query supports only select statements.'); @@ -1128,7 +1131,7 @@ public function testNonCacheableQueryUpdateStatementException() ->getResult(); } - public function testQueryCacheShouldBeEvictedOnTimestampUpdate() + public function testQueryCacheShouldBeEvictedOnTimestampUpdate(): void { $this->loadFixturesCountries(); $this->_em->clear(); @@ -1136,7 +1139,7 @@ public function testQueryCacheShouldBeEvictedOnTimestampUpdate() $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(); diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheRepositoryTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheRepositoryTest.php index c8c4303c4da..7bd11f974a9 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheRepositoryTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheRepositoryTest.php @@ -1,5 +1,7 @@ evictRegions(); $this->loadFixturesCountries(); @@ -35,10 +37,9 @@ public function testRepositoryCacheFind() $this->assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); $this->assertEquals(0, $this->secondLevelCacheLogger->getMissCount()); $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(Country::class))); - } - public function testRepositoryCacheFindAll() + public function testRepositoryCacheFindAll(): void { $this->loadFixturesCountries(); $this->evictRegions(); @@ -69,7 +70,7 @@ public function testRepositoryCacheFindAll() $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); } - public function testRepositoryCacheFindAllInvalidation() + public function testRepositoryCacheFindAllInvalidation(): void { $this->loadFixturesCountries(); $this->evictRegions(); @@ -117,7 +118,7 @@ public function testRepositoryCacheFindAllInvalidation() $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } - public function testRepositoryCacheFindBy() + public function testRepositoryCacheFindBy(): void { $this->loadFixturesCountries(); $this->evictRegions(); @@ -126,7 +127,7 @@ public function testRepositoryCacheFindBy() $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $criteria = ['name'=>$this->countries[0]->getName()]; + $criteria = ['name' => $this->countries[0]->getName()]; $repository = $this->_em->getRepository(Country::class); $queryCount = $this->getCurrentQueryCount(); @@ -147,7 +148,7 @@ public function testRepositoryCacheFindBy() $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); } - public function testRepositoryCacheFindOneBy() + public function testRepositoryCacheFindOneBy(): void { $this->loadFixturesCountries(); $this->evictRegions(); @@ -156,7 +157,7 @@ public function testRepositoryCacheFindOneBy() $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $criteria = ['name'=>$this->countries[0]->getName()]; + $criteria = ['name' => $this->countries[0]->getName()]; $repository = $this->_em->getRepository(Country::class); $queryCount = $this->getCurrentQueryCount(); @@ -176,7 +177,7 @@ public function testRepositoryCacheFindOneBy() $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); } - public function testRepositoryCacheFindAllToOneAssociation() + public function testRepositoryCacheFindAllToOneAssociation(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheSingleTableInheritanceTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheSingleTableInheritanceTest.php index 858adb3a19c..841621eca5d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheSingleTableInheritanceTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheSingleTableInheritanceTest.php @@ -1,5 +1,7 @@ cache->getEntityCacheRegion(Attraction::class); - $restaurantRegion = $this->cache->getEntityCacheRegion(Restaurant::class); - $beachRegion = $this->cache->getEntityCacheRegion(Beach::class); - $barRegion = $this->cache->getEntityCacheRegion(Bar::class); + $attractionRegion = $this->cache->getEntityCacheRegion(Attraction::class); + $restaurantRegion = $this->cache->getEntityCacheRegion(Restaurant::class); + $beachRegion = $this->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()); } - public function testPutOnPersistSingleTableInheritance() + public function testPutOnPersistSingleTableInheritance(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -39,7 +44,7 @@ public function testPutOnPersistSingleTableInheritance() $this->assertTrue($this->cache->containsEntity(Bar::class, $this->attractions[1]->getId())); } - public function testCountaisRootClass() + public function testCountaisRootClass(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -54,7 +59,7 @@ public function testCountaisRootClass() } } - public function testPutAndLoadEntities() + public function testPutAndLoadEntities(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -115,7 +120,7 @@ public function testPutAndLoadEntities() $this->assertEquals($entity2->getName(), $entity4->getName()); } - public function testQueryCacheFindAll() + public function testQueryCacheFindAll(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -147,7 +152,7 @@ public function testQueryCacheFindAll() } } - public function testShouldNotPutOneToManyRelationOnPersist() + public function testShouldNotPutOneToManyRelationOnPersist(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -166,7 +171,7 @@ public function testShouldNotPutOneToManyRelationOnPersist() } } - public function testOneToManyRelationSingleTable() + public function testOneToManyRelationSingleTable(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -212,7 +217,7 @@ public function testOneToManyRelationSingleTable() $this->assertEquals($this->attractions[1]->getName(), $entity->getAttractions()->get(1)->getName()); } - public function testQueryCacheShouldBeEvictedOnTimestampUpdate() + public function testQueryCacheShouldBeEvictedOnTimestampUpdate(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -223,7 +228,7 @@ public function testQueryCacheShouldBeEvictedOnTimestampUpdate() $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(); diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheTest.php index 32047dda39b..1dac1ca5e4e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheTest.php @@ -1,17 +1,24 @@ loadFixturesCountries(); $this->_em->clear(); @@ -22,7 +29,7 @@ public function testPutOnPersist() $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Country::class))); } - public function testPutAndLoadEntities() + public function testPutAndLoadEntities(): void { $this->loadFixturesCountries(); $this->_em->clear(); @@ -71,7 +78,7 @@ public function testPutAndLoadEntities() $this->assertEquals($c2->getName(), $c4->getName()); } - public function testRemoveEntities() + public function testRemoveEntities(): void { $this->loadFixturesCountries(); $this->_em->clear(); @@ -117,7 +124,7 @@ public function testRemoveEntities() $this->assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); } - public function testUpdateEntities() + public function testUpdateEntities(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -152,8 +159,8 @@ public function testUpdateEntities() $this->assertEquals($this->states[1]->getId(), $s2->getId()); $this->assertEquals($this->states[1]->getName(), $s2->getName()); - $s1->setName("NEW NAME 1"); - $s2->setName("NEW NAME 2"); + $s1->setName('NEW NAME 1'); + $s2->setName('NEW NAME 2'); $this->_em->persist($s1); $this->_em->persist($s2); @@ -184,46 +191,44 @@ public function testUpdateEntities() $this->assertInstanceOf(State::class, $c4); $this->assertEquals($s1->getId(), $c3->getId()); - $this->assertEquals("NEW NAME 1", $c3->getName()); + $this->assertEquals('NEW NAME 1', $c3->getName()); $this->assertEquals($s2->getId(), $c4->getId()); - $this->assertEquals("NEW NAME 2", $c4->getName()); + $this->assertEquals('NEW NAME 2', $c4->getName()); $this->assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::class))); } - public function testPostFlushFailure() + public function testPostFlushFailure(): void { $listener = new ListenerSecondLevelCacheTest( [ - Events::postFlush => function(){ - throw new \RuntimeException('post flush failure'); - } + Events::postFlush => static function (): void { + throw new RuntimeException('post flush failure'); + }, ] ); $this->_em->getEventManager() ->addEventListener(Events::postFlush, $listener); - $country = new Country("Brazil"); + $country = new Country('Brazil'); $this->cache->evictEntityRegion(Country::class); try { - $this->_em->persist($country); $this->_em->flush(); $this->fail('Should throw exception'); - - } catch (\RuntimeException $exc) { + } catch (RuntimeException $exc) { $this->assertNotNull($country->getId()); $this->assertEquals('post flush failure', $exc->getMessage()); $this->assertTrue($this->cache->containsEntity(Country::class, $country->getId())); } } - public function testPostUpdateFailure() + public function testPostUpdateFailure(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -231,9 +236,9 @@ public function testPostUpdateFailure() $listener = new ListenerSecondLevelCacheTest( [ - Events::postUpdate => function(){ - throw new \RuntimeException('post update failure'); - } + Events::postUpdate => static function (): void { + throw new RuntimeException('post update failure'); + }, ] ); @@ -242,9 +247,9 @@ public function testPostUpdateFailure() $this->cache->evictEntityRegion(State::class); - $stateId = $this->states[0]->getId(); - $stateName = $this->states[0]->getName(); - $state = $this->_em->find(State::class, $stateId); + $stateId = $this->states[0]->getId(); + $stateName = $this->states[0]->getName(); + $state = $this->_em->find(State::class, $stateId); $this->assertTrue($this->cache->containsEntity(State::class, $stateId)); $this->assertInstanceOf(State::class, $state); @@ -257,8 +262,7 @@ public function testPostUpdateFailure() try { $this->_em->flush(); $this->fail('Should throw exception'); - - } catch (\Exception $exc) { + } catch (Exception $exc) { $this->assertEquals('post update failure', $exc->getMessage()); } @@ -272,16 +276,16 @@ public function testPostUpdateFailure() $this->assertEquals($stateName, $state->getName()); } - public function testPostRemoveFailure() + public function testPostRemoveFailure(): void { $this->loadFixturesCountries(); $this->_em->clear(); $listener = new ListenerSecondLevelCacheTest( [ - Events::postRemove => function(){ - throw new \RuntimeException('post remove failure'); - } + Events::postRemove => static function (): void { + throw new RuntimeException('post remove failure'); + }, ] ); @@ -290,8 +294,8 @@ public function testPostRemoveFailure() $this->cache->evictEntityRegion(Country::class); - $countryId = $this->countries[0]->getId(); - $country = $this->_em->find(Country::class, $countryId); + $countryId = $this->countries[0]->getId(); + $country = $this->_em->find(Country::class, $countryId); $this->assertTrue($this->cache->containsEntity(Country::class, $countryId)); $this->assertInstanceOf(Country::class, $country); @@ -301,8 +305,7 @@ public function testPostRemoveFailure() try { $this->_em->flush(); $this->fail('Should throw exception'); - - } catch (\Exception $exc) { + } catch (Exception $exc) { $this->assertEquals('post remove failure', $exc->getMessage()); } @@ -316,7 +319,7 @@ public function testPostRemoveFailure() $this->assertInstanceOf(Country::class, $this->_em->find(Country::class, $countryId)); } - public function testCachedNewEntityExists() + public function testCachedNewEntityExists(): void { $this->loadFixturesCountries(); @@ -341,24 +344,24 @@ public function __construct(array $callbacks = []) $this->callbacks = $callbacks; } - private function dispatch($eventName, $args) + private function dispatch($eventName, $args): void { if (isset($this->callbacks[$eventName])) { call_user_func($this->callbacks[$eventName], $args); } } - public function postFlush($args) + public function postFlush($args): void { $this->dispatch(__FUNCTION__, $args); } - public function postUpdate($args) + public function postUpdate($args): void { $this->dispatch(__FUNCTION__, $args); } - public function postRemove($args) + public function postRemove($args): void { $this->dispatch(__FUNCTION__, $args); } diff --git a/tests/Doctrine/Tests/ORM/Functional/SequenceEmulatedIdentityStrategyTest.php b/tests/Doctrine/Tests/ORM/Functional/SequenceEmulatedIdentityStrategyTest.php index 03b764c4aa6..1396315c72d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SequenceEmulatedIdentityStrategyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SequenceEmulatedIdentityStrategyTest.php @@ -1,20 +1,22 @@ _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.' ); @@ -23,16 +25,13 @@ protected function setUp() : void $this->_schemaTool->createSchema( [$this->_em->getClassMetadata(SequenceEmulatedIdentityEntity::class)] ); - } catch (\Exception $e) { + } catch (Exception $e) { // Swallow all exceptions. We do not test the schema tool here. } } } - /** - * {@inheritdoc} - */ - protected function tearDown() : void + protected function tearDown(): void { parent::tearDown(); @@ -47,7 +46,7 @@ protected function tearDown() : void ); } - public function testPreSavePostSaveCallbacksAreInvoked() + public function testPreSavePostSaveCallbacksAreInvoked(): void { $entity = new SequenceEmulatedIdentityEntity(); $entity->setValue('hello'); @@ -78,7 +77,7 @@ public function getValue() return $this->value; } - public function setValue($value) + public function setValue($value): void { $this->value = $value; } diff --git a/tests/Doctrine/Tests/ORM/Functional/SequenceGeneratorTest.php b/tests/Doctrine/Tests/ORM/Functional/SequenceGeneratorTest.php index f313d7162ee..c57607f857c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SequenceGeneratorTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SequenceGeneratorTest.php @@ -1,20 +1,22 @@ _em->getConnection()->getDatabasePlatform()->supportsSequences()) { + if (! $this->_em->getConnection()->getDatabasePlatform()->supportsSequences()) { $this->markTestSkipped('Only working for Databases that support sequences.'); } @@ -24,11 +26,11 @@ protected function setUp() : void $this->_em->getClassMetadata(SequenceEntity::class), ] ); - } catch(\Exception $e) { + } catch (Exception $e) { } } - public function testHighAllocationSizeSequence() + public function testHighAllocationSizeSequence(): void { for ($i = 0; $i < 11; ++$i) { $this->_em->persist(new SequenceEntity()); diff --git a/tests/Doctrine/Tests/ORM/Functional/SingleTableCompositeKeyTest.php b/tests/Doctrine/Tests/ORM/Functional/SingleTableCompositeKeyTest.php index c61290bae35..33ee05cb316 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SingleTableCompositeKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SingleTableCompositeKeyTest.php @@ -1,19 +1,23 @@ useModelSet('compositekeyinheritance'); parent::setUp(); } - public function testInsertWithCompositeKey() + public function testInsertWithCompositeKey(): void { $childEntity = new SingleChildClass(); $this->_em->persist($childEntity); @@ -28,7 +32,7 @@ public function testInsertWithCompositeKey() /** * @group non-cacheable */ - public function testUpdateWithCompositeKey() + public function testUpdateWithCompositeKey(): void { $childEntity = new SingleChildClass(); $this->_em->persist($childEntity); @@ -36,7 +40,7 @@ public function testUpdateWithCompositeKey() $this->_em->clear(); - $entity = $this->findEntity(); + $entity = $this->findEntity(); $entity->extension = 'ext-new'; $this->_em->persist($entity); $this->_em->flush(); @@ -47,10 +51,7 @@ public function testUpdateWithCompositeKey() $this->assertEquals($entity, $persistedEntity); } - /** - * @return \Doctrine\Tests\Models\CompositeKeyInheritance\JoinedChildClass - */ - private function findEntity() + private function findEntity(): JoinedChildClass { 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 3ef2f03ac3f..311dc211497 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SingleTableInheritanceTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SingleTableInheritanceTest.php @@ -1,5 +1,7 @@ useModelSet('company'); parent::setUp(); } - public function persistRelatedEmployees() + public function persistRelatedEmployees(): void { $this->salesPerson = new CompanyEmployee(); $this->salesPerson->setName('Poor Sales Guy'); @@ -65,7 +72,7 @@ public function persistRelatedEmployees() $this->_em->persist($engineer4); } - public function loadFullFixture() + public function loadFullFixture(): void { $this->persistRelatedEmployees(); @@ -100,7 +107,7 @@ public function loadFullFixture() $this->_em->clear(); } - public function testPersistChildOfBaseClass() + public function testPersistChildOfBaseClass(): void { $this->persistRelatedEmployees(); @@ -119,7 +126,7 @@ public function testPersistChildOfBaseClass() $this->assertEquals($this->salesPerson->getId(), $contract->getSalesPerson()->getId()); } - public function testPersistDeepChildOfBaseClass() + public function testPersistDeepChildOfBaseClass(): void { $this->persistRelatedEmployees(); @@ -141,7 +148,7 @@ public function testPersistDeepChildOfBaseClass() $this->assertEquals(50, $contract->getPricePerHour()); } - public function testChildClassLifecycleUpdate() + public function testChildClassLifecycleUpdate(): void { $this->loadFullFixture(); @@ -155,7 +162,7 @@ public function testChildClassLifecycleUpdate() $this->assertEquals(2500, $newFix->getFixPrice()); } - public function testChildClassLifecycleRemove() + public function testChildClassLifecycleRemove(): void { $this->loadFullFixture(); @@ -166,7 +173,7 @@ public function testChildClassLifecycleRemove() $this->assertNull($this->_em->find(CompanyContract::class, $this->fix->getId())); } - public function testFindAllForAbstractBaseClass() + public function testFindAllForAbstractBaseClass(): void { $this->loadFullFixture(); $contracts = $this->_em->getRepository(CompanyContract::class)->findAll(); @@ -175,7 +182,7 @@ public function testFindAllForAbstractBaseClass() $this->assertContainsOnly(CompanyContract::class, $contracts); } - public function testFindAllForChildClass() + public function testFindAllForChildClass(): void { $this->loadFullFixture(); @@ -184,7 +191,7 @@ public function testFindAllForChildClass() $this->assertEquals(1, count($this->_em->getRepository(CompanyFlexUltraContract::class)->findAll())); } - public function testFindForAbstractBaseClass() + public function testFindForAbstractBaseClass(): void { $this->loadFullFixture(); @@ -194,7 +201,7 @@ public function testFindForAbstractBaseClass() $this->assertEquals(1000, $contract->getFixPrice()); } - public function testQueryForAbstractBaseClass() + public function testQueryForAbstractBaseClass(): void { $this->loadFullFixture(); @@ -204,7 +211,7 @@ public function testQueryForAbstractBaseClass() $this->assertContainsOnly(CompanyContract::class, $contracts); } - public function testQueryForChildClass() + public function testQueryForChildClass(): void { $this->loadFullFixture(); @@ -213,7 +220,7 @@ public function testQueryForChildClass() $this->assertEquals(1, count($this->_em->createQuery('SELECT c FROM Doctrine\Tests\Models\Company\CompanyFlexUltraContract c')->getResult())); } - public function testQueryBaseClassWithJoin() + public function testQueryBaseClassWithJoin(): void { $this->loadFullFixture(); @@ -222,13 +229,13 @@ public function testQueryBaseClassWithJoin() $this->assertContainsOnly(CompanyContract::class, $contracts); } - public function testQueryScalarWithDiscriminatorValue() + public function testQueryScalarWithDiscriminatorValue(): void { $this->loadFullFixture(); $contracts = $this->_em->createQuery('SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c ORDER BY c.id')->getScalarResult(); - $discrValues = \array_map(function($a) { + $discrValues = array_map(static function ($a) { return $a['c_discr']; }, $contracts); @@ -237,11 +244,11 @@ public function testQueryScalarWithDiscriminatorValue() $this->assertEquals(['fix', 'flexible', 'flexultra'], $discrValues); } - public function testQueryChildClassWithCondition() + public function testQueryChildClassWithCondition(): void { $this->loadFullFixture(); - $dql = 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyFixContract c WHERE c.fixPrice = ?1'; + $dql = 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyFixContract c WHERE c.fixPrice = ?1'; $contract = $this->_em->createQuery($dql)->setParameter(1, 1000)->getSingleResult(); $this->assertInstanceOf(CompanyFixContract::class, $contract); @@ -251,52 +258,52 @@ public function testQueryChildClassWithCondition() /** * @group non-cacheable */ - public function testUpdateChildClassWithCondition() + public function testUpdateChildClassWithCondition(): void { $this->loadFullFixture(); - $dql = 'UPDATE Doctrine\Tests\Models\Company\CompanyFlexContract c SET c.hoursWorked = c.hoursWorked * 2 WHERE c.hoursWorked = 150'; + $dql = 'UPDATE Doctrine\Tests\Models\Company\CompanyFlexContract c SET c.hoursWorked = c.hoursWorked * 2 WHERE c.hoursWorked = 150'; $affected = $this->_em->createQuery($dql)->execute(); $this->assertEquals(1, $affected); - $flexContract = $this->_em->find(CompanyContract::class, $this->flex->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()); } - public function testUpdateBaseClassWithCondition() + public function testUpdateBaseClassWithCondition(): void { $this->loadFullFixture(); - $dql = 'UPDATE Doctrine\Tests\Models\Company\CompanyContract c SET c.completed = true WHERE c.completed = false'; + $dql = 'UPDATE Doctrine\Tests\Models\Company\CompanyContract c SET c.completed = true WHERE c.completed = false'; $affected = $this->_em->createQuery($dql)->execute(); $this->assertEquals(1, $affected); - $dql = 'UPDATE Doctrine\Tests\Models\Company\CompanyContract c SET c.completed = false'; + $dql = 'UPDATE Doctrine\Tests\Models\Company\CompanyContract c SET c.completed = false'; $affected = $this->_em->createQuery($dql)->execute(); $this->assertEquals(3, $affected); } - public function testDeleteByChildClassCondition() + public function testDeleteByChildClassCondition(): void { $this->loadFullFixture(); - $dql = 'DELETE Doctrine\Tests\Models\Company\CompanyFlexContract c'; + $dql = 'DELETE Doctrine\Tests\Models\Company\CompanyFlexContract c'; $affected = $this->_em->createQuery($dql)->execute(); $this->assertEquals(2, $affected); } - public function testDeleteByBaseClassCondition() + public function testDeleteByBaseClassCondition(): void { $this->loadFullFixture(); - $dql = "DELETE Doctrine\Tests\Models\Company\CompanyContract c WHERE c.completed = true"; + $dql = 'DELETE Doctrine\Tests\Models\Company\CompanyContract c WHERE c.completed = true'; $affected = $this->_em->createQuery($dql)->execute(); $this->assertEquals(2, $affected); @@ -304,13 +311,13 @@ public function testDeleteByBaseClassCondition() $contracts = $this->_em->createQuery('SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c')->getResult(); $this->assertEquals(1, count($contracts)); - $this->assertFalse($contracts[0]->isCompleted(), "Only non completed contracts should be left."); + $this->assertFalse($contracts[0]->isCompleted(), 'Only non completed contracts should be left.'); } /** * @group DDC-130 */ - public function testDeleteJoinTableRecords() + public function testDeleteJoinTableRecords(): void { $this->loadFullFixture(); @@ -318,48 +325,48 @@ public function testDeleteJoinTableRecords() $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."); + $this->assertNull($this->_em->find(get_class($this->fix), $this->fix->getId()), 'Contract should not be present in the database anymore.'); } /** * @group DDC-817 */ - public function testFindByAssociation() + public function testFindByAssociation(): void { $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'"); + $this->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'"); + $this->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'"); + $this->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'"); + $this->assertEquals(1, count($contracts), 'There should be 1 entities related to ' . $this->salesPerson->getId() . " for 'Doctrine\Tests\Models\Company\CompanyFlexUltraContract'"); } /** * @group DDC-1637 */ - public function testInheritanceMatching() + public function testInheritanceMatching(): void { $this->loadFullFixture(); $repository = $this->_em->getRepository(CompanyContract::class); - $contracts = $repository->matching(new Criteria( + $contracts = $repository->matching(new Criteria( Criteria::expr()->eq('salesPerson', $this->salesPerson) )); $this->assertEquals(3, count($contracts)); $repository = $this->_em->getRepository(CompanyFixContract::class); - $contracts = $repository->matching(new Criteria( + $contracts = $repository->matching(new Criteria( Criteria::expr()->eq('salesPerson', $this->salesPerson) )); $this->assertEquals(1, count($contracts)); @@ -368,7 +375,7 @@ public function testInheritanceMatching() /** * @group DDC-2430 */ - public function testMatchingNonObjectOnAssocationThrowsException() + public function testMatchingNonObjectOnAssocationThrowsException(): void { $this->loadFullFixture(); @@ -388,28 +395,28 @@ public function testMatchingNonObjectOnAssocationThrowsException() /** * @group DDC-834 */ - public function testGetReferenceEntityWithSubclasses() + public function testGetReferenceEntityWithSubclasses(): void { $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->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->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."); + $this->assertInstanceOf(Proxy::class, $ref, 'A proxy can be generated only if no subclasses exists for the requested reference.'); } /** * @group DDC-952 */ - public function testEagerLoadInheritanceHierarchy() + public function testEagerLoadInheritanceHierarchy(): void { $this->loadFullFixture(); - $dql = 'SELECT f FROM Doctrine\Tests\Models\Company\CompanyFixContract f WHERE f.id = ?1'; + $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()) diff --git a/tests/Doctrine/Tests/ORM/Functional/StandardEntityPersisterTest.php b/tests/Doctrine/Tests/ORM/Functional/StandardEntityPersisterTest.php index f2c0472ec33..401e06fa078 100644 --- a/tests/Doctrine/Tests/ORM/Functional/StandardEntityPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/StandardEntityPersisterTest.php @@ -1,5 +1,7 @@ */ class StandardEntityPersisterTest extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { $this->useModelSet('ecommerce'); parent::setUp(); } - public function testAcceptsForeignKeysAsCriteria() + public function testAcceptsForeignKeysAsCriteria(): void { $customer = new ECommerceCustomer(); $customer->setName('John Doe'); @@ -37,7 +40,7 @@ public function testAcceptsForeignKeysAsCriteria() $class = $this->_em->getClassMetadata(ECommerceCart::class); $persister = $this->_em->getUnitOfWork()->getEntityPersister(ECommerceCart::class); - $newCart = new ECommerceCart(); + $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()); @@ -46,15 +49,15 @@ public function testAcceptsForeignKeysAsCriteria() /** * Ticket #2478 from Damon Jones (dljones) */ - public function testAddPersistRetrieve() + public function testAddPersistRetrieve(): void { - $f1 = new ECommerceFeature; + $f1 = new ECommerceFeature(); $f1->setDescription('AC-3'); - $f2 = new ECommerceFeature; + $f2 = new ECommerceFeature(); $f2->setDescription('DTS'); - $p = new ECommerceProduct; + $p = new ECommerceProduct(); $p->addFeature($f1); $p->addFeature($f2); $this->_em->persist($p); @@ -77,7 +80,7 @@ public function testAddPersistRetrieve() // Check that the features are the same instances still foreach ($p->getFeatures() as $feature) { - if ($feature->getDescription() == 'AC-3') { + if ($feature->getDescription() === 'AC-3') { $this->assertTrue($feature === $f1); } else { $this->assertTrue($feature === $f2); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1040Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1040Test.php index 0312bec549a..84e6010e3ec 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1040Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1040Test.php @@ -1,5 +1,7 @@ useModelSet('cms'); parent::setUp(); } - public function testReuseNamedEntityParameter() + public function testReuseNamedEntityParameter(): void { - $user = new CmsUser(); - $user->name = "John Galt"; - $user->username = "jgalt"; - $user->status = "inactive"; - - $article = new CmsArticle(); - $article->topic = "This is John Galt speaking!"; - $article->text = "Yadda Yadda!"; + $user = new CmsUser(); + $user->name = 'John Galt'; + $user->username = 'jgalt'; + $user->status = 'inactive'; + + $article = new CmsArticle(); + $article->topic = 'This is John Galt speaking!'; + $article->text = 'Yadda Yadda!'; $article->setAuthor($user); $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"; + $dql = 'SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.user = :author'; $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"; + $dql = 'SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.user = :author AND a.user = :author'; $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"; + $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) ->setParameter('author', $user) ->setParameter('topic', 'This is John Galt speaking!') @@ -52,23 +54,23 @@ public function testReuseNamedEntityParameter() $this->assertSame($article, $farticle); } - public function testUseMultiplePositionalParameters() + public function testUseMultiplePositionalParameters(): void { - $user = new CmsUser(); - $user->name = "John Galt"; - $user->username = "jgalt"; - $user->status = "inactive"; - - $article = new CmsArticle(); - $article->topic = "This is John Galt speaking!"; - $article->text = "Yadda Yadda!"; + $user = new CmsUser(); + $user->name = 'John Galt'; + $user->username = 'jgalt'; + $user->status = 'inactive'; + + $article = new CmsArticle(); + $article->topic = 'This is John Galt speaking!'; + $article->text = 'Yadda Yadda!'; $article->setAuthor($user); $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"; + $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) ->setParameter(1, 'This is John Galt speaking!') ->setParameter(2, $user) diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1041Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1041Test.php index fcb6fce1be8..14642a657c9 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1041Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1041Test.php @@ -1,5 +1,7 @@ useModelSet('company'); parent::setUp(); } - public function testGrabWrongSubtypeReturnsNull() + public function testGrabWrongSubtypeReturnsNull(): void { $fix = new Models\Company\CompanyFixContract(); $fix->setFixPrice(2000); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1043Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1043Test.php index faeda3c141f..815e243caf4 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1043Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1043Test.php @@ -1,5 +1,7 @@ useModelSet('cms'); parent::setUp(); } - public function testChangeSetPlusWeirdPHPCastingIntCastingRule() + public function testChangeSetPlusWeirdPHPCastingIntCastingRule(): void { - $user = new CmsUser(); - $user->name = "John Galt"; - $user->username = "jgalt"; - $user->status = "+44"; + $user = new CmsUser(); + $user->name = 'John Galt'; + $user->username = 'jgalt'; + $user->status = '+44'; $this->_em->persist($user); $this->_em->flush(); - $user->status = "44"; + $user->status = '44'; $this->_em->flush(); $this->_em->clear(); $user = $this->_em->find(CmsUser::class, $user->id); - $this->assertSame("44", $user->status); + $this->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..e2377c02fd4 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1080Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1080Test.php @@ -1,21 +1,26 @@ _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), ] ); @@ -59,10 +64,10 @@ public function testHydration() $this->_em->flush(); $this->_em->clear(); - $foo = $this->_em->find(DDC1080Foo::class, $foo1->getFooID()); + $foo = $this->_em->find(DDC1080Foo::class, $foo1->getFooID()); $fooBars = $foo->getFooBars(); - $this->assertEquals(3, count($fooBars), "Should return three foobars."); + $this->assertEquals(3, count($fooBars), 'Should return three foobars.'); } } @@ -73,16 +78,13 @@ public function testHydration() */ class DDC1080Foo { - /** * @Id * @Column(name="fooID", type="integer") * @GeneratedValue(strategy="AUTO") */ protected $_fooID; - /** - * @Column(name="fooTitle", type="string") - */ + /** @Column(name="fooTitle", type="string") */ protected $_fooTitle; /** * @OneToMany(targetEntity="DDC1080FooBar", mappedBy="_foo", @@ -93,13 +95,13 @@ class DDC1080Foo public function __construct() { - $this->_fooBars = new \Doctrine\Common\Collections\ArrayCollection(); + $this->_fooBars = new ArrayCollection(); } /** * @return the $fooID */ - public function getFooID() + public function getFooID(): the { return $this->_fooID; } @@ -107,7 +109,7 @@ public function getFooID() /** * @return the $fooTitle */ - public function getFooTitle() + public function getFooTitle(): the { return $this->_fooTitle; } @@ -115,35 +117,25 @@ public function getFooTitle() /** * @return the $fooBars */ - public function getFooBars() + public function getFooBars(): the { return $this->_fooBars; } - /** - * @param field_type $fooID - */ - public function setFooID($fooID) + public function setFooID(field_type $fooID): void { $this->_fooID = $fooID; } - /** - * @param field_type $fooTitle - */ - public function setFooTitle($fooTitle) + public function setFooTitle(field_type $fooTitle): void { $this->_fooTitle = $fooTitle; } - /** - * @param field_type $fooBars - */ - public function setFooBars($fooBars) + public function setFooBars(field_type $fooBars): void { $this->_fooBars = $fooBars; } - } /** * @Entity @@ -151,16 +143,13 @@ public function setFooBars($fooBars) */ class DDC1080Bar { - /** * @Id * @Column(name="barID", type="integer") * @GeneratedValue(strategy="AUTO") */ protected $_barID; - /** - * @Column(name="barTitle", type="string") - */ + /** @Column(name="barTitle", type="string") */ protected $_barTitle; /** * @OneToMany(targetEntity="DDC1080FooBar", mappedBy="_bar", @@ -171,13 +160,13 @@ class DDC1080Bar public function __construct() { - $this->_fooBars = new \Doctrine\Common\Collections\ArrayCollection(); + $this->_fooBars = new ArrayCollection(); } /** * @return the $barID */ - public function getBarID() + public function getBarID(): the { return $this->_barID; } @@ -185,7 +174,7 @@ public function getBarID() /** * @return the $barTitle */ - public function getBarTitle() + public function getBarTitle(): the { return $this->_barTitle; } @@ -193,35 +182,25 @@ public function getBarTitle() /** * @return the $fooBars */ - public function getFooBars() + public function getFooBars(): the { return $this->_fooBars; } - /** - * @param field_type $barID - */ - public function setBarID($barID) + public function setBarID(field_type $barID): void { $this->_barID = $barID; } - /** - * @param field_type $barTitle - */ - public function setBarTitle($barTitle) + public function setBarTitle(field_type $barTitle): void { $this->_barTitle = $barTitle; } - /** - * @param field_type $fooBars - */ - public function setFooBars($fooBars) + public function setFooBars(field_type $fooBars): void { $this->_fooBars = $fooBars; } - } /** @@ -230,7 +209,6 @@ public function setFooBars($fooBars) */ class DDC1080FooBar { - /** * @ManyToOne(targetEntity="DDC1080Foo") * @JoinColumn(name="fooID", referencedColumnName="fooID") @@ -251,69 +229,55 @@ class DDC1080FooBar /** * Retrieve the foo property - * - * @return DDC1080Foo */ - public function getFoo() + public function getFoo(): DDC1080Foo { return $this->_foo; } /** * Set the foo property - * - * @param DDC1080Foo $foo - * @return DDC1080FooBar */ - public function setFoo($foo) + public function setFoo(DDC1080Foo $foo): DDC1080FooBar { $this->_foo = $foo; + return $this; } /** * Retrieve the bar property - * - * @return DDC1080Bar */ - public function getBar() + public function getBar(): DDC1080Bar { return $this->_bar; } /** * Set the bar property - * - * @param DDC1080Bar $bar - * @return DDC1080FooBar */ - public function setBar($bar) + public function setBar(DDC1080Bar $bar): DDC1080FooBar { $this->_bar = $bar; + return $this; } /** * Retrieve the orderNr property - * - * @return int|null */ - public function getOrderNr() + public function getOrderNr(): ?int { return $this->_orderNr; } /** * Set the orderNr property - * - * @param integer|null $orderNr - * @return DDC1080FooBar */ - public function setOrderNr($orderNr) + public function setOrderNr(?int $orderNr): DDC1080FooBar { $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 8b8c6f2d581..42ce37c62d7 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1113Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1113Test.php @@ -1,14 +1,19 @@ _em->getClassMetadata(DDC1113Bus::class), ] ); - } catch (\Exception $e) { + } catch (Exception $e) { } } - public function testIssue() + public function testIssue(): void { - $car = new DDC1113Car(); + $car = new DDC1113Car(); $car->engine = new DDC1113Engine(); - $bus = new DDC1113Bus(); + $bus = new DDC1113Bus(); $bus->engine = new DDC1113Engine(); $this->_em->persist($car); @@ -56,18 +61,14 @@ public function testIssue() */ class DDC1113Vehicle { - /** @Id @GeneratedValue @Column(type="integer") */ public $id; - /** - * @ManyToOne(targetEntity="DDC1113Vehicle") - */ + /** @ManyToOne(targetEntity="DDC1113Vehicle") */ public $parent; /** @OneToOne(targetEntity="DDC1113Engine", cascade={"persist", "remove"}) */ public $engine; - } /** @@ -75,7 +76,6 @@ class DDC1113Vehicle */ class DDC1113Car extends DDC1113Vehicle { - } /** @@ -83,7 +83,6 @@ class DDC1113Car extends DDC1113Vehicle */ class DDC1113Bus extends DDC1113Vehicle { - } /** @@ -91,9 +90,6 @@ class DDC1113Bus extends DDC1113Vehicle */ class DDC1113Engine { - /** @Id @GeneratedValue @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 480d2303781..4086715537e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1129Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1129Test.php @@ -1,25 +1,30 @@ useModelSet('cms'); parent::setUp(); } - public function testVersionFieldIgnoredInChangesetComputation() + public function testVersionFieldIgnoredInChangesetComputation(): void { - $article = new CmsArticle(); - $article->text = "I don't know."; - $article->topic = "Who is John Galt?"; + $article = new CmsArticle(); + $article->text = "I don't know."; + $article->topic = 'Who is John Galt?'; $this->_em->persist($article); $this->_em->flush(); @@ -27,19 +32,19 @@ public function testVersionFieldIgnoredInChangesetComputation() $this->assertEquals(1, $article->version); $class = $this->_em->getClassMetadata(CmsArticle::class); - $uow = $this->_em->getUnitOfWork(); + $uow = $this->_em->getUnitOfWork(); $uow->computeChangeSet($class, $article); $changeSet = $uow->getEntityChangeSet($article); - $this->assertEquals(0, count($changeSet), "No changesets should be computed."); + $this->assertEquals(0, count($changeSet), 'No changesets should be computed.'); - $article->text = "This is John Galt speaking."; + $article->text = 'This is John Galt speaking.'; $this->_em->flush(); $this->assertEquals(2, $article->version); $uow->computeChangeSet($class, $article); $changeSet = $uow->getEntityChangeSet($article); - $this->assertEquals(0, count($changeSet), "No changesets should be computed."); + $this->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..cddf140f813 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1151Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1151Test.php @@ -1,34 +1,38 @@ _em->getConnection()->getDatabasePlatform()->getName() != 'postgresql') { - $this->markTestSkipped("This test is useful for all databases, but designed only for 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( [ - $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]); + $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]); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1163Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1163Test.php index 32715075a88..790f72f29c7 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1163Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1163Test.php @@ -1,29 +1,35 @@ _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), ] ); } - public function testIssue() + public function testIssue(): void { $this->createSpecialProductAndProxyHolderReferencingIt(); $this->_em->clear(); @@ -36,7 +42,7 @@ public function testIssue() $this->_em->flush(); } - private function createSpecialProductAndProxyHolderReferencingIt() + private function createSpecialProductAndProxyHolderReferencingIt(): void { $specialProduct = new DDC1163SpecialProduct(); $this->_em->persist($specialProduct); @@ -48,7 +54,7 @@ private function createSpecialProductAndProxyHolderReferencingIt() $this->_em->flush(); - $this->productId = $specialProduct->getId(); + $this->productId = $specialProduct->getId(); $this->proxyHolderId = $proxyHolder->getId(); } @@ -59,18 +65,18 @@ private function createSpecialProductAndProxyHolderReferencingIt() * When Doctrine loads the 'ProxyHolder', it will do just that because the 'ProxyHolder' * references the 'SpecialProduct'. */ - private function createProxyForSpecialProduct() + private function createProxyForSpecialProduct(): void { - /* @var $proxyHolder DDC1163ProxyHolder */ $proxyHolder = $this->_em->find(DDC1163ProxyHolder::class, $this->proxyHolderId); + assert($proxyHolder instanceof DDC1163ProxyHolder); $this->assertInstanceOf(DDC1163SpecialProduct::class, $proxyHolder->getSpecialProduct()); } - private function setPropertyAndAssignTagToSpecialProduct() + private function setPropertyAndAssignTagToSpecialProduct(): void { - /* @var $specialProduct DDC1163SpecialProduct */ $specialProduct = $this->_em->find(DDC1163SpecialProduct::class, $this->productId); + assert($specialProduct instanceof DDC1163SpecialProduct); $this->assertInstanceOf(DDC1163SpecialProduct::class, $specialProduct); $this->assertInstanceOf(Proxy::class, $specialProduct); @@ -94,7 +100,6 @@ private function setPropertyAndAssignTagToSpecialProduct() */ class DDC1163ProxyHolder { - /** * @var int * @Column(name="id", type="integer") @@ -113,7 +118,7 @@ public function getId() return $this->id; } - public function setSpecialProduct(DDC1163SpecialProduct $specialProduct) + public function setSpecialProduct(DDC1163SpecialProduct $specialProduct): void { $this->specialProduct = $specialProduct; } @@ -122,7 +127,6 @@ public function getSpecialProduct() { return $this->specialProduct; } - } /** @@ -133,7 +137,6 @@ public function getSpecialProduct() */ abstract class DDC1163Product { - /** * @var int * @Column(name="id", type="integer") @@ -146,7 +149,6 @@ public function getId() { return $this->id; } - } /** @@ -154,21 +156,16 @@ public function getId() */ class DDC1163SpecialProduct extends DDC1163Product { - /** * @var string * @Column(name="subclass_property", type="string", nullable=true) */ private $subclassProperty; - /** - * @param string $value - */ - public function setSubclassProperty($value) + public function setSubclassProperty(string $value): void { $this->subclassProperty = $value; } - } /** @@ -176,7 +173,6 @@ public function setSubclassProperty($value) */ class DDC1163Tag { - /** * @var int * @Column(name="id", type="integer") @@ -198,10 +194,7 @@ class DDC1163Tag */ private $product; - /** - * @param string $name - */ - public function __construct($name) + public function __construct(string $name) { $this->name = $name; } @@ -209,9 +202,8 @@ public function __construct($name) /** * @param Product $product */ - public function setProduct(DDC1163Product $product) + public function setProduct(DDC1163Product $product): void { $this->product = $product; } - } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC117Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC117Test.php index 53cca994671..f7e074c4127 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC117Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC117Test.php @@ -1,20 +1,29 @@ useModelSet('ddc117'); parent::setUp(); - $this->article1 = new DDC117Article("Foo"); - $this->article2 = new DDC117Article("Bar"); + $this->article1 = new DDC117Article('Foo'); + $this->article2 = new DDC117Article('Bar'); $this->_em->persist($this->article1); $this->_em->persist($this->article2); $this->_em->flush(); - $link = new DDC117Link($this->article1, $this->article2, "Link-Description"); + $link = new DDC117Link($this->article1, $this->article2, 'Link-Description'); $this->_em->persist($link); - $this->reference = new DDC117Reference($this->article1, $this->article2, "Test-Description"); + $this->reference = new DDC117Reference($this->article1, $this->article2, 'Test-Description'); $this->_em->persist($this->reference); - $this->translation = new DDC117Translation($this->article1, "en", "Bar"); + $this->translation = new DDC117Translation($this->article1, 'en', 'Bar'); $this->_em->persist($this->translation); - $this->articleDetails = new DDC117ArticleDetails($this->article1, "Very long text"); + $this->articleDetails = new DDC117ArticleDetails($this->article1, 'Very long text'); $this->_em->persist($this->articleDetails); $this->_em->flush(); @@ -55,7 +64,7 @@ protected function setUp() : void /** * @group DDC-117 */ - public function testAssociationOnlyCompositeKey() + public function testAssociationOnlyCompositeKey(): void { $idCriteria = ['source' => $this->article1->id(), 'target' => $this->article2->id()]; @@ -67,7 +76,7 @@ public function testAssociationOnlyCompositeKey() $this->_em->clear(); - $dql = 'SELECT r, s FROM ' . DDC117Reference::class . ' r JOIN r.source s WHERE r.source = ?1'; + $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(); $this->assertInstanceOf(DDC117Reference::class, $mapRef); @@ -77,7 +86,7 @@ public function testAssociationOnlyCompositeKey() $this->_em->clear(); - $dql = 'SELECT r, s FROM ' . DDC117Reference::class . ' r JOIN r.source s WHERE s.title = ?1'; + $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(); $this->assertInstanceOf(DDC117Reference::class, $dqlRef); @@ -85,7 +94,7 @@ public function testAssociationOnlyCompositeKey() $this->assertInstanceOf(DDC117Article::class, $dqlRef->source()); $this->assertSame($dqlRef, $this->_em->find(DDC117Reference::class, $idCriteria)); - $dql = 'SELECT r, s FROM ' . DDC117Reference::class . ' r JOIN r.source s WHERE s.title = ?1'; + $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(); $this->_em->contains($dqlRef); @@ -94,13 +103,13 @@ public function testAssociationOnlyCompositeKey() /** * @group DDC-117 */ - public function testUpdateAssociationEntity() + public function testUpdateAssociationEntity(): void { $idCriteria = ['source' => $this->article1->id(), 'target' => $this->article2->id()]; $mapRef = $this->_em->find(DDC117Reference::class, $idCriteria); $this->assertNotNull($mapRef); - $mapRef->setDescription("New Description!!"); + $mapRef->setDescription('New Description!!'); $this->_em->flush(); $this->_em->clear(); @@ -112,23 +121,23 @@ public function testUpdateAssociationEntity() /** * @group DDC-117 */ - public function testFetchDql() + public function testFetchDql(): void { - $dql = "SELECT r, s FROM Doctrine\Tests\Models\DDC117\DDC117Reference r JOIN r.source s WHERE s.title = ?1"; + $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(); - $this->assertTrue(count($refs) > 0, "Has to contain at least one Reference."); + $this->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."); + foreach ($refs as $ref) { + $this->assertInstanceOf(DDC117Reference::class, $ref, 'Contains only Reference instances.'); + $this->assertTrue($this->_em->contains($ref), 'Contains Reference in the IdentityMap.'); } } /** * @group DDC-117 */ - public function testRemoveCompositeElement() + public function testRemoveCompositeElement(): void { $idCriteria = ['source' => $this->article1->id(), 'target' => $this->article2->id()]; @@ -145,11 +154,11 @@ public function testRemoveCompositeElement() * @group DDC-117 * @group non-cacheable */ - public function testDqlRemoveCompositeElement() + public function testDqlRemoveCompositeElement(): void { $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"; + $dql = 'DELETE Doctrine\Tests\Models\DDC117\DDC117Reference r WHERE r.source = ?1 AND r.target = ?2'; $this->_em->createQuery($dql) ->setParameter(1, $this->article1->id()) ->setParameter(2, $this->article2->id()) @@ -161,27 +170,27 @@ public function testDqlRemoveCompositeElement() /** * @group DDC-117 */ - public function testInverseSideAccess() + public function testInverseSideAccess(): void { $this->article1 = $this->_em->find(DDC117Article::class, $this->article1->id()); $this->assertEquals(1, count($this->article1->references())); - foreach ($this->article1->references() AS $this->reference) { + foreach ($this->article1->references() as $this->reference) { $this->assertInstanceOf(DDC117Reference::class, $this->reference); $this->assertSame($this->article1, $this->reference->source()); } $this->_em->clear(); - $dql = 'SELECT a, r FROM Doctrine\Tests\Models\DDC117\DDC117Article a INNER JOIN a.references r WHERE a.id = ?1'; + $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) ->setParameter(1, $this->article1->id()) ->getSingleResult(); $this->assertEquals(1, count($this->article1->references())); - foreach ($this->article1->references() AS $this->reference) { + foreach ($this->article1->references() as $this->reference) { $this->assertInstanceOf(DDC117Reference::class, $this->reference); $this->assertSame($this->article1, $this->reference->source()); } @@ -190,7 +199,7 @@ public function testInverseSideAccess() /** * @group DDC-117 */ - public function testMixedCompositeKey() + public function testMixedCompositeKey(): void { $idCriteria = ['article' => $this->article1->id(), 'language' => 'en']; @@ -201,7 +210,7 @@ public function testMixedCompositeKey() $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'; + $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) ->setParameter(1, $this->article1->id()) ->setParameter(2, 'en') @@ -213,7 +222,7 @@ public function testMixedCompositeKey() /** * @group DDC-117 */ - public function testMixedCompositeKeyViolateUniqueness() + public function testMixedCompositeKeyViolateUniqueness(): void { $this->article1 = $this->_em->find(DDC117Article::class, $this->article1->id()); $this->article1->addTranslation('en', 'Bar'); @@ -223,39 +232,39 @@ public function testMixedCompositeKeyViolateUniqueness() try { // exception depending on the underlying Database Driver $this->_em->flush(); - } catch(\Exception $e) { + } catch (Exception $e) { $exceptionThrown = true; } - $this->assertTrue($exceptionThrown, "The underlying database driver throws an exception."); + $this->assertTrue($exceptionThrown, 'The underlying database driver throws an exception.'); } /** * @group DDC-117 */ - public function testOneToOneForeignObjectId() + public function testOneToOneForeignObjectId(): void { - $this->article1 = new DDC117Article("Foo"); + $this->article1 = new DDC117Article('Foo'); $this->_em->persist($this->article1); $this->_em->flush(); - $this->articleDetails = new DDC117ArticleDetails($this->article1, "Very long text"); + $this->articleDetails = new DDC117ArticleDetails($this->article1, 'Very long text'); $this->_em->persist($this->articleDetails); $this->_em->flush(); - $this->articleDetails->update("not so very long text!"); + $this->articleDetails->update('not so very long text!'); $this->_em->flush(); $this->_em->clear(); - /* @var $article DDC117Article */ $article = $this->_em->find(get_class($this->article1), $this->article1->id()); + assert($article instanceof DDC117Article); $this->assertEquals('not so very long text!', $article->getText()); } /** * @group DDC-117 */ - public function testOneToOneCascadeRemove() + public function testOneToOneCascadeRemove(): void { $article = $this->_em->find(get_class($this->article1), $this->article1->id()); $this->_em->remove($article); @@ -267,14 +276,14 @@ public function testOneToOneCascadeRemove() /** * @group DDC-117 */ - public function testOneToOneCascadePersist() + public function testOneToOneCascadePersist(): void { - 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->article1 = new DDC117Article('Foo'); + $this->articleDetails = new DDC117ArticleDetails($this->article1, 'Very long text'); $this->_em->persist($this->article1); $this->_em->flush(); @@ -285,12 +294,12 @@ public function testOneToOneCascadePersist() /** * @group DDC-117 */ - public function testReferencesToForeignKeyEntities() + public function testReferencesToForeignKeyEntities(): void { $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']; + $idCriteria = ['article' => $this->article1->id(), 'language' => 'en']; $translation = $this->_em->find(DDC117Translation::class, $idCriteria); $approveChanges = new DDC117ApproveChanges($reference->source()->getDetails(), $reference, $translation); @@ -308,10 +317,10 @@ public function testReferencesToForeignKeyEntities() /** * @group DDC-117 */ - public function testLoadOneToManyCollectionOfForeignKeyEntities() + public function testLoadOneToManyCollectionOfForeignKeyEntities(): void { - /* @var $article DDC117Article */ $article = $this->_em->find(get_class($this->article1), $this->article1->id()); + assert($article instanceof DDC117Article); $translations = $article->getTranslations(); $this->assertFalse($translations->isInitialized()); @@ -322,7 +331,7 @@ public function testLoadOneToManyCollectionOfForeignKeyEntities() /** * @group DDC-117 */ - public function testLoadManyToManyCollectionOfForeignKeyEntities() + public function testLoadManyToManyCollectionOfForeignKeyEntities(): void { $editor = $this->loadEditorFixture(); @@ -332,7 +341,7 @@ public function testLoadManyToManyCollectionOfForeignKeyEntities() $this->_em->clear(); - $dql = "SELECT e, t FROM Doctrine\Tests\Models\DDC117\DDC117Editor e JOIN e.reviewingTranslations t WHERE e.id = ?1"; + $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); @@ -341,7 +350,7 @@ public function testLoadManyToManyCollectionOfForeignKeyEntities() /** * @group DDC-117 */ - public function testClearManyToManyCollectionOfForeignKeyEntities() + public function testClearManyToManyCollectionOfForeignKeyEntities(): void { $editor = $this->loadEditorFixture(); $this->assertEquals(3, count($editor->reviewingTranslations)); @@ -357,7 +366,7 @@ public function testClearManyToManyCollectionOfForeignKeyEntities() /** * @group DDC-117 */ - public function testLoadInverseManyToManyCollection() + public function testLoadInverseManyToManyCollection(): void { $editor = $this->loadEditorFixture(); @@ -369,8 +378,8 @@ public function testLoadInverseManyToManyCollection() $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"; + $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) ->setParameter(1, $this->translation->getArticleId()) ->setParameter(2, $this->translation->getLanguage()) @@ -384,7 +393,7 @@ public function testLoadInverseManyToManyCollection() /** * @group DDC-117 */ - public function testLoadOneToManyOfSourceEntityWithAssociationIdentifier() + public function testLoadOneToManyOfSourceEntityWithAssociationIdentifier(): void { $editor = $this->loadEditorFixture(); @@ -392,32 +401,29 @@ public function testLoadOneToManyOfSourceEntityWithAssociationIdentifier() $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)); } - /** - * @return DDC117Editor - */ - private function loadEditorFixture() + private function loadEditorFixture(): DDC117Editor { - $editor = new DDC117Editor("beberlei"); + $editor = new DDC117Editor('beberlei'); - /* @var $article1 DDC117Article */ $article1 = $this->_em->find(get_class($this->article1), $this->article1->id()); - foreach ($article1->getTranslations() AS $translation) { + assert($article1 instanceof DDC117Article); + foreach ($article1->getTranslations() as $translation) { $editor->reviewingTranslations[] = $translation; } - /* @var $article2 DDC117Article */ $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!"); + assert($article2 instanceof DDC117Article); + $article2->addTranslation('de', 'Vanille-Krapferl'); // omnomnom + $article2->addTranslation('fr', "Sorry can't speak french!"); - foreach ($article2->getTranslations() AS $translation) { + foreach ($article2->getTranslations() as $translation) { $this->_em->persist($translation); // otherwise persisting the editor won't work, reachability! $editor->reviewingTranslations[] = $translation; } @@ -432,7 +438,7 @@ private function loadEditorFixture() /** * @group DDC-1519 */ - public function testMergeForeignKeyIdentifierEntity() + public function testMergeForeignKeyIdentifierEntity(): void { $idCriteria = ['source' => $this->article1->id(), 'target' => $this->article2->id()]; @@ -449,26 +455,26 @@ public function testMergeForeignKeyIdentifierEntity() /** * @group DDC-1652 */ - public function testArrayHydrationWithCompositeKey() + public function testArrayHydrationWithCompositeKey(): void { - $dql = "SELECT r,s,t FROM Doctrine\Tests\Models\DDC117\DDC117Reference r INNER JOIN r.source s INNER JOIN r.target t"; + $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()); $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->reference = new DDC117Reference($this->article2, $this->article1, 'Test-Description'); $this->_em->persist($this->reference); - $this->reference = new DDC117Reference($this->article1, $this->article1, "Test-Description"); + $this->reference = new DDC117Reference($this->article1, $this->article1, 'Test-Description'); $this->_em->persist($this->reference); - $this->reference = new DDC117Reference($this->article2, $this->article2, "Test-Description"); + $this->reference = new DDC117Reference($this->article2, $this->article2, 'Test-Description'); $this->_em->persist($this->reference); $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"; + $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(); $this->assertEquals($before + 3, count($data)); @@ -477,7 +483,7 @@ public function testArrayHydrationWithCompositeKey() /** * @group DDC-2246 */ - public function testGetEntityState() + public function testGetEntityState(): void { if ($this->isSecondLevelCacheEnabled) { $this->markTestIncomplete('Second level cache - not supported yet'); @@ -486,19 +492,20 @@ public function testGetEntityState() $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->reference = new DDC117Reference($this->article2, $this->article1, 'Test-Description'); - $this->assertEquals(\Doctrine\ORM\UnitOfWork::STATE_NEW, $this->_em->getUnitOfWork()->getEntityState($this->reference)); + $this->assertEquals(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)); + $this->assertEquals(UnitOfWork::STATE_MANAGED, $this->_em->getUnitOfWork()->getEntityState($reference)); } + /** * @group DDC-117 */ - public function testIndexByOnCompositeKeyField() + public function testIndexByOnCompositeKeyField(): void { $article = $this->_em->find(DDC117Article::class, $this->article1->id()); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1181Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1181Test.php index 55cff4c0272..1391ad0e134 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1181Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1181Test.php @@ -1,12 +1,14 @@ _schemaTool->createSchema( @@ -21,7 +23,7 @@ protected function setUp() : void /** * @group DDC-1181 */ - public function testIssue() + public function testIssue(): void { $hotel = new DDC1181Hotel(); $room1 = new DDC1181Room(); @@ -32,12 +34,12 @@ public function testIssue() $this->_em->persist($room2); $this->_em->flush(); - $booking1 = new DDC1181Booking; - $booking1->hotel = $hotel; - $booking1->room = $room1; - $booking2 = new DDC1181Booking; - $booking2->hotel = $hotel; - $booking2->room = $room2; + $booking1 = new DDC1181Booking(); + $booking1->hotel = $hotel; + $booking1->room = $room1; + $booking2 = new DDC1181Booking(); + $booking2->hotel = $hotel; + $booking2->room = $room2; $hotel->bookings[] = $booking1; $hotel->bookings[] = $booking2; @@ -65,7 +67,6 @@ class DDC1181Hotel * @var Booking[] */ public $bookings; - } /** @@ -75,7 +76,6 @@ class DDC1181Booking { /** * @var Hotel - * * @Id * @ManyToOne(targetEntity="DDC1181Hotel", inversedBy="bookings") * @JoinColumns({ @@ -85,7 +85,6 @@ class DDC1181Booking public $hotel; /** * @var Room - * * @Id * @ManyToOne(targetEntity="DDC1181Room") * @JoinColumns({ diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1193Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1193Test.php index 93044ae912d..88132e5a1fd 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1193Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1193Test.php @@ -1,20 +1,25 @@ _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), ] ); } @@ -22,10 +27,10 @@ protected function setUp() : void /** * @group DDC-1193 */ - public function testIssue() + public function testIssue(): void { $company = new DDC1193Company(); - $person = new DDC1193Person(); + $person = new DDC1193Person(); $account = new DDC1193Account(); $person->account = $account; @@ -43,9 +48,9 @@ public function testIssue() $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."); + $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.'); $this->_em->remove($company); $this->_em->flush(); @@ -55,7 +60,8 @@ public function testIssue() } /** @Entity */ -class DDC1193Company { +class DDC1193Company +{ /** * @Id @Column(type="integer") * @GeneratedValue @@ -64,29 +70,27 @@ class DDC1193Company { /** @OneToOne(targetEntity="DDC1193Person", cascade={"persist", "remove"}) */ public $member; - } /** @Entity */ -class DDC1193Person { +class DDC1193Person +{ /** * @Id @Column(type="integer") * @GeneratedValue */ public $id; - /** - * @OneToOne(targetEntity="DDC1193Account", cascade={"persist", "remove"}) - */ + /** @OneToOne(targetEntity="DDC1193Account", cascade={"persist", "remove"}) */ public $account; } /** @Entity */ -class DDC1193Account { +class DDC1193Account +{ /** * @Id @Column(type="integer") * @GeneratedValue */ public $id; - } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1209Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1209Test.php index 76b22e80b5e..ec96efdaa29 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1209Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1209Test.php @@ -1,12 +1,16 @@ _em->getClassMetadata(DDC1209_1::class), $this->_em->getClassMetadata(DDC1209_2::class), - $this->_em->getClassMetadata(DDC1209_3::class) + $this->_em->getClassMetadata(DDC1209_3::class), ] ); - } catch(\Exception $e) { + } catch (Exception $e) { } } /** * @group DDC-1209 */ - public function testIdentifierCanHaveCustomType() + public function testIdentifierCanHaveCustomType(): void { $entity = new DDC1209_3(); @@ -37,7 +41,7 @@ public function testIdentifierCanHaveCustomType() /** * @group DDC-1209 */ - public function testCompositeIdentifierCanHaveCustomType() + public function testCompositeIdentifierCanHaveCustomType(): void { $future1 = new DDC1209_1(); @@ -69,9 +73,7 @@ public function testCompositeIdentifierCanHaveCustomType() */ class DDC1209_1 { - /** - * @Id @GeneratedValue @Column(type="integer") - */ + /** @Id @GeneratedValue @Column(type="integer") */ private $id; public function getId() @@ -111,10 +113,10 @@ class DDC1209_2 public function __construct(DDC1209_1 $future1) { - $this->future1 = $future1; + $this->future1 = $future1; $this->starting_datetime = new DateTime2(); - $this->during_datetime = new DateTime2(); - $this->ending_datetime = new DateTime2(); + $this->during_datetime = new DateTime2(); + $this->ending_datetime = new DateTime2(); } } @@ -135,7 +137,7 @@ public function __construct() } } -class DateTime2 extends \DateTime +class DateTime2 extends DateTime { public function __toString() { diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1225Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1225Test.php index 7669f68337f..7cec13b09f8 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1225Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1225Test.php @@ -1,28 +1,34 @@ _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) { - + } catch (PDOException $e) { } } - public function testIssue() + public function testIssue(): void { $qb = $this->_em->createQueryBuilder(); $qb->from(DDC1225_TestEntity1::class, 'te1') @@ -50,18 +56,12 @@ class DDC1225_TestEntity1 */ private $testEntity2; - /** - * @param DDC1225_TestEntity2 $testEntity2 - */ - public function setTestEntity2(DDC1225_TestEntity2 $testEntity2) + public function setTestEntity2(DDC1225_TestEntity2 $testEntity2): void { $this->testEntity2 = $testEntity2; } - /** - * @return DDC1225_TestEntity2 - */ - public function getTestEntity2() + public function getTestEntity2(): DDC1225_TestEntity2 { return $this->testEntity2; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1228Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1228Test.php index 9cde55d64e8..bc0b3680118 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1228Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1228Test.php @@ -1,33 +1,37 @@ _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) { - + } catch (Exception $e) { } } - public function testOneToOnePersist() + public function testOneToOnePersist(): void { - $user = new DDC1228User; - $profile = new DDC1228Profile(); - $profile->name = "Foo"; + $user = new DDC1228User(); + $profile = new DDC1228Profile(); + $profile->name = 'Foo'; $user->profile = $profile; $this->_em->persist($user); @@ -37,25 +41,25 @@ public function testOneToOnePersist() $user = $this->_em->find(DDC1228User::class, $user->id); - $this->assertFalse($user->getProfile()->__isInitialized__, "Proxy is not initialized"); - $user->getProfile()->setName("Bar"); - $this->assertTrue($user->getProfile()->__isInitialized__, "Proxy is not initialized"); + $this->assertFalse($user->getProfile()->__isInitialized__, 'Proxy is not initialized'); + $user->getProfile()->setName('Bar'); + $this->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())); + $this->assertEquals('Bar', $user->getProfile()->getName()); + $this->assertEquals(['id' => 1, 'name' => 'Foo'], $this->_em->getUnitOfWork()->getOriginalEntityData($user->getProfile())); $this->_em->flush(); $this->_em->clear(); $user = $this->_em->find(DDC1228User::class, $user->id); - $this->assertEquals("Bar", $user->getProfile()->getName()); + $this->assertEquals('Bar', $user->getProfile()->getName()); } - public function testRefresh() + public function testRefresh(): void { - $user = new DDC1228User; - $profile = new DDC1228Profile(); - $profile->name = "Foo"; + $user = new DDC1228User(); + $profile = new DDC1228Profile(); + $profile->name = 'Foo'; $user->profile = $profile; $this->_em->persist($user); @@ -66,12 +70,12 @@ public function testRefresh() $user = $this->_em->getReference(DDC1228User::class, $user->id); $this->_em->refresh($user); - $user->name = "Baz"; + $user->name = 'Baz'; $this->_em->flush(); $this->_em->clear(); $user = $this->_em->find(DDC1228User::class, $user->id); - $this->assertEquals("Baz", $user->name); + $this->assertEquals('Baz', $user->name); } } @@ -126,7 +130,7 @@ public function getName() return $this->name; } - public function setName($name) + public function setName($name): void { $this->name = $name; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1238Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1238Test.php index f90de56f826..cdabee854ea 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1238Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1238Test.php @@ -1,30 +1,34 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1238User::class), + $this->_em->getClassMetadata(DDC1238User::class), ] ); - } catch(\Exception $e) { - + } catch (Exception $e) { } } - public function testIssue() + public function testIssue(): void { - $user = new DDC1238User; - $user->setName("test"); + $user = new DDC1238User(); + $user->setName('test'); $this->_em->persist($user); $this->_em->flush(); @@ -37,13 +41,13 @@ public function testIssue() $this->_em->clear(); $userId2 = $user->getId(); - $this->assertEquals($userId, $userId2, "This proxy can still be initialized."); + $this->assertEquals($userId, $userId2, 'This proxy can still be initialized.'); } - public function testIssueProxyClear() + public function testIssueProxyClear(): void { - $user = new DDC1238User; - $user->setName("test"); + $user = new DDC1238User(); + $user->setName('test'); $this->_em->persist($user); $this->_em->flush(); @@ -61,7 +65,7 @@ public function testIssueProxyClear() // 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"); + $this->assertNull($user->getId(), 'Now this is null, we already have a user instance of that type'); } } @@ -89,9 +93,8 @@ public function getName() return $this->name; } - public function setName($name) + public function setName($name): void { $this->name = $name; } } - diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1250Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1250Test.php index 6de949d0e91..a277d32918a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1250Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1250Test.php @@ -1,34 +1,36 @@ _schemaTool->createSchema( - [ - $this->_em->getClassMetadata(DDC1250ClientHistory::class), - ] + [$this->_em->getClassMetadata(DDC1250ClientHistory::class)] ); - } catch(\PDOException $e) { - + } catch (PDOException $e) { } } - public function testIssue() + public function testIssue(): void { - $c1 = new DDC1250ClientHistory; - $c2 = new DDC1250ClientHistory; + $c1 = new DDC1250ClientHistory(); + $c2 = new DDC1250ClientHistory(); $c1->declinedClientsHistory = $c2; - $c1->declinedBy = $c2; - $c2->declinedBy = $c1; - $c2->declinedClientsHistory= $c1; + $c1->declinedBy = $c2; + $c2->declinedBy = $c1; + $c2->declinedClientsHistory = $c1; $this->_em->persist($c1); $this->_em->persist($c2); @@ -47,22 +49,27 @@ public function testIssue() */ class DDC1250ClientHistory { - /** @Id @GeneratedValue @Column(type="integer") */ + /** + * @var int + * @Id @GeneratedValue @Column(type="integer") + */ public $id; - /** @OneToOne(targetEntity="DDC1250ClientHistory", inversedBy="declinedBy") + /** + * @var DDC1250ClientHistory + * @OneToOne(targetEntity="DDC1250ClientHistory", inversedBy="declinedBy") * @JoinColumn(name="declined_clients_history_id", referencedColumnName="id") */ public $declinedClientsHistory; /** + * @var DDC1250ClientHistory * @OneToOne(targetEntity="DDC1250ClientHistory", mappedBy="declinedClientsHistory") - * @var */ public $declinedBy; } -/** +/* * Entities\ClientsHistory: type: entity diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1276Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1276Test.php index 62b9d718a3d..755a0b2fd65 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1276Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1276Test.php @@ -1,42 +1,48 @@ useModelSet('cms'); parent::setUp(); } - public function testIssue() + public function testIssue(): void { - $user = new CmsUser(); - $user->name = "Benjamin"; - $user->username = "beberlei"; - $user->status = "active"; + $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; + $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); + $user = $this->_em->find(CmsUser::class, $user->id); $cloned = clone $user; $this->assertSame($user->groups, $cloned->groups); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1300Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1300Test.php index 71559da6b58..a1dc70defa4 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1300Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1300Test.php @@ -1,40 +1,47 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1300Foo::class), - $this->_em->getClassMetadata(DDC1300FooLocale::class), + $this->_em->getClassMetadata(DDC1300Foo::class), + $this->_em->getClassMetadata(DDC1300FooLocale::class), ] ); } - public function testIssue() + public function testIssue(): void { - $foo = new DDC1300Foo(); - $foo->_fooReference = "foo"; + $foo = new DDC1300Foo(); + $foo->_fooReference = 'foo'; $this->_em->persist($foo); $this->_em->flush(); - $locale = new DDC1300FooLocale(); - $locale->_foo = $foo; - $locale->_locale = "en"; - $locale->_title = "blub"; + $locale = new DDC1300FooLocale(); + $locale->_foo = $foo; + $locale->_locale = 'en'; + $locale->_title = 'blub'; $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)); @@ -70,13 +77,13 @@ class DDC1300Foo * Constructor * * @param array|Zend_Config|null $options + * * @return Bug_Model_Foo */ public function __construct($options = null) { - $this->_fooLocaleRefFoo = new \Doctrine\Common\Collections\ArrayCollection(); + $this->_fooLocaleRefFoo = new ArrayCollection(); } - } /** @@ -84,7 +91,6 @@ public function __construct($options = null) */ class DDC1300FooLocale { - /** * @ManyToOne(targetEntity="DDC1300Foo") * @JoinColumn(name="fooID", referencedColumnName="fooID") @@ -104,5 +110,4 @@ class DDC1300FooLocale * @Column(name="title", type="string", nullable=true, length=150) */ public $_title = null; - } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1301Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1301Test.php index 1fed1daf8a2..6ebda56b58a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1301Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1301Test.php @@ -1,127 +1,133 @@ useModelSet('legacy'); parent::setUp(); - $class = $this->_em->getClassMetadata(Models\Legacy\LegacyUser::class); - $class->associationMappings['_articles']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY; + $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->associationMappings['_cars']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY; $this->loadFixture(); } - public function tearDown() : void + public function tearDown(): void { parent::tearDown(); - $class = $this->_em->getClassMetadata(Models\Legacy\LegacyUser::class); - $class->associationMappings['_articles']['fetch'] = ClassMetadataInfo::FETCH_LAZY; + $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->associationMappings['_cars']['fetch'] = ClassMetadataInfo::FETCH_LAZY; } - public function testCountNotInitializesLegacyCollection() + public function testCountNotInitializesLegacyCollection(): void { - $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()); - 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."); + $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount(), 'Expecting two queries to be fired for count, then iteration.'); } - public function testCountNotInitializesLegacyCollectionWithForeignIdentifier() + public function testCountNotInitializesLegacyCollectionWithForeignIdentifier(): void { - $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()); - 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."); + $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount(), 'Expecting two queries to be fired for count, then iteration.'); } - public function testCountNotInitializesLegacyManyToManyCollection() + public function testCountNotInitializesLegacyManyToManyCollection(): void { - $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()); - 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."); + $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount(), 'Expecting two queries to be fired for count, then iteration.'); } - public function loadFixture() + public function loadFixture(): void { - $user1 = new Models\Legacy\LegacyUser(); - $user1->_username = "beberlei"; - $user1->_name = "Benjamin"; - $user1->_status = "active"; + $user1 = new Models\Legacy\LegacyUser(); + $user1->_username = 'beberlei'; + $user1->_name = 'Benjamin'; + $user1->_status = 'active'; - $user2 = new Models\Legacy\LegacyUser(); - $user2->_username = "jwage"; - $user2->_name = "Jonathan"; - $user2->_status = "active"; + $user2 = new Models\Legacy\LegacyUser(); + $user2->_username = 'jwage'; + $user2->_name = 'Jonathan'; + $user2->_status = 'active'; - $user3 = new Models\Legacy\LegacyUser(); - $user3->_username = "romanb"; - $user3->_name = "Roman"; - $user3->_status = "active"; + $user3 = new Models\Legacy\LegacyUser(); + $user3->_username = 'romanb'; + $user3->_name = 'Roman'; + $user3->_status = 'active'; $this->_em->persist($user1); $this->_em->persist($user2); $this->_em->persist($user3); - $article1 = new Models\Legacy\LegacyArticle(); - $article1->_topic = "Test"; - $article1->_text = "Test"; + $article1 = new Models\Legacy\LegacyArticle(); + $article1->_topic = 'Test'; + $article1->_text = 'Test'; $article1->setAuthor($user1); - $article2 = new Models\Legacy\LegacyArticle(); - $article2->_topic = "Test"; - $article2->_text = "Test"; + $article2 = new Models\Legacy\LegacyArticle(); + $article2->_topic = 'Test'; + $article2->_text = 'Test'; $article2->setAuthor($user1); $this->_em->persist($article1); $this->_em->persist($article2); - $car1 = new Models\Legacy\LegacyCar(); - $car1->_description = "Test1"; + $car1 = new Models\Legacy\LegacyCar(); + $car1->_description = 'Test1'; - $car2 = new Models\Legacy\LegacyCar(); - $car2->_description = "Test2"; + $car2 = new Models\Legacy\LegacyCar(); + $car2->_description = 'Test2'; - $car3 = new Models\Legacy\LegacyCar(); - $car3->_description = "Test3"; + $car3 = new Models\Legacy\LegacyCar(); + $car3->_description = 'Test3'; $user1->addCar($car1); $user1->addCar($car2); @@ -136,8 +142,8 @@ public function loadFixture() $this->_em->flush(); - $detail1 = new Models\Legacy\LegacyUserReference($user1, $user2, "foo"); - $detail2 = new Models\Legacy\LegacyUserReference($user1, $user3, "bar"); + $detail1 = new Models\Legacy\LegacyUserReference($user1, $user2, 'foo'); + $detail2 = new Models\Legacy\LegacyUserReference($user1, $user3, 'bar'); $this->_em->persist($detail1); $this->_em->persist($detail2); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1306Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1306Test.php index f5ca357bcce..e1d212da262 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1306Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1306Test.php @@ -1,44 +1,47 @@ useModelSet('cms'); parent::setUp(); } - public function testIssue() + public function testIssue(): void { - $phone = new CmsPhonenumber(); - $phone->phonenumber = "1234"; + $phone = new CmsPhonenumber(); + $phone->phonenumber = '1234'; // puts user and phone into commit order calculator $this->_em->persist($phone); $this->_em->flush(); - $address = new CmsAddress(); - $address->city = "bonn"; - $address->country = "Germany"; - $address->street = "somestreet!"; - $address->zip = 12345; + $address = new CmsAddress(); + $address->city = 'bonn'; + $address->country = 'Germany'; + $address->street = 'somestreet!'; + $address->zip = 12345; $this->_em->persist($address); - $user = new CmsUser(); - $user->username = "beberlei"; - $user->name = "benjamin"; - $user->status = "active"; + $user = new CmsUser(); + $user->username = 'beberlei'; + $user->name = 'benjamin'; + $user->status = 'active'; $user->setAddress($address); // puts user and address into commit order calculator, but does not calculate user dependencies new diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1335Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1335Test.php index 17f412ab26a..1e692658274 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1335Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1335Test.php @@ -1,42 +1,49 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1335User::class), - $this->_em->getClassMetadata(DDC1335Phone::class), + $this->_em->getClassMetadata(DDC1335User::class), + $this->_em->getClassMetadata(DDC1335Phone::class), ] ); $this->loadFixture(); - } catch(\Exception $e) { + } catch (Exception $e) { } } - - public function testDql() + public function testDql(): void { - $dql = 'SELECT u FROM ' . __NAMESPACE__ . '\DDC1335User u INDEX BY u.id'; - $query = $this->_em->createQuery($dql); - $result = $query->getResult(); + $dql = 'SELECT u FROM ' . __NAMESPACE__ . '\DDC1335User u INDEX BY u.id'; + $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); - $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); - $result = $query->getResult(); + $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); + $result = $query->getResult(); $this->assertEquals(sizeof($result), 3); $this->assertArrayHasKey('foo@foo.com', $result); @@ -47,8 +54,8 @@ public function testDql() $this->assertEquals(sizeof($result['bar@bar.com']->phones), 3); $this->assertEquals(sizeof($result['foobar@foobar.com']->phones), 3); - $foo = $result['foo@foo.com']->phones->toArray(); - $bar = $result['bar@bar.com']->phones->toArray(); + $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); @@ -64,7 +71,7 @@ public function testDql() $this->assertArrayHasKey(9, $foobar); } - public function testTicket() + public function testTicket(): void { $builder = $this->_em->createQueryBuilder(); $builder->select('u')->from(DDC1335User::class, 'u', 'u.id'); @@ -79,7 +86,7 @@ public function testTicket() $this->assertEquals('SELECT u FROM ' . __NAMESPACE__ . '\DDC1335User u INDEX BY u.id', $dql); } - public function testIndexByUnique() + public function testIndexByUnique(): void { $builder = $this->_em->createQueryBuilder(); $builder->select('u')->from(DDC1335User::class, 'u', 'u.email'); @@ -94,10 +101,10 @@ public function testIndexByUnique() $this->assertEquals('SELECT u FROM ' . __NAMESPACE__ . '\DDC1335User u INDEX BY u.email', $dql); } - public function testIndexWithJoin() + public function testIndexWithJoin(): void { $builder = $this->_em->createQueryBuilder(); - $builder->select('u','p') + $builder->select('u', 'p') ->from(DDC1335User::class, 'u', 'u.email') ->join('u.phones', 'p', null, null, 'p.id'); @@ -125,18 +132,18 @@ public function testIndexWithJoin() $this->assertArrayHasKey(8, $result['foobar@foobar.com']->phones->toArray()); $this->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); + $this->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() + private function loadFixture(): void { - $p1 = ['11 xxxx-xxxx','11 yyyy-yyyy','11 zzzz-zzzz']; - $p2 = ['22 xxxx-xxxx','22 yyyy-yyyy','22 zzzz-zzzz']; - $p3 = ['33 xxxx-xxxx','33 yyyy-yyyy','33 zzzz-zzzz']; + $p1 = ['11 xxxx-xxxx', '11 yyyy-yyyy', '11 zzzz-zzzz']; + $p2 = ['22 xxxx-xxxx', '22 yyyy-yyyy', '22 zzzz-zzzz']; + $p3 = ['33 xxxx-xxxx', '33 yyyy-yyyy', '33 zzzz-zzzz']; - $u1 = new DDC1335User("foo@foo.com", "Foo",$p1); - $u2 = new DDC1335User("bar@bar.com", "Bar",$p2); - $u3 = new DDC1335User("foobar@foobar.com", "Foo Bar",$p3); + $u1 = new DDC1335User('foo@foo.com', 'Foo', $p1); + $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); @@ -144,7 +151,6 @@ private function loadFixture() $this->_em->flush(); $this->_em->clear(); } - } /** @@ -158,29 +164,23 @@ class DDC1335User */ public $id; - /** - * @Column(type="string", unique=true) - */ + /** @Column(type="string", unique=true) */ public $email; - /** - * @Column(type="string") - */ + /** @Column(type="string") */ public $name; - /** - * @OneToMany(targetEntity="DDC1335Phone", mappedBy="user", cascade={"persist", "remove"}) - */ + /** @OneToMany(targetEntity="DDC1335Phone", mappedBy="user", cascade={"persist", "remove"}) */ public $phones; public function __construct($email, $name, array $numbers = []) { $this->name = $name; $this->email = $email; - $this->phones = new \Doctrine\Common\Collections\ArrayCollection(); + $this->phones = new ArrayCollection(); foreach ($numbers as $number) { - $this->phones->add(new DDC1335Phone($this,$number)); + $this->phones->add(new DDC1335Phone($this, $number)); } } } @@ -197,9 +197,7 @@ class DDC1335Phone */ public $id; - /** - * @Column(name="numericalValue", type="string", nullable = false) - */ + /** @Column(name="numericalValue", type="string", nullable = false) */ public $numericalValue; /** @@ -210,7 +208,7 @@ class DDC1335Phone public function __construct($user, $number) { - $this->user = $user; - $this->numericalValue = $number; + $this->user = $user; + $this->numericalValue = $number; } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1360Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1360Test.php index 6e71e6fc742..333bb7a032a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1360Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1360Test.php @@ -1,5 +1,7 @@ _em->getConnection()->getDatabasePlatform()->getName() != "postgresql") { - $this->markTestSkipped("PostgreSQL only test."); + if ($this->_em->getConnection()->getDatabasePlatform()->getName() !== 'postgresql') { + $this->markTestSkipped('PostgreSQL only test.'); } $sql = $this->_schemaTool->getCreateSchemaSql( [ - $this->_em->getClassMetadata(DDC1360DoubleQuote::class) + $this->_em->getClassMetadata(DDC1360DoubleQuote::class), ] ); $this->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 + ); } } @@ -38,4 +42,3 @@ class DDC1360DoubleQuote /** @Id @GeneratedValue @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 index 8720ab6a950..4f663d41e54 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1383Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1383Test.php @@ -1,56 +1,67 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1383AbstractEntity::class), - $this->_em->getClassMetadata(DDC1383Entity::class), + $this->_em->getClassMetadata(DDC1383AbstractEntity::class), + $this->_em->getClassMetadata(DDC1383Entity::class), ] ); - } catch(\Exception $ignored) {} + } catch (Exception $ignored) { + } } - public function testFailingCase() + public function testFailingCase(): void { - $parent = new DDC1383Entity(); - $child = new DDC1383Entity(); + $parent = new DDC1383Entity(); + $child = new DDC1383Entity(); - $child->setReference($parent); + $child->setReference($parent); - $this->_em->persist($parent); - $this->_em->persist($child); + $this->_em->persist($parent); + $this->_em->persist($child); - $id = $child->getId(); + $id = $child->getId(); - $this->_em->flush(); - $this->_em->clear(); + $this->_em->flush(); + $this->_em->clear(); - // Try merging the parent entity - $child = $this->_em->merge($child); - $parent = $child->getReference(); + // 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 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'); + // Parent is NOT instance of entity + self::assertTrue( + $parent instanceof DDC1383Entity, + 'Entity class is ' . get_class($parent) . ', "DDC1383Entity" was expected' + ); $this->assertHasDeprecationMessages(); } } @@ -63,22 +74,22 @@ public function testFailingCase() */ abstract class DDC1383AbstractEntity { - /** - * @Id - * @Column(type="integer") - * @GeneratedValue - */ - protected $id; - - public function getId() - { - return $this->id; - } - - public function setId($id) - { - $this->id = $id; - } + /** + * @Id + * @Column(type="integer") + * @GeneratedValue + */ + protected $id; + + public function getId() + { + return $this->id; + } + + public function setId($id): void + { + $this->id = $id; + } } /** @@ -86,18 +97,16 @@ public function setId($id) */ class DDC1383Entity extends DDC1383AbstractEntity { - /** - * @ManyToOne(targetEntity="DDC1383AbstractEntity") - */ - protected $reference; - - public function getReference() - { - return $this->reference; - } - - public function setReference(DDC1383AbstractEntity $reference) - { - $this->reference = $reference; - } + /** @ManyToOne(targetEntity="DDC1383AbstractEntity") */ + protected $reference; + + public function getReference() + { + return $this->reference; + } + + public function setReference(DDC1383AbstractEntity $reference): void + { + $this->reference = $reference; + } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1392Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1392Test.php index 5d6dd660728..dda2f839688 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1392Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1392Test.php @@ -1,37 +1,41 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1392File::class), - $this->_em->getClassMetadata(DDC1392Picture::class), + $this->_em->getClassMetadata(DDC1392File::class), + $this->_em->getClassMetadata(DDC1392Picture::class), ] ); - } catch (\Exception $ignored) { + } catch (Exception $ignored) { } } - public function testFailingCase() + public function testFailingCase(): void { - $file = new DDC1392File; + $file = new DDC1392File(); - $picture = new DDC1392Picture; + $picture = new DDC1392Picture(); $picture->setFile($file); $em = $this->_em; @@ -39,13 +43,13 @@ public function testFailingCase() $em->flush(); $em->clear(); - $fileId = $file->getFileId(); + $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."); + $this->assertEquals(UnitOfWork::STATE_MANAGED, $em->getUnitOfWork()->getEntityState($picture->getFile()), 'Lazy Proxy should be marked MANAGED.'); $file = $picture->getFile(); @@ -60,7 +64,7 @@ public function testFailingCase() $em->flush(); - $q = $this->_em->createQuery("SELECT COUNT(e) FROM " . __NAMESPACE__ . '\DDC1392File e'); + $q = $this->_em->createQuery('SELECT COUNT(e) FROM ' . __NAMESPACE__ . '\DDC1392File e'); $result = $q->getSingleScalarResult(); self::assertEquals(1, $result); @@ -96,7 +100,7 @@ public function getPictureId() /** * Set file */ - public function setFile($value = null) + public function setFile($value = null): void { $this->file = $value; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1400Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1400Test.php index 0f0a41aa9ba..1c574e4aae9 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1400Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1400Test.php @@ -1,13 +1,18 @@ _em->getClassMetadata(DDC1400UserState::class), ] ); - } catch (\Exception $ignored) { + } catch (Exception $ignored) { } } - public function testFailingCase() + public function testFailingCase(): void { - $article = new DDC1400Article; - $user1 = new DDC1400User; - $user2 = new DDC1400User; + $article = new DDC1400Article(); + $user1 = new DDC1400User(); + $user2 = new DDC1400User(); $this->_em->persist($article); $this->_em->persist($user1); $this->_em->persist($user2); $this->_em->flush(); - $userState1 = new DDC1400UserState; - $userState1->article = $article; + $userState1 = new DDC1400UserState(); + $userState1->article = $article; $userState1->articleId = $article->id; - $userState1->user = $user1; - $userState1->userId = $user1->id; + $userState1->user = $user1; + $userState1->userId = $user1->id; - $userState2 = new DDC1400UserState; - $userState2->article = $article; + $userState2 = new DDC1400UserState(); + $userState2->article = $article; $userState2->articleId = $article->id; - $userState2->user = $user2; - $userState2->userId = $user2->id; + $userState2->user = $user2; + $userState2->userId = $user2->id; $this->_em->persist($userState1); $this->_em->persist($userState2); @@ -77,9 +82,7 @@ class DDC1400Article */ public $id; - /** - * @OneToMany(targetEntity="DDC1400UserState", mappedBy="article", indexBy="userId", fetch="EXTRA_LAZY") - */ + /** @OneToMany(targetEntity="DDC1400UserState", mappedBy="article", indexBy="userId", fetch="EXTRA_LAZY") */ public $userStates; } @@ -88,7 +91,6 @@ class DDC1400Article */ class DDC1400User { - /** * @Id * @Column(type="integer") @@ -96,9 +98,7 @@ class DDC1400User */ public $id; - /** - * @OneToMany(targetEntity="DDC1400UserState", mappedBy="user", indexBy="articleId", fetch="EXTRA_LAZY") - */ + /** @OneToMany(targetEntity="DDC1400UserState", mappedBy="user", indexBy="articleId", fetch="EXTRA_LAZY") */ public $userStates; } @@ -107,27 +107,21 @@ class DDC1400User */ class DDC1400UserState { - /** - * @Id + * @Id * @ManyToOne(targetEntity="DDC1400Article", inversedBy="userStates") */ public $article; /** - * @Id + * @Id * @ManyToOne(targetEntity="DDC1400User", inversedBy="userStates") */ public $user; - /** - * @Column(name="user_id", type="integer") - */ + /** @Column(name="user_id", type="integer") */ public $userId; - /** - * @Column(name="article_id", type="integer") - */ + /** @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 419225ed149..00e29bb3413 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1404Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1404Test.php @@ -1,65 +1,65 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1404ParentEntity::class), - $this->_em->getClassMetadata(DDC1404ChildEntity::class), + $this->_em->getClassMetadata(DDC1404ParentEntity::class), + $this->_em->getClassMetadata(DDC1404ChildEntity::class), ] ); $this->loadFixtures(); - } catch (Exception $exc) { } } - public function testTicket() + public function testTicket(): void { - $repository = $this->_em->getRepository(DDC1404ChildEntity::class); - $queryAll = $repository->createNamedQuery('all'); - $queryFirst = $repository->createNamedQuery('first'); - $querySecond = $repository->createNamedQuery('second'); - + $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()); - $this->assertEquals(sizeof($queryAll->getResult()), 2); $this->assertEquals(sizeof($queryFirst->getResult()), 1); $this->assertEquals(sizeof($querySecond->getResult()), 1); } - - public function loadFixtures() + public function loadFixtures(): void { - $c1 = new DDC1404ChildEntity("ChildEntity 1"); - $c2 = new DDC1404ChildEntity("ChildEntity 2"); + $c1 = new DDC1404ChildEntity('ChildEntity 1'); + $c2 = new DDC1404ChildEntity('ChildEntity 2'); $this->_em->persist($c1); $this->_em->persist($c2); $this->_em->flush(); } - } /** * @MappedSuperclass - * * @NamedQueries({ * @NamedQuery(name="all", query="SELECT p FROM __CLASS__ p"), * @NamedQuery(name="first", query="SELECT p FROM __CLASS__ p WHERE p.id = 1"), @@ -67,7 +67,6 @@ public function loadFixtures() */ class DDC1404ParentEntity { - /** * @Id * @Column(type="integer") @@ -75,19 +74,14 @@ class DDC1404ParentEntity */ protected $id; - /** - * @return int - */ - public function getId() + public function getId(): int { return $this->id; } - } /** * @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") @@ -95,34 +89,21 @@ public function getId() */ class DDC1404ChildEntity extends DDC1404ParentEntity { - - /** - * @column(type="string") - */ + /** @column(type="string") */ private $name; - /** - * @param string $name - */ - public function __construct($name) + public function __construct(string $name) { $this->name = $name; } - /** - * @return string - */ - public function getName() + public function getName(): string { return $this->name; } - /** - * @param string $name - */ - public function setName($name) + public function setName(string $name): void { $this->name = $name; } - } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC142Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC142Test.php index ae455f546a2..0bd6ea7bf64 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC142Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC142Test.php @@ -1,32 +1,34 @@ useModelSet('quote'); parent::setUp(); } - public function testCreateRetrieveUpdateDelete() + public function testCreateRetrieveUpdateDelete(): void { - - $user = new User; - $user->name = 'FabioBatSilva'; + $user = new User(); + $user->name = 'FabioBatSilva'; $this->_em->persist($user); - $address = new Address; - $address->zip = '12345'; + $address = new Address(); + $address->zip = '12345'; $this->_em->persist($address); $this->_em->flush(); @@ -41,9 +43,8 @@ public function testCreateRetrieveUpdateDelete() $id = $user->id; $this->assertNotNull($id); - - $user = $this->_em->find(User::class, $id); - $address = $user->getAddress(); + $user = $this->_em->find(User::class, $id); + $address = $user->getAddress(); $this->assertInstanceOf(User::class, $user); $this->assertInstanceOf(Address::class, $user->getAddress()); @@ -51,28 +52,24 @@ public function testCreateRetrieveUpdateDelete() $this->assertEquals('FabioBatSilva', $user->name); $this->assertEquals('12345', $address->zip); - - $user->name = 'FabioBatSilva1'; - $user->address = null; + $user->name = 'FabioBatSilva1'; + $user->address = null; $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); - $this->_em->remove($user); $this->_em->flush(); $this->_em->clear(); $this->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 138eeb7e59f..bd50eb57a59 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1430Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1430Test.php @@ -1,30 +1,38 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1430Order::class), - $this->_em->getClassMetadata(DDC1430OrderProduct::class), + $this->_em->getClassMetadata(DDC1430Order::class), + $this->_em->getClassMetadata(DDC1430OrderProduct::class), ] ); $this->loadFixtures(); - } catch (\Exception $exc) { - + } catch (Exception $exc) { } } - public function testOrderByFields() + public function testOrderByFields(): void { $repository = $this->_em->getRepository(DDC1430Order::class); $builder = $repository->createQueryBuilder('o'); @@ -37,7 +45,6 @@ public function testOrderByFields() $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()); - $result = $query->getResult(); $this->assertEquals(2, sizeof($result)); @@ -55,7 +62,7 @@ public function testOrderByFields() $this->assertEquals(3, $result[1]['p_count']); } - public function testOrderByAllObjectFields() + public function testOrderByAllObjectFields(): void { $repository = $this->_em->getRepository(DDC1430Order::class); $builder = $repository->createQueryBuilder('o'); @@ -65,13 +72,11 @@ public function testOrderByAllObjectFields() ->orderBy('o.id') ->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()); $result = $query->getResult(); - $this->assertEquals(2, sizeof($result)); $this->assertTrue($result[0][0] instanceof DDC1430Order); @@ -84,7 +89,7 @@ public function testOrderByAllObjectFields() $this->assertEquals($result[1]['p_count'], 3); } - public function testTicket() + public function testTicket(): void { $repository = $this->_em->getRepository(DDC1430Order::class); $builder = $repository->createQueryBuilder('o'); @@ -94,11 +99,9 @@ public function testTicket() ->orderBy('o.id') ->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()); - $result = $query->getResult(); $this->assertEquals(2, sizeof($result)); @@ -113,7 +116,7 @@ public function testTicket() $this->assertEquals($result[1]['p_count'], 3); } - public function loadFixtures() + public function loadFixtures(): void { $o1 = new DDC1430Order('NEW'); $o2 = new DDC1430Order('OK'); @@ -130,7 +133,6 @@ public function loadFixtures() $this->_em->flush(); } - } /** @@ -138,7 +140,6 @@ public function loadFixtures() */ class DDC1430Order { - /** * @Id * @Column(name="order_id", type="integer") @@ -146,27 +147,19 @@ class DDC1430Order */ protected $id; - /** - * @Column(name="created_at", type="datetime") - */ + /** @Column(name="created_at", type="datetime") */ private $date; - /** - * @Column(name="order_status", type="string") - */ + /** @Column(name="order_status", type="string") */ private $status; /** * @OneToMany(targetEntity="DDC1430OrderProduct", mappedBy="order", cascade={"persist", "remove"}) - * - * @var \Doctrine\Common\Collections\ArrayCollection $products + * @var ArrayCollection $products */ private $products; - /** - * @return int - */ - public function getId() + public function getId(): int { return $this->id; } @@ -174,45 +167,31 @@ public function getId() public function __construct($status) { $this->status = $status; - $this->date = new \DateTime(); - $this->products = new \Doctrine\Common\Collections\ArrayCollection(); + $this->date = new DateTime(); + $this->products = new ArrayCollection(); } - /** - * @return \DateTime - */ - public function getDate() + + public function getDate(): DateTime { return $this->date; } - /** - * @return string - */ - public function getStatus() + public function getStatus(): string { return $this->status; } - /** - * @param string $status - */ - public function setStatus($status) + public function setStatus(string $status): void { $this->status = $status; } - /** - * @return \Doctrine\Common\Collections\ArrayCollection - */ - public function getProducts() + public function getProducts(): ArrayCollection { return $this->products; } - /** - * @param DDC1430OrderProduct $product - */ - public function addProduct(DDC1430OrderProduct $product) + public function addProduct(DDC1430OrderProduct $product): void { $product->setOrder($this); $this->products->add($product); @@ -224,73 +203,50 @@ public function addProduct(DDC1430OrderProduct $product) */ class DDC1430OrderProduct { - /** - * @Id - * @Column(type="integer") - * @GeneratedValue() - */ + * @Id + * @Column(type="integer") + * @GeneratedValue() + */ protected $id; /** * @var DDC1430Order $order - * * @ManyToOne(targetEntity="DDC1430Order", inversedBy="products") * @JoinColumn(name="order_id", referencedColumnName="order_id", nullable = false) */ private $order; - /** - * @column(type="float") - */ + /** @column(type="float") */ private $value; - /** - * @param float $value - */ - public function __construct($value) + public function __construct(float $value) { $this->value = $value; } - /** - * @return int - */ - public function getId() + public function getId(): int { return $this->id; } - /** - * @return DDC1430Order - */ - public function getOrder() + public function getOrder(): DDC1430Order { return $this->order; } - /** - * @param DDC1430Order $order - */ - public function setOrder(DDC1430Order $order) + public function setOrder(DDC1430Order $order): void { $this->order = $order; } - /** - * @return float - */ - public function getValue() + public function getValue(): float { return $this->value; } - /** - * @param float $value - */ - public function setValue($value) + public function setValue(float $value): void { $this->value = $value; } - } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1436Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1436Test.php index 8c44942b51a..2752c9803d2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1436Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1436Test.php @@ -1,27 +1,32 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1436Page::class), + $this->_em->getClassMetadata(DDC1436Page::class), ] ); - } catch (\Exception $ignored) { + } catch (Exception $ignored) { } } - public function testIdentityMap() + public function testIdentityMap(): void { // fixtures $parent = null; @@ -31,6 +36,7 @@ public function testIdentityMap() $this->_em->persist($page); $parent = $page; } + $this->_em->flush(); $this->_em->clear(); @@ -74,17 +80,13 @@ public function getId() return $this->id; } - /** - * @return DDC1436Page - */ - public function getParent() + public function getParent(): DDC1436Page { return $this->parent; } - public function setParent($parent) + public function setParent($parent): void { $this->parent = $parent; } } - diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC144Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC144Test.php index 1c68764a7b3..9bf70625a94 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC144Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC144Test.php @@ -1,12 +1,14 @@ property = 'flowValue'; + $operand = new DDC144Operand(); + $operand->property = 'flowValue'; $operand->operandProperty = 'operandValue'; $this->_em->persist($operand); @@ -55,7 +57,7 @@ class DDC144FlowElement abstract class DDC144Expression extends DDC144FlowElement { - abstract public function method(); + abstract public function method(): void; } /** @Entity @Table(name="ddc144_operands") */ @@ -64,7 +66,7 @@ class DDC144Operand extends DDC144Expression /** @Column */ public $operandProperty; - public function method() + public function method(): void { } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1452Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1452Test.php index 59d97360509..67a073b94c8 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1452Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1452Test.php @@ -1,18 +1,23 @@ useModelSet('cms'); parent::setUp(); @@ -20,25 +25,25 @@ protected function setUp() : void try { $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) { + } catch (Exception $ignored) { } } - public function testIssue() + public function testIssue(): void { - $a1 = new DDC1452EntityA(); - $a1->title = "foo"; + $a1 = new DDC1452EntityA(); + $a1->title = 'foo'; - $a2 = new DDC1452EntityA(); - $a2->title = "bar"; + $a2 = new DDC1452EntityA(); + $a2->title = 'bar'; - $b = new DDC1452EntityB(); + $b = new DDC1452EntityB(); $b->entityAFrom = $a1; - $b->entityATo = $a2; + $b->entityATo = $a2; $this->_em->persist($a1); $this->_em->persist($a2); @@ -46,41 +51,41 @@ public function testIssue() $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"; + $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(); $this->assertSame($results[0], $results[0]->entitiesB[0]->entityAFrom); - $this->assertFalse( $results[0]->entitiesB[0]->entityATo instanceof Proxy); + $this->assertFalse($results[0]->entitiesB[0]->entityATo instanceof Proxy); $this->assertInstanceOf(Collection::class, $results[0]->entitiesB[0]->entityATo->getEntitiesB()); } - public function testFetchJoinOneToOneFromInverse() + public function testFetchJoinOneToOneFromInverse(): void { - $address = new \Doctrine\Tests\Models\CMS\CmsAddress(); - $address->city = "Bonn"; - $address->country = "Germany"; - $address->street = "Somestreet"; - $address->zip = 12345; - - $user = new CmsUser(); - $user->name = "beberlei"; - $user->username = "beberlei"; - $user->status = "active"; - $user->address = $address; - $address->user = $user; + $address = new CmsAddress(); + $address->city = 'Bonn'; + $address->country = 'Germany'; + $address->street = 'Somestreet'; + $address->zip = 12345; + + $user = new CmsUser(); + $user->name = 'beberlei'; + $user->username = 'beberlei'; + $user->status = 'active'; + $user->address = $address; + $address->user = $user; $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"; + $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(); $this->assertFalse($data[0]->user instanceof Proxy); - $dql = "SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.address a"; + $dql = 'SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.address a'; $data = $this->_em->createQuery($dql)->getResult(); $this->assertFalse($data[0]->address instanceof Proxy); @@ -118,12 +123,8 @@ class DDC1452EntityB /** @Id @Column(type="integer") @GeneratedValue */ public $id; - /** - * @ManyToOne(targetEntity="DDC1452EntityA", inversedBy="entitiesB") - */ + /** @ManyToOne(targetEntity="DDC1452EntityA", inversedBy="entitiesB") */ public $entityAFrom; - /** - * @ManyToOne(targetEntity="DDC1452EntityA") - */ + /** @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 93de4f0a168..bcfe2921430 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1454Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1454Test.php @@ -1,15 +1,22 @@ _em->getClassMetadata(DDC1454Picture::class), ] ); - } catch (\Exception $ignored) { + } catch (Exception $ignored) { } } - public function testFailingCase() + public function testFailingCase(): void { $pic = new DDC1454Picture(); @@ -65,5 +72,4 @@ public function getFileId() { return $this->fileId; } - } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1458Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1458Test.php index ef2b5599722..7aa22acf07f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1458Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1458Test.php @@ -1,23 +1,25 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(TestEntity::class), - $this->_em->getClassMetadata(TestAdditionalEntity::class) + $this->_em->getClassMetadata(TestEntity::class), + $this->_em->getClassMetadata(TestAdditionalEntity::class), ] ); } - public function testIssue() + public function testIssue(): void { $testEntity = new TestEntity(); $testEntity->setValue(3); @@ -63,13 +65,9 @@ class TestEntity * @GeneratedValue(strategy="AUTO") */ protected $id; - /** - * @Column(type="integer") - */ + /** @Column(type="integer") */ protected $value; - /** - * @OneToOne(targetEntity="TestAdditionalEntity", inversedBy="entity", orphanRemoval=true, cascade={"persist", "remove"}) - */ + /** @OneToOne(targetEntity="TestAdditionalEntity", inversedBy="entity", orphanRemoval=true, cascade={"persist", "remove"}) */ protected $additional; public function getValue() @@ -77,7 +75,7 @@ public function getValue() return $this->value; } - public function setValue($value) + public function setValue($value): void { $this->value = $value; } @@ -87,7 +85,7 @@ public function getAdditional() return $this->additional; } - public function setAdditional($additional) + public function setAdditional($additional): void { $this->additional = $additional; } @@ -103,13 +101,9 @@ class TestAdditionalEntity * @GeneratedValue(strategy="AUTO") */ protected $id; - /** - * @OneToOne(targetEntity="TestEntity", mappedBy="additional") - */ + /** @OneToOne(targetEntity="TestEntity", mappedBy="additional") */ protected $entity; - /** - * @Column(type="boolean") - */ + /** @Column(type="boolean") */ protected $bool; public function __construct() @@ -122,7 +116,7 @@ public function getBool() return $this->bool; } - public function setBool($bool) + public function setBool($bool): void { $this->bool = $bool; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1461Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1461Test.php index c0aaf1afc90..64f1795941a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1461Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1461Test.php @@ -1,38 +1,45 @@ _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) { - + } catch (Exception $e) { } } - public function testChangeDetectionDeferredExplicit() + public function testChangeDetectionDeferredExplicit(): void { - $user = new DDC1461User; + $user = new DDC1461User(); $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."); + $this->assertEquals(UnitOfWork::STATE_MANAGED, $this->_em->getUnitOfWork()->getEntityState($user, UnitOfWork::STATE_NEW), 'Entity should be managed.'); + $this->assertEquals(UnitOfWork::STATE_MANAGED, $this->_em->getUnitOfWork()->getEntityState($user), 'Entity should be managed.'); - $acc = new DDC1461TwitterAccount; + $acc = new DDC1461TwitterAccount(); $user->twitterAccount = $acc; $this->_em->persist($user); @@ -76,8 +83,6 @@ class DDC1461TwitterAccount */ public $id; - /** - * @OneToOne(targetEntity="DDC1461User", fetch="EAGER") - */ + /** @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 index 8d8f3add744..596b0613890 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1509Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1509Test.php @@ -1,45 +1,50 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1509AbstractFile::class), - $this->_em->getClassMetadata(DDC1509File::class), - $this->_em->getClassMetadata(DDC1509Picture::class), + $this->_em->getClassMetadata(DDC1509AbstractFile::class), + $this->_em->getClassMetadata(DDC1509File::class), + $this->_em->getClassMetadata(DDC1509Picture::class), ] ); - } catch (\Exception $ignored) { - + } catch (Exception $ignored) { } } - public function testFailingCase() + public function testFailingCase(): void { - $file = new DDC1509File; - $thumbnail = new DDC1509File; + $file = new DDC1509File(); + $thumbnail = new DDC1509File(); - $picture = new DDC1509Picture; + $picture = new DDC1509Picture(); $picture->setFile($file); $picture->setThumbnail($thumbnail); - - /* @var $em \Doctrine\ORM\EntityManager */ $em = $this->_em; + assert($em instanceof EntityManager); $em->persist($picture); $em->flush(); $em->clear(); @@ -47,13 +52,12 @@ public function testFailingCase() $id = $picture->getPictureId(); $pic = $em->merge($picture); - /* @var $pic DDC1509Picture */ + assert($pic instanceof DDC1509Picture); $this->assertNotNull($pic->getThumbnail()); $this->assertNotNull($pic->getFile()); $this->assertHasDeprecationMessages(); } - } /** @@ -61,7 +65,6 @@ public function testFailingCase() */ class DDC1509Picture { - /** * @Column(type="integer") * @Id @@ -69,14 +72,10 @@ class DDC1509Picture */ private $id; - /** - * @ManyToOne(targetEntity="DDC1509AbstractFile", cascade={"persist", "remove"}) - */ + /** @ManyToOne(targetEntity="DDC1509AbstractFile", cascade={"persist", "remove"}) */ private $thumbnail; - /** - * @ManyToOne(targetEntity="DDC1509AbstractFile", cascade={"persist", "remove"}) - */ + /** @ManyToOne(targetEntity="DDC1509AbstractFile", cascade={"persist", "remove"}) */ private $file; /** @@ -90,7 +89,7 @@ public function getPictureId() /** * Set file */ - public function setFile($value = null) + public function setFile($value = null): void { $this->file = $value; } @@ -108,11 +107,10 @@ public function getThumbnail() return $this->thumbnail; } - public function setThumbnail($thumbnail) + public function setThumbnail($thumbnail): void { $this->thumbnail = $thumbnail; } - } /** @@ -123,7 +121,6 @@ public function setThumbnail($thumbnail) */ class DDC1509AbstractFile { - /** * @Column(type="integer") * @Id @@ -138,7 +135,6 @@ public function getFileId() { return $this->id; } - } /** @@ -146,5 +142,4 @@ public function getFileId() */ 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 25e32602a6a..20273dffd50 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1514Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1514Test.php @@ -1,48 +1,52 @@ _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) { + } catch (Exception $ignored) { } } - public function testIssue() + public function testIssue(): void { - $a1 = new DDC1514EntityA(); - $a1->title = "1foo"; + $a1 = new DDC1514EntityA(); + $a1->title = '1foo'; - $a2 = new DDC1514EntityA(); - $a2->title = "2bar"; + $a2 = new DDC1514EntityA(); + $a2->title = '2bar'; - $b1 = new DDC1514EntityB(); + $b1 = new DDC1514EntityB(); $b1->entityAFrom = $a1; - $b1->entityATo = $a2; + $b1->entityATo = $a2; - $b2 = new DDC1514EntityB(); + $b2 = new DDC1514EntityB(); $b2->entityAFrom = $a2; - $b2->entityATo = $a1; + $b2->entityATo = $a1; - $c = new DDC1514EntityC(); - $c->title = "baz"; + $c = new DDC1514EntityC(); + $c->title = 'baz'; $a2->entityC = $c; $this->_em->persist($a1); @@ -53,7 +57,7 @@ public function testIssue() $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"; + $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(); $this->assertEquals($a1->id, $results[0]->id); @@ -92,13 +96,9 @@ class DDC1514EntityB /** @Id @Column(type="integer") @GeneratedValue */ public $id; - /** - * @ManyToOne(targetEntity="DDC1514EntityA", inversedBy="entitiesB") - */ + /** @ManyToOne(targetEntity="DDC1514EntityA", inversedBy="entitiesB") */ public $entityAFrom; - /** - * @ManyToOne(targetEntity="DDC1514EntityA") - */ + /** @ManyToOne(targetEntity="DDC1514EntityA") */ public $entityATo; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1515Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1515Test.php index 300413eb7fc..44bd3a54556 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1515Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1515Test.php @@ -1,31 +1,34 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1515Foo::class), - $this->_em->getClassMetadata(DDC1515Bar::class), + $this->_em->getClassMetadata(DDC1515Foo::class), + $this->_em->getClassMetadata(DDC1515Bar::class), ] ); } - public function testIssue() + public function testIssue(): void { $bar = new DDC1515Bar(); $this->_em->persist($bar); $this->_em->flush(); - $foo = new DDC1515Foo(); + $foo = new DDC1515Foo(); $foo->bar = $bar; $this->_em->persist($foo); $this->_em->flush(); @@ -41,9 +44,7 @@ public function testIssue() */ class DDC1515Foo { - /** - * @OneToOne(targetEntity="DDC1515Bar", inversedBy="foo") @Id - */ + /** @OneToOne(targetEntity="DDC1515Bar", inversedBy="foo") @Id */ public $bar; } @@ -52,13 +53,9 @@ class DDC1515Foo */ class DDC1515Bar { - /** - * @Id @Column(type="integer") @GeneratedValue - */ + /** @Id @Column(type="integer") @GeneratedValue */ public $id; - /** - * @OneToOne(targetEntity="DDC1515Foo", mappedBy="bar") - */ + /** @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 605f9412b60..e1d4aae447b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1526Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1526Test.php @@ -1,42 +1,46 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1526Menu::class), + $this->_em->getClassMetadata(DDC1526Menu::class), ] ); } - public function testIssue() + public function testIssue(): void { $parents = []; for ($i = 0; $i < 9; $i++) { - $entity = new DDC1526Menu; + $entity = new DDC1526Menu(); - if (isset ($parents[($i % 3)])) { - $entity->parent = $parents[($i%3)]; + if (isset($parents[$i % 3])) { + $entity->parent = $parents[$i % 3]; } $this->_em->persist($entity); $parents[$i] = $entity; } + $this->_em->flush(); $this->_em->clear(); - - $dql = "SELECT m, c - FROM " . __NAMESPACE__ . "\DDC1526Menu m - LEFT JOIN m.children c"; + $dql = 'SELECT m, c + FROM ' . __NAMESPACE__ . '\DDC1526Menu m + LEFT JOIN m.children c'; $menus = $this->_em->createQuery($dql)->getResult(); // All Children collection now have to be initialized @@ -57,13 +61,9 @@ class DDC1526Menu * @GeneratedValue */ public $id; - /** - * @ManyToOne(targetEntity="DDC1526Menu", inversedBy="children") - */ + /** @ManyToOne(targetEntity="DDC1526Menu", inversedBy="children") */ public $parent; - /** - * @OneToMany(targetEntity="DDC1526Menu", mappedBy="parent") - */ + /** @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 00df9327bc2..db625e1592e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1545Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1545Test.php @@ -1,14 +1,17 @@ useModelSet('cms'); parent::setUp(); } - private function initDb($link) + private function initDb($link): void { - $article = new CmsArticle(); + $article = new CmsArticle(); $article->topic = 'foo'; - $article->text = 'foo'; + $article->text = 'foo'; - $user = new CmsUser(); - $user->status = 'foo'; + $user = new CmsUser(); + $user->status = 'foo'; $user->username = 'foo'; - $user->name = 'foo'; + $user->name = 'foo'; - $user2 = new CmsUser(); - $user2->status = 'bar'; + $user2 = new CmsUser(); + $user2->status = 'bar'; $user2->username = 'bar'; - $user2->name = 'bar'; + $user2->name = 'bar'; if ($link) { $article->user = $user; @@ -49,11 +52,11 @@ private function initDb($link) $this->_em->clear(); $this->articleId = $article->id; - $this->userId = $user->id; - $this->user2Id = $user2->id; + $this->userId = $user->id; + $this->user2Id = $user2->id; } - public function testLinkObjects() + public function testLinkObjects(): void { $this->initDb(false); @@ -76,7 +79,7 @@ public function testLinkObjects() $this->assertEquals($user->id, $article->user->id); } - public function testLinkObjectsWithAssociationLoaded() + public function testLinkObjectsWithAssociationLoaded(): void { $this->initDb(false); @@ -102,7 +105,7 @@ public function testLinkObjectsWithAssociationLoaded() $this->assertEquals($user->id, $article->user->id); } - public function testUnlinkObjects() + public function testUnlinkObjects(): void { $this->initDb(true); @@ -122,7 +125,7 @@ public function testUnlinkObjects() $this->assertNull($article->user); } - public function testUnlinkObjectsWithAssociationLoaded() + public function testUnlinkObjectsWithAssociationLoaded(): void { $this->initDb(true); @@ -145,7 +148,7 @@ public function testUnlinkObjectsWithAssociationLoaded() $this->assertNull($article->user); } - public function testChangeLink() + public function testChangeLink(): void { $this->initDb(false); @@ -168,7 +171,7 @@ public function testChangeLink() $this->assertEquals($user2->id, $article->user->id); } - public function testChangeLinkWithAssociationLoaded() + public function testChangeLinkWithAssociationLoaded(): void { $this->initDb(false); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1548Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1548Test.php index 31fa6f19338..12c49439506 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1548Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1548Test.php @@ -1,31 +1,35 @@ _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), ] ); } - public function testIssue() + public function testIssue(): void { $rel = new DDC1548Rel(); $this->_em->persist($rel); $this->_em->flush(); - $e1 = new DDC1548E1(); + $e1 = new DDC1548E1(); $e1->rel = $rel; $this->_em->persist($e1); $this->_em->flush(); @@ -72,12 +76,8 @@ class DDC1548Rel */ public $id; - /** - * @OneToOne(targetEntity="DDC1548E1", mappedBy="rel") - */ + /** @OneToOne(targetEntity="DDC1548E1", mappedBy="rel") */ public $e1; - /** - * @OneToOne(targetEntity="DDC1548E2", mappedBy="rel") - */ + /** @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 index f6be23a6af6..0aad2abedcf 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1594Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1594Test.php @@ -1,36 +1,41 @@ useModelSet('cms'); parent::setUp(); } - public function testIssue() + public function testIssue(): void { - $user = new CmsUser(); - $user->status = 'foo'; + $user = new CmsUser(); + $user->status = 'foo'; $user->username = 'foo'; - $user->name = 'foo'; + $user->name = 'foo'; $this->_em->persist($user); $this->_em->flush(); $this->_em->clear(); - $detachedUser = clone $user; - $detachedUser->name = 'bar'; + $detachedUser = clone $user; + $detachedUser->name = 'bar'; $detachedUser->status = 'bar'; $newUser = $this->_em->getReference(get_class($user), $user->id); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1595Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1595Test.php index 57601c6d65a..0c71c7bf5f6 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1595Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1595Test.php @@ -1,30 +1,37 @@ _em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\DebugStack); + $this->_em->getConnection()->getConfiguration()->setSQLLogger(new DebugStack()); $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), ] ); } - public function testIssue() + public function testIssue(): void { $e1 = new DDC1595InheritedEntity1(); @@ -35,7 +42,7 @@ public function testIssue() $sqlLogger = $this->_em->getConnection()->getConfiguration()->getSQLLogger(); $repository = $this->_em->getRepository(DDC1595InheritedEntity1::class); - $entity1 = $repository->find($e1->id); + $entity1 = $repository->find($e1->id); // DDC-1596 $this->assertSQLEquals( @@ -56,7 +63,7 @@ public function testIssue() $entities = $entity1->getEntities()->count(); $this->assertSQLEquals( - "SELECT COUNT(*) FROM entity1_entity2 t WHERE t.parent = ?", + 'SELECT COUNT(*) FROM entity1_entity2 t WHERE t.parent = ?', $sqlLogger->queries[count($sqlLogger->queries)]['sql'] ); } @@ -65,7 +72,6 @@ public function testIssue() /** * @Entity * @Table(name="base") - * * @InheritanceType("SINGLE_TABLE") * @DiscriminatorColumn(name="type", type="string") * @DiscriminatorMap({ @@ -78,7 +84,6 @@ abstract class DDC1595BaseInheritance /** * @Id @GeneratedValue * @Column(type="integer") - * * @var int */ public $id; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC163Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC163Test.php index 9cb8e755302..5f6560dec34 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC163Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC163Test.php @@ -1,12 +1,15 @@ useModelSet('company'); parent::setUp(); @@ -15,18 +18,18 @@ protected function setUp() : void /** * @group DDC-163 */ - public function testQueryWithOrConditionUsingTwoRelationOnSameEntity() + public function testQueryWithOrConditionUsingTwoRelationOnSameEntity(): void { - $p1 = new CompanyPerson; + $p1 = new CompanyPerson(); $p1->setName('p1'); - $p2 = new CompanyPerson; + $p2 = new CompanyPerson(); $p2->setName('p2'); - $p3 = new CompanyPerson; + $p3 = new CompanyPerson(); $p3->setName('p3'); - $p4 = new CompanyPerson; + $p4 = new CompanyPerson(); $p4->setName('p4'); $p1->setSpouse($p3); @@ -52,8 +55,8 @@ public function testQueryWithOrConditionUsingTwoRelationOnSameEntity() WHERE person.name=:name AND (spouse_friend.name=:name2 OR friend_friend.name=:name2)'; $q = $this->_em->createQuery($dql); - $q->setParameter('name', "p1"); - $q->setParameter('name2', "p4"); + $q->setParameter('name', 'p1'); + $q->setParameter('name2', 'p4'); $result = $q->getScalarResult(); $this->assertEquals('p3', $result[0]['spouse_name']); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1643Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1643Test.php index 4d82d152d64..1ab396ef9af 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1643Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1643Test.php @@ -1,36 +1,43 @@ useModelSet('cms'); parent::setUp(); - $user1 = new CmsUser(); - $user1->username = "beberlei"; - $user1->name = "Benjamin"; - $user1->status = "active"; - $group1 = new CmsGroup(); - $group1->name = "test"; - $group2 = new CmsGroup(); - $group2->name = "test"; + $user1 = new CmsUser(); + $user1->username = 'beberlei'; + $user1->name = 'Benjamin'; + $user1->status = 'active'; + $group1 = new CmsGroup(); + $group1->name = 'test'; + $group2 = new CmsGroup(); + $group2->name = 'test'; $user1->addGroup($group1); $user1->addGroup($group2); - $user2 = new CmsUser(); - $user2->username = "romanb"; - $user2->name = "Roman"; - $user2->status = "active"; + $user2 = new CmsUser(); + $user2->username = 'romanb'; + $user2->name = 'Roman'; + $user2->status = 'active'; $this->_em->persist($user1); $this->_em->persist($user2); @@ -43,7 +50,7 @@ protected function setUp() : void $this->user2 = $this->_em->find(get_class($user1), $user2->id); } - public function testClonePersistentCollectionAndReuse() + public function testClonePersistentCollectionAndReuse(): void { $user1 = $this->user1; @@ -57,7 +64,7 @@ public function testClonePersistentCollectionAndReuse() $this->assertEquals(2, count($user1->groups)); } - public function testClonePersistentCollectionAndShare() + public function testClonePersistentCollectionAndShare(): void { $user1 = $this->user1; $user2 = $this->user2; @@ -74,13 +81,13 @@ public function testClonePersistentCollectionAndShare() $this->assertEquals(2, count($user2->groups)); } - public function testCloneThenDirtyPersistentCollection() + public function testCloneThenDirtyPersistentCollection(): void { $user1 = $this->user1; $user2 = $this->user2; - $group3 = new CmsGroup(); - $group3->name = "test"; + $group3 = new CmsGroup(); + $group3->name = 'test'; $user2->groups = clone $user1->groups; $user2->groups->add($group3); @@ -95,13 +102,13 @@ public function testCloneThenDirtyPersistentCollection() $this->assertEquals(2, count($user1->groups)); } - public function testNotCloneAndPassAroundFlush() + public function testNotCloneAndPassAroundFlush(): void { $user1 = $this->user1; $user2 = $this->user2; - $group3 = new CmsGroup(); - $group3->name = "test"; + $group3 = new CmsGroup(); + $group3->name = 'test'; $user2->groups = $user1->groups; $user2->groups->add($group3); @@ -118,4 +125,3 @@ public function testNotCloneAndPassAroundFlush() $this->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 c6c332bc65e..628137de2f4 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1654Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1654Test.php @@ -1,24 +1,30 @@ setUpEntitySchema( [ - DDC1654Post::class, - DDC1654Comment::class, + DDC1654Post::class, + DDC1654Comment::class, ] ); } - public function tearDown() : void + public function tearDown(): void { $conn = static::$_sharedConn; $conn->executeUpdate('DELETE FROM ddc1654post_ddc1654comment'); @@ -26,9 +32,9 @@ public function tearDown() : void $conn->executeUpdate('DELETE FROM DDC1654Post'); } - public function testManyToManyRemoveFromCollectionOrphanRemoval() + public function testManyToManyRemoveFromCollectionOrphanRemoval(): void { - $post = new DDC1654Post(); + $post = new DDC1654Post(); $post->comments[] = new DDC1654Comment(); $post->comments[] = new DDC1654Comment(); @@ -45,9 +51,9 @@ public function testManyToManyRemoveFromCollectionOrphanRemoval() $this->assertEquals(0, count($comments)); } - public function testManyToManyRemoveElementFromCollectionOrphanRemoval() + public function testManyToManyRemoveElementFromCollectionOrphanRemoval(): void { - $post = new DDC1654Post(); + $post = new DDC1654Post(); $post->comments[] = new DDC1654Comment(); $post->comments[] = new DDC1654Comment(); @@ -67,9 +73,9 @@ public function testManyToManyRemoveElementFromCollectionOrphanRemoval() /** * @group DDC-3382 */ - public function testManyToManyRemoveElementFromReAddToCollectionOrphanRemoval() + public function testManyToManyRemoveElementFromReAddToCollectionOrphanRemoval(): void { - $post = new DDC1654Post(); + $post = new DDC1654Post(); $post->comments[] = new DDC1654Comment(); $post->comments[] = new DDC1654Comment(); @@ -87,9 +93,9 @@ public function testManyToManyRemoveElementFromReAddToCollectionOrphanRemoval() $this->assertEquals(2, count($comments)); } - public function testManyToManyClearCollectionOrphanRemoval() + public function testManyToManyClearCollectionOrphanRemoval(): void { - $post = new DDC1654Post(); + $post = new DDC1654Post(); $post->comments[] = new DDC1654Comment(); $post->comments[] = new DDC1654Comment(); @@ -103,15 +109,14 @@ public function testManyToManyClearCollectionOrphanRemoval() $comments = $this->_em->getRepository(DDC1654Comment::class)->findAll(); $this->assertEquals(0, count($comments)); - } /** * @group DDC-3382 */ - public function testManyToManyClearCollectionReAddOrphanRemoval() + public function testManyToManyClearCollectionReAddOrphanRemoval(): void { - $post = new DDC1654Post(); + $post = new DDC1654Post(); $post->comments[] = new DDC1654Comment(); $post->comments[] = new DDC1654Comment(); @@ -135,9 +140,7 @@ public function testManyToManyClearCollectionReAddOrphanRemoval() */ class DDC1654Post { - /** - * @Id @Column(type="integer") @GeneratedValue - */ + /** @Id @Column(type="integer") @GeneratedValue */ public $id; /** @@ -152,8 +155,6 @@ class DDC1654Post */ class DDC1654Comment { - /** - * @Id @Column(type="integer") @GeneratedValue - */ + /** @Id @Column(type="integer") @GeneratedValue */ public $id; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1655Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1655Test.php index f5996be3ecd..33b43ed5529 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1655Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1655Test.php @@ -1,42 +1,49 @@ _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) { + } catch (Exception $e) { } } - public function testPostLoadOneToManyInheritance() + public function testPostLoadOneToManyInheritance(): void { $cm = $this->_em->getClassMetadata(DDC1655Foo::class); - $this->assertEquals(["postLoad" => ["postLoad"]], $cm->lifecycleCallbacks); + $this->assertEquals(['postLoad' => ['postLoad']], $cm->lifecycleCallbacks); $cm = $this->_em->getClassMetadata(DDC1655Bar::class); - $this->assertEquals(["postLoad" => ["postLoad", "postSubLoaded"]], $cm->lifecycleCallbacks); + $this->assertEquals(['postLoad' => ['postLoad', 'postSubLoaded']], $cm->lifecycleCallbacks); - $baz = new DDC1655Baz(); - $foo = new DDC1655Foo(); + $baz = new DDC1655Baz(); + $foo = new DDC1655Foo(); $foo->baz = $baz; - $bar = new DDC1655Bar(); + $bar = new DDC1655Bar(); $bar->baz = $baz; $this->_em->persist($foo); @@ -47,7 +54,7 @@ public function testPostLoadOneToManyInheritance() $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)); + $this->assertEquals(1, $foo->loaded, 'should have loaded callback counter incremented for ' . get_class($foo)); } } @@ -55,7 +62,7 @@ public function testPostLoadOneToManyInheritance() * Check that post load is not executed several times when the entity * is rehydrated again although its already known. */ - public function testPostLoadInheritanceChild() + public function testPostLoadInheritanceChild(): void { $bar = new DDC1655Bar(); @@ -71,7 +78,7 @@ public function testPostLoadInheritanceChild() $this->assertEquals(1, $bar->loaded); $this->assertEquals(1, $bar->subLoaded); - $dql = "SELECT b FROM " . __NAMESPACE__ . "\DDC1655Bar b WHERE b.id = ?1"; + $dql = 'SELECT b FROM ' . __NAMESPACE__ . '\DDC1655Bar b WHERE b.id = ?1'; $bar = $this->_em->createQuery($dql)->setParameter(1, $bar->id)->getSingleResult(); $this->assertEquals(1, $bar->loaded); @@ -100,15 +107,13 @@ class DDC1655Foo public $loaded = 0; - /** - * @ManyToOne(targetEntity="DDC1655Baz", inversedBy="foos") - */ + /** @ManyToOne(targetEntity="DDC1655Baz", inversedBy="foos") */ public $baz; /** * @PostLoad */ - public function postLoad() + public function postLoad(): void { $this->loaded++; } @@ -125,7 +130,7 @@ class DDC1655Bar extends DDC1655Foo /** * @PostLoad */ - public function postSubLoaded() + public function postSubLoaded(): void { $this->subLoaded++; } @@ -139,8 +144,6 @@ class DDC1655Baz /** @Id @GeneratedValue @Column(type="integer") */ public $id; - /** - * @OneToMany(targetEntity="DDC1655Foo", mappedBy="baz") - */ + /** @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 6e359ddd70b..111a9e03d3f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1666Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1666Test.php @@ -1,29 +1,32 @@ useModelSet('cms'); parent::setUp(); } - public function testGivenOrphanRemovalOneToOne_WhenReplacing_ThenNoUniqueConstraintError() + public function testGivenOrphanRemovalOneToOne_WhenReplacing_ThenNoUniqueConstraintError(): void { - $user = new CmsUser(); - $user->name = "Benjamin"; - $user->username = "beberlei"; - $user->status = "something"; + $user = new CmsUser(); + $user->name = 'Benjamin'; + $user->username = 'beberlei'; + $user->status = 'something'; $user->setEmail($email = new CmsEmail()); - $email->setEmail("kontakt@beberlei.de"); + $email->setEmail('kontakt@beberlei.de'); $this->_em->persist($user); $this->_em->flush(); @@ -31,7 +34,7 @@ public function testGivenOrphanRemovalOneToOne_WhenReplacing_ThenNoUniqueConstra $this->assertTrue($this->_em->contains($email)); $user->setEmail($newEmail = new CmsEmail()); - $newEmail->setEmail("benjamin.eberlei@googlemail.com"); + $newEmail->setEmail('benjamin.eberlei@googlemail.com'); $this->_em->flush(); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1685Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1685Test.php index c93f059169d..d235a3eef6e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1685Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1685Test.php @@ -1,62 +1,69 @@ useModelSet('ddc117'); parent::setUp(); $this->_em->createQuery('DELETE FROM Doctrine\Tests\Models\DDC117\DDC117ArticleDetails ad')->execute(); - $article = new DDC117Article("Foo"); + $article = new DDC117Article('Foo'); $this->_em->persist($article); $this->_em->flush(); - $articleDetails = new DDC117ArticleDetails($article, "Very long text"); + $articleDetails = new DDC117ArticleDetails($article, 'Very long text'); $this->_em->persist($articleDetails); $this->_em->flush(); - $dql = "SELECT ad FROM Doctrine\Tests\Models\DDC117\DDC117ArticleDetails ad"; + $dql = 'SELECT ad FROM Doctrine\Tests\Models\DDC117\DDC117ArticleDetails ad'; $query = $this->_em->createQuery($dql); $query->setMaxResults(1); $this->paginator = new Paginator($query); } - public function testPaginateCount() + public function testPaginateCount(): void { $this->assertEquals(1, count($this->paginator)); } - public function testPaginateIterate() + public function testPaginateIterate(): void { foreach ($this->paginator as $ad) { $this->assertInstanceOf(DDC117ArticleDetails::class, $ad); } } - public function testPaginateCountNoOutputWalkers() + public function testPaginateCountNoOutputWalkers(): void { $this->paginator->setUseOutputWalkers(false); $this->assertEquals(1, count($this->paginator)); } - public function testPaginateIterateNoOutputWalkers() + public function testPaginateIterateNoOutputWalkers(): void { $this->paginator->setUseOutputWalkers(false); - $this->expectException(\RuntimeException::class); + $this->expectException(RuntimeException::class); $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) { @@ -64,4 +71,3 @@ public function testPaginateIterateNoOutputWalkers() } } } - diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC168Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC168Test.php index 87647d397f6..0c39e68b824 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC168Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC168Test.php @@ -1,14 +1,19 @@ useModelSet('company'); parent::setUp(); @@ -20,7 +25,7 @@ protected function setUp() : void $this->_em->getMetadataFactory()->setMetadataFor(CompanyEmployee::class, $metadata); } - public function tearDown() : void + public function tearDown(): void { $this->_em->getMetadataFactory()->setMetadataFor(CompanyEmployee::class, $this->oldMetadata); parent::tearDown(); @@ -29,18 +34,18 @@ public function tearDown() : void /** * @group DDC-168 */ - public function testJoinedSubclassPersisterRequiresSpecificOrderOfMetadataReflFieldsArray() + public function testJoinedSubclassPersisterRequiresSpecificOrderOfMetadataReflFieldsArray(): void { //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $spouse = new CompanyEmployee; - $spouse->setName("Blub"); - $spouse->setDepartment("Accounting"); + $spouse = new CompanyEmployee(); + $spouse->setName('Blub'); + $spouse->setDepartment('Accounting'); $spouse->setSalary(500); - $employee = new CompanyEmployee; - $employee->setName("Foo"); - $employee->setDepartment("bar"); + $employee = new CompanyEmployee(); + $employee->setName('Foo'); + $employee->setDepartment('bar'); $employee->setSalary(1000); $employee->setSpouse($spouse); @@ -50,12 +55,12 @@ public function testJoinedSubclassPersisterRequiresSpecificOrderOfMetadataReflFi $this->_em->flush(); $this->_em->clear(); - $q = $this->_em->createQuery("SELECT e FROM Doctrine\Tests\Models\Company\CompanyEmployee e WHERE e.name = ?1"); - $q->setParameter(1, "Foo"); + $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('bar', $theEmployee->getDepartment()); + $this->assertEquals('Foo', $theEmployee->getName()); $this->assertEquals(1000, $theEmployee->getSalary()); $this->assertInstanceOf(CompanyEmployee::class, $theEmployee); $this->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 f86bcb2c02d..32b3a9c6b10 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1690Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1690Test.php @@ -1,32 +1,39 @@ _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) { + } catch (Exception $e) { // Swallow all exceptions. We do not test the schema tool here. } } - public function testChangeTracking() + public function testChangeTracking(): void { $parent = new DDC1690Parent(); - $child = new DDC1690Child(); + $child = new DDC1690Child(); $parent->setName('parent'); $child->setName('child'); @@ -46,11 +53,11 @@ public function testChangeTracking() $this->assertEquals(1, count($child->listeners)); $parentId = $parent->getId(); - $childId = $child->getId(); + $childId = $child->getId(); unset($parent, $child); $parent = $this->_em->find(DDC1690Parent::class, $parentId); - $child = $this->_em->find(DDC1690Child::class, $childId); + $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'); @@ -60,13 +67,13 @@ public function testChangeTracking() unset($parent, $child); $parent = $this->_em->find(DDC1690Parent::class, $parentId); - $child = $parent->getChild(); + $child = $parent->getChild(); $this->assertEquals(1, count($parent->listeners)); $this->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)); @@ -74,16 +81,19 @@ public function testChangeTracking() } } -class NotifyBaseEntity implements NotifyPropertyChanged { +class NotifyBaseEntity implements NotifyPropertyChanged +{ public $listeners = []; - public function addPropertyChangedListener(PropertyChangedListener $listener) { - if (!in_array($listener, $this->listeners)) { + public function addPropertyChangedListener(PropertyChangedListener $listener): void + { + if (! in_array($listener, $this->listeners)) { $this->listeners[] = $listener; } } - protected function onPropertyChanged($propName, $oldValue, $newValue) { + protected function onPropertyChanged($propName, $oldValue, $newValue): void + { if ($this->listeners) { foreach ($this->listeners as $listener) { $listener->propertyChanged($this, $propName, $oldValue, $newValue); @@ -93,7 +103,8 @@ protected function onPropertyChanged($propName, $oldValue, $newValue) { } /** @Entity @ChangeTrackingPolicy("NOTIFY") */ -class DDC1690Parent extends NotifyBaseEntity { +class DDC1690Parent extends NotifyBaseEntity +{ /** @Id @Column(type="integer") @GeneratedValue */ private $id; @@ -103,30 +114,36 @@ class DDC1690Parent extends NotifyBaseEntity { /** @OneToOne(targetEntity="DDC1690Child") */ private $child; - function getId() { + function getId() + { return $this->id; } - function getName() { + function getName() + { return $this->name; } - function setName($name) { + function setName($name): void + { $this->onPropertyChanged('name', $this->name, $name); $this->name = $name; } - function setChild($child) { + function setChild($child): void + { $this->child = $child; } - function getChild() { + function getChild() + { return $this->child; } } /** @Entity */ -class DDC1690Child extends NotifyBaseEntity { +class DDC1690Child extends NotifyBaseEntity +{ /** @Id @Column(type="integer") @GeneratedValue */ private $id; @@ -136,24 +153,29 @@ class DDC1690Child extends NotifyBaseEntity { /** @OneToOne(targetEntity="DDC1690Parent", mappedBy="child") */ private $parent; - function getId() { + function getId() + { return $this->id; } - function getName() { + function getName() + { return $this->name; } - function setName($name) { + function setName($name): void + { $this->onPropertyChanged('name', $this->name, $name); $this->name = $name; } - function setParent($parent) { + function setParent($parent): void + { $this->parent = $parent; } - function getParent() { + function getParent() + { return $this->parent; } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1695Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1695Test.php index 20cef650755..6f142313724 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1695Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1695Test.php @@ -1,18 +1,23 @@ _em->getConnection()->getDatabasePlatform()->getName() != "sqlite") { - $this->markTestSkipped("Only with sqlite"); + if ($this->_em->getConnection()->getDatabasePlatform()->getName() !== 'sqlite') { + $this->markTestSkipped('Only with sqlite'); } - $dql = "SELECT n.smallText, n.publishDate FROM " . __NAMESPACE__ . "\\DDC1695News n"; + + $dql = 'SELECT n.smallText, n.publishDate FROM ' . __NAMESPACE__ . '\\DDC1695News n'; $sql = $this->_em->createQuery($dql)->getSQL(); $this->assertEquals( @@ -30,7 +35,6 @@ class DDC1695News { /** * @var int - * * @Column(name="`IdNews`", type="integer", nullable=false) * @Id * @GeneratedValue @@ -39,119 +43,102 @@ class DDC1695News /** * @var int - * * @Column(name="`IdUser`", type="bigint", nullable=false) */ private $idUser; /** * @var int - * * @Column(name="`IdLanguage`", type="integer", nullable=false) */ private $idLanguage; /** * @var int - * * @Column(name="`IdCondition`", type="integer", nullable=true) */ private $idCondition; /** * @var int - * * @Column(name="`IdHealthProvider`", type="integer", nullable=true) */ private $idHealthProvider; /** * @var int - * * @Column(name="`IdSpeciality`", type="integer", nullable=true) */ private $idSpeciality; /** * @var int - * * @Column(name="`IdMedicineType`", type="integer", nullable=true) */ private $idMedicineType; /** * @var int - * * @Column(name="`IdTreatment`", type="integer", nullable=true) */ private $idTreatment; /** * @var string - * * @Column(name="`Title`", type="string", nullable=true) */ private $title; /** * @var string - * * @Column(name="`SmallText`", type="string", nullable=true) */ private $smallText; /** * @var string - * * @Column(name="`LongText`", type="string", nullable=true) */ private $longText; /** * @var DateTimeZone - * * @Column(name="`PublishDate`", type="datetimetz", nullable=true) */ private $publishDate; /** * @var array - * * @Column(name="`IdxNews`", type="json_array", nullable=true) */ private $idxNews; /** * @var bool - * * @Column(name="`Highlight`", type="boolean", nullable=false) */ private $highlight; /** * @var int - * * @Column(name="`Order`", type="integer", nullable=false) */ private $order; /** * @var bool - * * @Column(name="`Deleted`", type="boolean", nullable=false) */ private $deleted; /** * @var bool - * * @Column(name="`Active`", type="boolean", nullable=false) */ private $active; /** * @var bool - * * @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 9e2c9f94185..65e34fb1033 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1707Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1707Test.php @@ -1,32 +1,34 @@ _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) { - + } catch (Exception $ignored) { } } - public function testPostLoadOnChild() + public function testPostLoadOnChild(): void { $class = $this->_em->getClassMetadata(DDC1707Child::class); $entity = new DDC1707Child(); @@ -45,9 +47,7 @@ public function testPostLoadOnChild() */ abstract class DDC1707Base { - /** - * @Id @Column(type="integer") @GeneratedValue - */ + /** @Id @Column(type="integer") @GeneratedValue */ protected $id; public $postLoad = false; @@ -55,7 +55,7 @@ abstract class DDC1707Base /** * @PostLoad */ - public function onPostLoad() + public function onPostLoad(): void { $this->postLoad = true; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1719Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1719Test.php index 33e71e07865..423d14cd201 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1719Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1719Test.php @@ -1,35 +1,39 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1719SimpleEntity::class), + $this->_em->getClassMetadata(DDC1719SimpleEntity::class), ] ); } - protected function tearDown() : void + protected function tearDown(): void { parent::tearDown(); $this->_schemaTool->dropSchema( [ - $this->_em->getClassMetadata(DDC1719SimpleEntity::class), + $this->_em->getClassMetadata(DDC1719SimpleEntity::class), ] ); } - public function testCreateRetrieveUpdateDelete() + public function testCreateRetrieveUpdateDelete(): void { $e1 = new DDC1719SimpleEntity('Bar 1'); $e2 = new DDC1719SimpleEntity('Foo 1'); @@ -40,12 +44,12 @@ public function testCreateRetrieveUpdateDelete() $this->_em->flush(); $this->_em->clear(); - $e1Id = $e1->id; - $e2Id = $e2->id; + $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); @@ -81,14 +85,12 @@ public function testCreateRetrieveUpdateDelete() $this->_em->remove($e2); $this->_em->flush(); - $e1 = $this->_em->find(DDC1719SimpleEntity::class, $e1Id); $e2 = $this->_em->find(DDC1719SimpleEntity::class, $e2Id); $this->assertNull($e1); $this->assertNull($e2); } - } /** @@ -97,7 +99,6 @@ public function testCreateRetrieveUpdateDelete() */ class DDC1719SimpleEntity { - /** * @Id * @Column(type="integer", name="`simple-entity-id`") @@ -105,17 +106,11 @@ class DDC1719SimpleEntity */ public $id; - /** - * @Column(type="string", name="`simple-entity-value`") - */ + /** @Column(type="string", name="`simple-entity-value`") */ public $value; - /** - * @param string $value - */ - public function __construct($value) + public function __construct(string $value) { $this->value = $value; } - } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1734Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1734Test.php index 9df2ea1f21c..0a78b90b2c5 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1734Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1734Test.php @@ -1,26 +1,30 @@ useModelSet('cms'); parent::setUp(); } /** @after */ - public function ensureTestGeneratedDeprecationMessages() : void + public function ensureTestGeneratedDeprecationMessages(): void { $this->assertHasDeprecationMessages(); } @@ -30,7 +34,7 @@ public function ensureTestGeneratedDeprecationMessages() : void * * @group DDC-1734 */ - public function testMergeWorksOnNonSerializedProxies() + public function testMergeWorksOnNonSerializedProxies(): void { $group = new CmsGroup(); @@ -60,7 +64,7 @@ public function testMergeWorksOnNonSerializedProxies() * * @group DDC-1734 */ - public function testMergeWorksOnSerializedProxies() + public function testMergeWorksOnSerializedProxies(): void { $group = new CmsGroup(); @@ -82,12 +86,7 @@ public function testMergeWorksOnSerializedProxies() $this->assertEquals('Foo', $unserializedProxy->getName(), 'The entity is broken'); } - /** - * @param object $object - * - * @return \Doctrine\Common\Proxy\Proxy - */ - private function getProxy($object) + private function getProxy(object $object): \Doctrine\Common\Proxy\Proxy { $metadataFactory = $this->_em->getMetadataFactory(); $className = get_class($object); @@ -95,5 +94,4 @@ private function getProxy($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..96b7f2689fb 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1757Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1757Test.php @@ -1,15 +1,20 @@ _em->createQueryBuilder(); - /* @var $qb \Doctrine\ORM\QueryBuilder */ + assert($qb instanceof QueryBuilder); $qb->select('_a') ->from(DDC1757A::class, '_a') @@ -17,13 +22,15 @@ public function testFailingCase() ->join('_b.c', '_c') ->join('_c.d', '_d'); - $q = $qb->getQuery(); + $q = $qb->getQuery(); $dql = $q->getDQL(); // Show difference between expected and actual queries on error - self::assertEquals("SELECT _a FROM " . __NAMESPACE__ . "\DDC1757A _a, " . __NAMESPACE__ . "\DDC1757B _b INNER JOIN _b.c _c INNER JOIN _c.d _d", - $dql, - "Wrong DQL query"); + self::assertEquals( + 'SELECT _a FROM ' . __NAMESPACE__ . '\DDC1757A _a, ' . __NAMESPACE__ . '\DDC1757B _b INNER JOIN _b.c _c INNER JOIN _c.d _d', + $dql, + 'Wrong DQL query' + ); } } @@ -52,9 +59,7 @@ class DDC1757B */ private $id; - /** - * @OneToOne(targetEntity="DDC1757C") - */ + /** @OneToOne(targetEntity="DDC1757C") */ private $c; } @@ -70,9 +75,7 @@ class DDC1757C */ public $id; - /** - * @OneToOne(targetEntity="DDC1757D") - */ + /** @OneToOne(targetEntity="DDC1757D") */ private $d; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1778Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1778Test.php index f838fefd907..667b4b9411c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1778Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1778Test.php @@ -1,29 +1,32 @@ useModelSet('cms'); parent::setUp(); - $this->user = new CmsUser(); - $this->user->username = "beberlei"; - $this->user->name = "Benjamin"; - $this->user->status = "active"; + $this->user = new CmsUser(); + $this->user->username = 'beberlei'; + $this->user->name = 'Benjamin'; + $this->user->status = 'active'; - $this->phone = new CmsPhonenumber(); + $this->phone = new CmsPhonenumber(); $this->phone->phonenumber = '0123456789'; $this->user->addPhonenumber($this->phone); @@ -32,11 +35,11 @@ protected function setUp() : void $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->phone = $this->_em->find(CmsPhonenumber::class, $this->phone->phonenumber); } - public function testClear() + public function testClear(): void { $clonedNumbers = clone $this->user->getPhonenumbers(); $clonedNumbers->clear(); @@ -48,7 +51,7 @@ public function testClear() $this->assertCount(1, $this->user->getPhonenumbers()); } - public function testRemove() + public function testRemove(): void { $clonedNumbers = clone $this->user->getPhonenumbers(); $clonedNumbers->remove(0); @@ -60,7 +63,7 @@ public function testRemove() $this->assertCount(1, $this->user->getPhonenumbers()); } - public function testRemoveElement() + public function testRemoveElement(): void { $clonedNumbers = clone $this->user->getPhonenumbers(); $clonedNumbers->removeElement($this->phone); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1787Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1787Test.php index 027a13a383b..20e2d9f7d53 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1787Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1787Test.php @@ -1,27 +1,31 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1787Foo::class), - $this->_em->getClassMetadata(DDC1787Bar::class), + $this->_em->getClassMetadata(DDC1787Foo::class), + $this->_em->getClassMetadata(DDC1787Bar::class), ] ); } - public function testIssue() + public function testIssue(): void { - $bar = new DDC1787Bar; - $bar2 = new DDC1787Bar; + $bar = new DDC1787Bar(); + $bar2 = new DDC1787Bar(); $this->_em->persist($bar); $this->_em->persist($bar2); @@ -39,14 +43,10 @@ public function testIssue() */ class DDC1787Foo { - /** - * @Id @Column(type="integer") @GeneratedValue(strategy="AUTO") - */ + /** @Id @Column(type="integer") @GeneratedValue(strategy="AUTO") */ private $id; - /** - * @Version @Column(type="integer") - */ + /** @Version @Column(type="integer") */ private $version; public function getVersion() diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1843Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1843Test.php index c97ebb287a2..571c818902e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1843Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1843Test.php @@ -1,25 +1,27 @@ useModelSet('quote'); parent::setUp(); } - public function testCreateRetrieveUpdateDelete() + public function testCreateRetrieveUpdateDelete(): void { - $e1 = new Group('Parent Bar 1'); $e2 = new Group('Parent Foo 2'); @@ -36,16 +38,16 @@ public function testCreateRetrieveUpdateDelete() $this->_em->flush(); $this->_em->clear(); - $e1Id = $e1->id; - $e2Id = $e2->id; - $e3Id = $e3->id; - $e4Id = $e4->id; + $e1Id = $e1->id; + $e2Id = $e2->id; + $e3Id = $e3->id; + $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); @@ -57,7 +59,6 @@ public function testCreateRetrieveUpdateDelete() $this->assertEquals($e3Id, $e3->id); $this->assertEquals($e4Id, $e4->id); - $this->assertEquals('Parent Bar 1', $e1->name); $this->assertEquals('Parent Foo 2', $e2->name); $this->assertEquals('Bar 3', $e3->name); @@ -104,22 +105,20 @@ public function testCreateRetrieveUpdateDelete() $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); // 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->assertNull($e1); $this->assertNull($e2); $this->assertNull($e3); $this->assertNull($e4); } - } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1884Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1884Test.php index 958100ecacf..df063824025 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1884Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1884Test.php @@ -1,18 +1,21 @@ */ -class DDC1884Test extends \Doctrine\Tests\OrmFunctionalTestCase +class DDC1884Test extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { $this->useModelSet('taxi'); parent::setUp(); @@ -53,19 +56,19 @@ protected function setUp() : void private function createCars($class) { - $bimmer = new $class; + $bimmer = new $class(); $bimmer->setBrand('BMW'); $bimmer->setModel('7-Series'); - $crysler = new $class; + $crysler = new $class(); $crysler->setBrand('Crysler'); $crysler->setModel('300'); - $merc = new $class; + $merc = new $class(); $merc->setBrand('Mercedes'); $merc->setModel('C-Class'); - $volvo = new $class; + $volvo = new $class(); $volvo->setBrand('Volvo'); $volvo->setModel('XC90'); @@ -79,10 +82,10 @@ private function createCars($class) private function createDrivers($class) { - $john = new $class; + $john = new $class(); $john->setName('John Doe'); - $foo = new $class; + $foo = new $class(); $foo->setName('Foo Bar'); $this->_em->persist($foo); @@ -95,7 +98,7 @@ private function createDrivers($class) * 1) Ride contains only columns that are part of its composite primary key * 2) We use fetch joins here */ - public function testSelectFromInverseSideWithCompositePkAndSolelyIdentifierColumnsUsingFetchJoins() + public function testSelectFromInverseSideWithCompositePkAndSolelyIdentifierColumnsUsingFetchJoins(): void { $qb = $this->_em->createQueryBuilder(); @@ -117,7 +120,7 @@ public function testSelectFromInverseSideWithCompositePkAndSolelyIdentifierColum * 1) PaidRide contains an extra column that is not part of the composite primary key * 2) Again we will use fetch joins */ - public function testSelectFromInverseSideWithCompositePkUsingFetchJoins() + public function testSelectFromInverseSideWithCompositePkUsingFetchJoins(): void { $qb = $this->_em->createQueryBuilder(); @@ -137,7 +140,7 @@ public function testSelectFromInverseSideWithCompositePkUsingFetchJoins() /** * The other way around will fail too */ - public function testSelectFromOwningSideUsingFetchJoins() + public function testSelectFromOwningSideUsingFetchJoins(): void { $qb = $this->_em->createQueryBuilder(); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1885Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1885Test.php index 2c141151b29..54ae8f538f3 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1885Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1885Test.php @@ -1,31 +1,31 @@ useModelSet('quote'); parent::setUp(); $user = new User(); - $user->name = "FabioBatSilva"; - $user->email = "fabio.bat.silva@gmail.com"; + $user->name = 'FabioBatSilva'; + $user->email = 'fabio.bat.silva@gmail.com'; $user->groups[] = new Group('G 1'); $user->groups[] = new Group('G 2'); $this->user = $user; @@ -34,18 +34,17 @@ protected function setUp() : void $this->_em->persist($user); $this->_em->flush(); $this->_em->clear(); - } - public function testCreateRetrieveUpdateDelete() + public function testCreateRetrieveUpdateDelete(): void { - $user = $this->user; - $g1 = $user->getGroups()->get(0); - $g2 = $user->getGroups()->get(1); + $user = $this->user; + $g1 = $user->getGroups()->get(0); + $g2 = $user->getGroups()->get(1); - $u1Id = $user->id; - $g1Id = $g1->id; - $g2Id = $g2->id; + $u1Id = $user->id; + $g1Id = $g1->id; + $g2Id = $g2->id; // Retrieve $user = $this->_em->find(User::class, $u1Id); @@ -87,11 +86,11 @@ public function testCreateRetrieveUpdateDelete() $this->assertNull($this->_em->find(Group::class, $g2Id)); } - public function testRemoveItem() + public function testRemoveItem(): void { - $user = $this->user; - $u1Id = $user->id; - $user = $this->_em->find(User::class, $u1Id); + $user = $this->user; + $u1Id = $user->id; + $user = $this->_em->find(User::class, $u1Id); $this->assertInstanceOf(User::class, $user); $this->assertEquals('FabioBatSilva', $user->name); @@ -117,11 +116,11 @@ public function testRemoveItem() $this->assertCount(1, $user->getGroups()); } - public function testClearAll() + public function testClearAll(): void { - $user = $this->user; - $u1Id = $user->id; - $user = $this->_em->find(User::class, $u1Id); + $user = $this->user; + $u1Id = $user->id; + $user = $this->_em->find(User::class, $u1Id); $this->assertInstanceOf(User::class, $user); $this->assertEquals('FabioBatSilva', $user->name); @@ -147,11 +146,11 @@ public function testClearAll() $this->assertCount(0, $user->getGroups()); } - public function testCountExtraLazy() + public function testCountExtraLazy(): void { - $user = $this->user; - $u1Id = $user->id; - $user = $this->_em->find(User::class, $u1Id); + $user = $this->user; + $u1Id = $user->id; + $user = $this->_em->find(User::class, $u1Id); $this->assertInstanceOf(User::class, $user); $this->assertEquals('FabioBatSilva', $user->name); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1918Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1918Test.php index 92c12d60b97..9ce6f9af622 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1918Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1918Test.php @@ -1,39 +1,45 @@ useModelSet('cms'); parent::setUp(); } - public function testLastPageCorrect() + public function testLastPageCorrect(): void { $groups = []; for ($i = 0; $i < 3; $i++) { - $group = new CmsGroup(); - $group->name = "test"; + $group = new CmsGroup(); + $group->name = 'test'; $this->_em->persist($group); $groups[] = $group; } for ($i = 0; $i < 10; $i++) { - $user = new CmsUser(); + $user = new CmsUser(); $user->username = "user$i"; - $user->name = "user$i"; - $user->status = "active"; - $user->groups = $groups; + $user->name = "user$i"; + $user->status = 'active'; + $user->groups = $groups; $this->_em->persist($user); } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1925Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1925Test.php index ef7d6014bf6..461560b2419 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1925Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1925Test.php @@ -1,16 +1,21 @@ _schemaTool->createSchema( [ @@ -20,10 +25,10 @@ public function testIssue() ); $user = new DDC1925User(); - $user->setTitle("Test User"); + $user->setTitle('Test User'); $product = new DDC1925Product(); - $product->setTitle("Test product"); + $product->setTitle('Test product'); $this->_em->persist($user); $this->_em->persist($product); @@ -38,8 +43,8 @@ public function testIssue() $this->_em->flush(); $this->_em->clear(); - /** @var DDC1925Product $persistedProduct */ $persistedProduct = $this->_em->find(DDC1925Product::class, $product->getId()); + assert($persistedProduct instanceof DDC1925Product); self::assertEquals($user, $persistedProduct->getBuyers()->first()); } @@ -53,7 +58,6 @@ class DDC1925Product { /** * @var int $id - * * @Column(name="id", type="integer") * @Id * @GeneratedValue(strategy="AUTO") @@ -62,7 +66,6 @@ class DDC1925Product /** * @var string $title - * * @Column(name="title", type="string", length=255) */ private $title; @@ -85,44 +88,30 @@ public function __construct() $this->buyers = new ArrayCollection(); } - /** - * @return int - */ - public function getId() + public function getId(): int { return $this->id; } - /** - * @param string $title - */ - public function setTitle($title) + public function setTitle(string $title): void { $this->title = $title; } /** * Get title - * - * @return string */ - public function getTitle() + public function getTitle(): string { return $this->title; } - /** - * @return ArrayCollection - */ - public function getBuyers() + public function getBuyers(): ArrayCollection { return $this->buyers; } - /** - * @param DDC1925User $buyer - */ - public function addBuyer(DDC1925User $buyer) + public function addBuyer(DDC1925User $buyer): void { $this->buyers[] = $buyer; } @@ -136,7 +125,6 @@ class DDC1925User { /** * @var int - * * @Column(name="id", type="integer") * @Id * @GeneratedValue(strategy="AUTO") @@ -145,37 +133,30 @@ class DDC1925User /** * @var string - * * @Column(name="title", type="string", length=255) */ private $title; /** * Get id - * - * @return int */ - public function getId() + public function getId(): int { return $this->id; } /** * Set title - * - * @param string $title */ - public function setTitle($title) + public function setTitle(string $title): void { $this->title = $title; } /** * Get title - * - * @return string */ - public function getTitle() + public function getTitle(): string { return $this->title; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC192Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC192Test.php index 532e0edfeb4..d05f8d3a552 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC192Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC192Test.php @@ -1,16 +1,20 @@ _em->getClassMetadata(DDC192User::class), @@ -23,8 +27,8 @@ public function testSchemaCreation() ->getSchemaManager() ->listTableNames(); - /** @var ClassMetadata $class */ foreach ($classes as $class) { + assert($class instanceof ClassMetadata); self::assertContains($class->getTableName(), $tables); } } @@ -43,9 +47,7 @@ class DDC192User */ public $id; - /** - * @Column(name="name", type="string") - */ + /** @Column(name="name", type="string") */ public $name; } @@ -69,8 +71,7 @@ class DDC192Phonenumber */ protected $User; - - public function setPhone($value) + public function setPhone($value): void { $this->phone = $value; } @@ -80,7 +81,7 @@ public function getPhone() return $this->phone; } - public function setUser(User $user) + public function setUser(User $user): void { $this->User = $user; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1995Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1995Test.php index e4643969a14..84a5ff94c67 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1995Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1995Test.php @@ -1,27 +1,30 @@ useModelSet('company'); parent::setUp(); } - public function testIssue() + public function testIssue(): void { - $person = new CompanyPerson; + $person = new CompanyPerson(); $person->setName('p1'); - $employee = new CompanyEmployee; + $employee = new CompanyEmployee(); $employee->setName('Foo'); $employee->setDepartment('bar'); $employee->setSalary(1000); @@ -31,8 +34,8 @@ public function testIssue() $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); + $dql = 'SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF ?1'; + $class = $this->_em->getClassMetadata(CompanyEmployee::class); $result = $this->_em->createQuery($dql) ->setParameter(1, $class) @@ -42,12 +45,12 @@ public function testIssue() $this->assertInstanceOf(CompanyEmployee::class, $result[0]); } - public function testQueryCache() + public function testQueryCache(): void { - $person = new CompanyPerson; + $person = new CompanyPerson(); $person->setName('p1'); - $employee = new CompanyEmployee; + $employee = new CompanyEmployee(); $employee->setName('Foo'); $employee->setDepartment('bar'); $employee->setSalary(1000); @@ -57,9 +60,9 @@ public function testQueryCache() $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); + $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); $result1 = $this->_em->createQuery($dql) ->setParameter('type', $class1) diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1998Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1998Test.php index 74ea2fd8889..5de93d0f189 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1998Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1998Test.php @@ -1,28 +1,33 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1998Entity::class), + $this->_em->getClassMetadata(DDC1998Entity::class), ] ); - $entity = new DDC1998Entity(); - $entity->id = new DDC1998Id("foo"); + $entity = new DDC1998Entity(); + $entity->id = new DDC1998Id('foo'); $this->_em->persist($entity); $this->_em->flush(); @@ -35,11 +40,10 @@ public function testSqlConversionAsIdentifier() $this->_em->flush(); $this->_em->clear(); - $found = $this->_em->find(DDC1998Entity::class, $entity->id); $this->assertNull($found); - $found = $this->_em->find(DDC1998Entity::class, "foo"); + $found = $this->_em->find(DDC1998Entity::class, 'foo'); $this->assertNull($found); $this->assertEquals(0, count($this->_em->getRepository(DDC1998Entity::class)->findAll())); @@ -51,27 +55,23 @@ public function testSqlConversionAsIdentifier() */ class DDC1998Entity { - /** - * @Id @Column(type="ddc1998") - */ + /** @Id @Column(type="ddc1998") */ public $id; - /** - * @Column(type="integer") - */ + /** @Column(type="integer") */ public $num = 0; } class DDC1998Type extends StringType { - const NAME = 'ddc1998'; + public const NAME = 'ddc1998'; /** * {@inheritdoc} */ public function convertToDatabaseValue($value, AbstractPlatform $platform) { - return (string)$value; + return (string) $value; } public function convertToPhpValue($value, AbstractPlatform $platform) diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC199Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC199Test.php index c40e09a1d48..17350ed2cbf 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC199Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC199Test.php @@ -1,44 +1,48 @@ _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), ] ); } - public function testPolymorphicLoading() + public function testPolymorphicLoading(): void { - $child = new DDC199ChildClass; + $child = new DDC199ChildClass(); $child->parentData = 'parentData'; - $child->childData = 'childData'; + $child->childData = 'childData'; $this->_em->persist($child); - $related1 = new DDC199RelatedClass; + $related1 = new DDC199RelatedClass(); $related1->relatedData = 'related1'; - $related1->parent = $child; + $related1->parent = $child; $this->_em->persist($related1); - $related2 = new DDC199RelatedClass; + $related2 = new DDC199RelatedClass(); $related2->relatedData = 'related2'; - $related2->parent = $child; + $related2->parent = $child; $this->_em->persist($related2); $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)); @@ -65,14 +69,10 @@ class DDC199ParentClass */ public $id; - /** - * @Column(type="string") - */ + /** @Column(type="string") */ public $parentData; - /** - * @OneToMany(targetEntity="DDC199RelatedClass", mappedBy="parent") - */ + /** @OneToMany(targetEntity="DDC199RelatedClass", mappedBy="parent") */ public $relatedEntities; } @@ -80,9 +80,7 @@ class DDC199ParentClass /** @Entity */ class DDC199ChildClass extends DDC199ParentClass { - /** - * @Column - */ + /** @Column */ public $childData; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2012Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2012Test.php index 13adca23e34..ce04e4db550 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2012Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2012Test.php @@ -1,17 +1,26 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2012Item::class), - $this->_em->getClassMetadata(DDC2012ItemPerson::class), + $this->_em->getClassMetadata(DDC2012Item::class), + $this->_em->getClassMetadata(DDC2012ItemPerson::class), ] ); } - public function testIssue() + public function testIssue(): void { - $item = new DDC2012ItemPerson(); - $item->tsv = ['word1', 'word2', 'word3']; + $item = new DDC2012ItemPerson(); + $item->tsv = ['word1', 'word2', 'word3']; $this->_em->persist($item); $this->_em->flush(); @@ -49,7 +58,6 @@ public function testIssue() $this->assertInstanceOf(DDC2012Item::class, $item); $this->assertEquals(['word1', 'word2', 'word3'], $item->tsv); - $item->tsv = ['word1', 'word2']; $this->_em->persist($item); @@ -86,9 +94,7 @@ class DDC2012Item */ public $id; - /** - * @Column(name="tsv", type="tsvector", nullable=true) - */ + /** @Column(name="tsv", type="tsvector", nullable=true) */ public $tsv; } @@ -98,12 +104,11 @@ class DDC2012Item */ class DDC2012ItemPerson extends DDC2012Item { - } class DDC2012TsVectorType extends Type { - const MYTYPE = 'tsvector'; + public const MYTYPE = 'tsvector'; public static $calls = []; @@ -121,7 +126,7 @@ public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $pla public function convertToDatabaseValue($value, AbstractPlatform $platform) { if (is_array($value)) { - $value = implode(" ", $value); + $value = implode(' ', $value); } self::$calls[__FUNCTION__][] = [ @@ -142,7 +147,7 @@ public function convertToPHPValue($value, AbstractPlatform $platform) 'platform' => $platform, ]; - return explode(" ", strtolower($value)); + return explode(' ', strtolower($value)); } /** diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2074Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2074Test.php index d5fc39b957b..19c45c3a963 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2074Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2074Test.php @@ -9,6 +9,7 @@ use Doctrine\Tests\Models\ECommerce\ECommerceCategory; use Doctrine\Tests\Models\ECommerce\ECommerceProduct; use Doctrine\Tests\OrmFunctionalTestCase; + use function count; /** @@ -16,13 +17,13 @@ */ class DDC2074Test extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { $this->useModelSet('ecommerce'); parent::setUp(); } - public function testShouldNotScheduleDeletionOnClonedInstances() + public function testShouldNotScheduleDeletionOnClonedInstances(): void { $class = $this->_em->getClassMetadata(ECommerceProduct::class); $product = new ECommerceProduct(); @@ -37,7 +38,7 @@ public function testShouldNotScheduleDeletionOnClonedInstances() $this->assertEquals(0, count($uow->getScheduledCollectionDeletions())); } - public function testSavingClonedPersistentCollection() + public function testSavingClonedPersistentCollection(): void { $product = new ECommerceProduct(); $category = new ECommerceCategory(); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2084Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2084Test.php index 8b342743842..cd9fbc4c3bc 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2084Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2084Test.php @@ -1,24 +1,29 @@ _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) { + } catch (Exception $exc) { } } @@ -38,7 +43,7 @@ public function loadFixture() return $e1; } - public function testIssue() + public function testIssue(): void { $e1 = $this->loadFixture(); $e2 = $e1->getMyEntity2(); @@ -49,7 +54,7 @@ public function testIssue() $this->assertEquals('Foo', $e->getMyEntity2()->getValue()); } - public function testinvalidIdentifierBindingEntityException() + public function testinvalidIdentifierBindingEntityException(): void { $this->expectException('Doctrine\ORM\ORMInvalidArgumentException'); $this->expectExceptionMessage('Binding entities to query parameters only allowed for entities that have an identifier.'); @@ -77,7 +82,7 @@ public function __construct(MyEntity2 $myEntity2) $this->entity2 = $myEntity2; } - public function setMyEntity2(MyEntity2 $myEntity2) + public function setMyEntity2(MyEntity2 $myEntity2): void { $this->entity2 = $myEntity2; } @@ -101,9 +106,7 @@ class MyEntity2 */ private $id; - /** - * @Column - */ + /** @Column */ private $value; public function __construct($value) @@ -121,7 +124,7 @@ public function getValue() return $this->value; } - public function setValue($value) + public function setValue($value): void { $this->value = $value; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2090Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2090Test.php index 1051751aa35..124f66965a8 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2090Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2090Test.php @@ -1,36 +1,40 @@ useModelSet('company'); parent::setUp(); } - public function testIssue() + public function testIssue(): void { - $date1 = new \DateTime('2011-11-11 11:11:11'); - $date2 = new \DateTime('2012-12-12 12:12:12'); - $employee1 = new CompanyEmployee; - $employee2 = new CompanyEmployee; - - $employee1->setName("Fabio B. Silva"); - $employee1->setStartDate(new \DateTime('yesterday')); - $employee1->setDepartment("R&D"); + $date1 = new DateTime('2011-11-11 11:11:11'); + $date2 = new DateTime('2012-12-12 12:12:12'); + $employee1 = new CompanyEmployee(); + $employee2 = new CompanyEmployee(); + + $employee1->setName('Fabio B. Silva'); + $employee1->setStartDate(new DateTime('yesterday')); + $employee1->setDepartment('R&D'); $employee1->setSalary(100); - $employee2->setName("Doctrine Bot"); - $employee1->setStartDate(new \DateTime('yesterday')); - $employee2->setDepartment("QA"); + $employee2->setName('Doctrine Bot'); + $employee1->setStartDate(new DateTime('yesterday')); + $employee2->setDepartment('QA'); $employee2->setSalary(100); $this->_em->persist($employee1); @@ -45,9 +49,9 @@ public function testIssue() ->where('e = :e') ->setParameters( [ - 'e' => $employee1, - 'date' => $date1, - 'salary' => 101, + 'e' => $employee1, + 'date' => $date1, + 'salary' => 101, ] ) ->getQuery() @@ -61,9 +65,9 @@ public function testIssue() ->where('e = :e') ->setParameters( [ - 'e' => $employee2, - 'date' => $date2, - 'salary' => 102, + 'e' => $employee2, + 'date' => $date2, + 'salary' => 102, ] ) ->getQuery() @@ -100,7 +104,6 @@ public function testIssue() ->useQueryCache(true) ->execute(); - $this->_em->clear(); $e1 = $this->_em->find(CompanyEmployee::class, $employee1->getId()); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2106Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2106Test.php index 53ce73e9ed2..ada0c630fd6 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2106Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2106Test.php @@ -1,15 +1,19 @@ children $entity = new DDC2106Entity(); @@ -54,14 +58,11 @@ class DDC2106Entity /** @ManyToOne(targetEntity="DDC2106Entity", inversedBy="children") */ public $parent; - /** - * @OneToMany(targetEntity="DDC2106Entity", mappedBy="parent", cascade={"persist"}) - */ + /** @OneToMany(targetEntity="DDC2106Entity", mappedBy="parent", cascade={"persist"}) */ public $children; public function __construct() { - $this->children = new \Doctrine\Common\Collections\ArrayCollection; + $this->children = new ArrayCollection(); } } - diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC211Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC211Test.php index f217afbb064..766d4360016 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC211Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC211Test.php @@ -1,27 +1,30 @@ _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() + public function testIssue(): void { //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $user = new DDC211User; + $user = new DDC211User(); $user->setName('John Doe'); $this->_em->persist($user); @@ -29,13 +32,12 @@ public function testIssue() $groupNames = ['group 1', 'group 2', 'group 3', 'group 4']; foreach ($groupNames as $name) { - - $group = new DDC211Group; + $group = new DDC211Group(); $group->setName($name); $this->_em->persist($group); $this->_em->flush(); - if (!$user->getGroups()->contains($group)) { + if (! $user->getGroups()->contains($group)) { $user->getGroups()->add($group); $group->getUsers()->add($user); $this->_em->flush(); @@ -43,7 +45,6 @@ public function testIssue() } $this->assertEquals(4, $user->getGroups()->count()); - } } @@ -51,7 +52,7 @@ public function testIssue() /** * @Entity * @Table(name="ddc211_users") -*/ + */ class DDC211User { /** @@ -61,27 +62,32 @@ class DDC211User */ protected $id; - /** - * @Column(name="name", type="string") - */ + /** @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")} - * ) - */ + * @ManyToMany(targetEntity="DDC211Group", inversedBy="users") + * @JoinTable(name="user_groups", + * joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")}, + * inverseJoinColumns={@JoinColumn(name="group_id", referencedColumnName="id")} + * ) + */ protected $groups; - public function __construct() { - $this->groups = new \Doctrine\Common\Collections\ArrayCollection(); + public function __construct() + { + $this->groups = new ArrayCollection(); } - public function setName($name) { $this->name = $name; } + public function setName($name): void + { + $this->name = $name; + } - public function getGroups() { return $this->groups; } + public function getGroups() + { + return $this->groups; + } } /** @@ -97,22 +103,24 @@ class DDC211Group */ protected $id; - /** - * @Column(name="name", type="string") - */ + /** @Column(name="name", type="string") */ protected $name; - /** - * @ManyToMany(targetEntity="DDC211User", mappedBy="groups") - */ + /** @ManyToMany(targetEntity="DDC211User", mappedBy="groups") */ protected $users; - public function __construct() { - $this->users = new \Doctrine\Common\Collections\ArrayCollection(); + public function __construct() + { + $this->users = new ArrayCollection(); } - public function setName($name) { $this->name = $name; } + public function setName($name): void + { + $this->name = $name; + } - public function getUsers() { return $this->users; } + public function getUsers() + { + return $this->users; + } } - diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2138Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2138Test.php index 5bf2ddbcaa5..ca166b33131 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2138Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2138Test.php @@ -1,19 +1,26 @@ _em; + $em = $this->_em; $schemaTool = new SchemaTool($em); $classes = [ @@ -21,21 +28,21 @@ public function testForeignKeyOnSTIWithMultipleMapping() $em->getClassMetadata(DDC2138Structure::class), $em->getClassMetadata(DDC2138UserFollowedObject::class), $em->getClassMetadata(DDC2138UserFollowedStructure::class), - $em->getClassMetadata(DDC2138UserFollowedUser::class) + $em->getClassMetadata(DDC2138UserFollowedUser::class), ]; $schema = $schemaTool->getSchemaFromMetadata($classes); - $this->assertTrue($schema->hasTable('users_followed_objects'), "Table users_followed_objects should exist."); + $this->assertTrue($schema->hasTable('users_followed_objects'), 'Table users_followed_objects should exist.'); - /* @var $table \Doctrine\DBAL\Schema\Table */ - $table = ($schema->getTable('users_followed_objects')); + $table = $schema->getTable('users_followed_objects'); + assert($table instanceof Table); $this->assertTrue($table->columnsAreIndexed(['object_id'])); $this->assertTrue($table->columnsAreIndexed(['user_id'])); $foreignKeys = $table->getForeignKeys(); $this->assertCount(1, $foreignKeys, 'user_id column has to have FK, but not object_id'); - /* @var $fk \Doctrine\DBAL\Schema\ForeignKeyConstraint */ $fk = reset($foreignKeys); + assert($fk instanceof ForeignKeyConstraint); $this->assertEquals('users', $fk->getForeignTableName()); $localColumns = $fk->getLocalColumns(); @@ -59,9 +66,7 @@ class DDC2138Structure */ protected $id; - /** - * @Column(type="string", length=32, nullable=true) - */ + /** @Column(type="string", length=32, nullable=true) */ protected $name; } @@ -76,7 +81,6 @@ abstract class DDC2138UserFollowedObject { /** * @var int $id - * * @Column(name="id", type="integer") * @Id * @GeneratedValue(strategy="AUTO") @@ -85,10 +89,8 @@ abstract class DDC2138UserFollowedObject /** * Get id - * - * @return int */ - public function getId() + public function getId(): int { return $this->id; } @@ -115,31 +117,22 @@ class DDC2138UserFollowedStructure extends DDC2138UserFollowedObject /** * Construct a UserFollowedStructure entity - * - * @param User $user - * @param Structure $followedStructure */ public function __construct(User $user, Structure $followedStructure) { - $this->user = $user; + $this->user = $user; $this->followedStructure = $followedStructure; } - /** - * - * @return User - */ - public function getUser() + public function getUser(): User { return $this->user; } /** * Gets followed structure - * - * @return Structure */ - public function getFollowedStructure() + public function getFollowedStructure(): Structure { return $this->followedStructure; } @@ -167,34 +160,26 @@ class DDC2138UserFollowedUser extends DDC2138UserFollowedObject /** * Construct a UserFollowedUser entity * - * @param User $user - * @param User $followedUser * @param bool $giveAgency */ public function __construct(User $user, User $followedUser) { - $this->user = $user; + $this->user = $user; $this->followedUser = $followedUser; } - /** - * @return User - */ - public function getUser() + public function getUser(): User { return $this->user; } /** * Gets followed user - * - * @return User */ - public function getFollowedUser() + public function getFollowedUser(): User { return $this->followedUser; } - } /** @@ -210,9 +195,7 @@ class DDC2138User */ protected $id; - /** - * @Column(type="string", length=32, nullable=true) - */ + /** @Column(type="string", length=32, nullable=true) */ protected $name; /** @@ -229,7 +212,7 @@ class DDC2138User public function __construct() { - $this->followedUsers = new ArrayCollection(); + $this->followedUsers = new ArrayCollection(); $this->followedStructures = new ArrayCollection(); } @@ -238,18 +221,15 @@ public function __construct() * * @param UserFollowedUser $followers */ - private function removeFollower(UserFollowedUser $followers) + private function removeFollower(UserFollowedUser $followers): void { $this->followers->removeElement($followers); } /** * Add followedUsers - * - * @param UserFollowedUser $followedUsers - * @return User */ - public function addFollowedUser(UserFollowedUser $followedUsers) + public function addFollowedUser(UserFollowedUser $followedUsers): User { $this->followedUsers[] = $followedUsers; @@ -258,11 +238,8 @@ public function addFollowedUser(UserFollowedUser $followedUsers) /** * Remove followedUsers - * - * @param UserFollowedUser $followedUsers - * @return User */ - public function removeFollowedUser(UserFollowedUser $followedUsers) + public function removeFollowedUser(UserFollowedUser $followedUsers): User { $this->followedUsers->removeElement($followedUsers); @@ -271,21 +248,16 @@ public function removeFollowedUser(UserFollowedUser $followedUsers) /** * Get followedUsers - * - * @return Doctrine\Common\Collections\Collection */ - public function getFollowedUsers() + public function getFollowedUsers(): Doctrine\Common\Collections\Collection { return $this->followedUsers; } /** * Add followedStructures - * - * @param UserFollowedStructure $followedStructures - * @return User */ - public function addFollowedStructure(UserFollowedStructure $followedStructures) + public function addFollowedStructure(UserFollowedStructure $followedStructures): User { $this->followedStructures[] = $followedStructures; @@ -294,11 +266,8 @@ public function addFollowedStructure(UserFollowedStructure $followedStructures) /** * Remove followedStructures - * - * @param UserFollowedStructure $followedStructures - * @return User */ - public function removeFollowedStructure(UserFollowedStructure $followedStructures) + public function removeFollowedStructure(UserFollowedStructure $followedStructures): User { $this->followedStructures->removeElement($followedStructures); @@ -307,10 +276,8 @@ public function removeFollowedStructure(UserFollowedStructure $followedStructure /** * Get followedStructures - * - * @return Doctrine\Common\Collections\Collection */ - public function getFollowedStructures() + public function getFollowedStructures(): Doctrine\Common\Collections\Collection { return $this->followedStructures; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2175Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2175Test.php index 532033c1fe8..1cc73d5d7ee 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2175Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2175Test.php @@ -1,38 +1,42 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2175Entity::class), + $this->_em->getClassMetadata(DDC2175Entity::class), ] ); } - public function testIssue() + public function testIssue(): void { - $entity = new DDC2175Entity(); - $entity->field = "foo"; + $entity = new DDC2175Entity(); + $entity->field = 'foo'; $this->_em->persist($entity); $this->_em->flush(); $this->assertEquals(1, $entity->version); - $entity->field = "bar"; + $entity->field = 'bar'; $this->_em->flush(); $this->assertEquals(2, $entity->version); - $entity->field = "baz"; + $entity->field = 'baz'; $this->_em->flush(); $this->assertEquals(3, $entity->version); @@ -46,14 +50,10 @@ public function testIssue() */ class DDC2175Entity { - /** - * @Id @GeneratedValue @Column(type="integer") - */ + /** @Id @GeneratedValue @Column(type="integer") */ public $id; - /** - * @Column(type="string") - */ + /** @Column(type="string") */ public $field; /** diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2182Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2182Test.php index e610a67bcb2..589ff74c498 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2182Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2182Test.php @@ -1,32 +1,36 @@ _em->getConnection()->getDatabasePlatform()->getName() != 'mysql') { - $this->markTestSkipped("This test is useful for all databases, but designed only for 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), ] ); $collation = $this->getColumnCollationDeclarationSQL('utf8_unicode_ci'); $this->assertEquals('CREATE TABLE DDC2182OptionParent (id INT UNSIGNED NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 ' . $collation . ' 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 ' . $collation . ' ENGINE = InnoDB', $sql[1]); - $this->assertEquals("ALTER TABLE DDC2182OptionChild ADD CONSTRAINT FK_B314D4AD727ACA70 FOREIGN KEY (parent_id) REFERENCES DDC2182OptionParent (id)", $sql[2]); + $this->assertEquals('ALTER TABLE DDC2182OptionChild ADD CONSTRAINT FK_B314D4AD727ACA70 FOREIGN KEY (parent_id) REFERENCES DDC2182OptionParent (id)', $sql[2]); } - private function getColumnCollationDeclarationSQL(string $collation) : string + private function getColumnCollationDeclarationSQL(string $collation): string { if (method_exists($this->_em->getConnection()->getDatabasePlatform(), 'getColumnCollationDeclarationSQL')) { return $this->_em->getConnection()->getDatabasePlatform()->getColumnCollationDeclarationSQL($collation); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2214Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2214Test.php index d180fa2b30b..3200e7369b6 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2214Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2214Test.php @@ -1,31 +1,37 @@ - * * @group DDC-2214 */ -class DDC2214Test extends \Doctrine\Tests\OrmFunctionalTestCase +class DDC2214Test extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { parent::setUp(); $this->_schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2214Foo::class), - $this->_em->getClassMetadata(DDC2214Bar::class), + $this->_em->getClassMetadata(DDC2214Foo::class), + $this->_em->getClassMetadata(DDC2214Bar::class), ] ); } - public function testIssue() + public function testIssue(): void { $foo = new DDC2214Foo(); $bar = new DDC2214Bar(); @@ -37,21 +43,21 @@ public function testIssue() $this->_em->flush(); $this->_em->clear(); - /* @var $foo \Doctrine\Tests\ORM\Functional\Ticket\DDC2214Foo */ $foo = $this->_em->find(DDC2214Foo::class, $foo->id); + assert($foo instanceof DDC2214Foo); $bar = $foo->bar; - $logger = $this->_em->getConnection()->getConfiguration()->getSQLLogger(); + $logger = $this->_em->getConnection()->getConfiguration()->getSQLLogger(); $related = $this ->_em - ->createQuery('SELECT b FROM '.__NAMESPACE__ . '\DDC2214Bar b WHERE b.id IN(:ids)') + ->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]); + $this->assertEquals(Connection::PARAM_INT_ARRAY, $query['types'][0]); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2224Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2224Test.php index f6bc715eeb6..fccd69443d3 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2224Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2224Test.php @@ -1,25 +1,30 @@ _em->createQuery($dql); $query->setQueryCacheDriver(new ArrayCache()); @@ -32,7 +37,7 @@ public function testIssue() /** * @depends testIssue */ - public function testCacheMissWhenTypeChanges(Query $query) + public function testCacheMissWhenTypeChanges(Query $query): void { $query->setParameter('field', 'test', 'string'); $this->assertStringEndsWith('.field = ?', $query->getSQL()); @@ -76,13 +81,9 @@ public function convertToDatabaseValueSQL($sqlExpr, AbstractPlatform $platform) */ class DDC2224Entity { - /** - * @Id @GeneratedValue @Column(type="integer") - */ + /** @Id @GeneratedValue @Column(type="integer") */ public $id; - /** - * @Column(type="DDC2224Type") - */ + /** @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 6a9488050fa..c041bf93d17 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2230Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2230Test.php @@ -1,5 +1,7 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2230User::class), - $this->_em->getClassMetadata(DDC2230Address::class), + $this->_em->getClassMetadata(DDC2230User::class), + $this->_em->getClassMetadata(DDC2230Address::class), ] ); - } catch (ToolsException $e) {} + } catch (ToolsException $e) { + } } - public function testNotifyTrackingNotCalledOnUninitializedProxies() + public function testNotifyTrackingNotCalledOnUninitializedProxies(): void { $insertedUser = new DDC2230User(); $insertedUser->address = new DDC2230Address(); @@ -46,15 +51,15 @@ public function testNotifyTrackingNotCalledOnUninitializedProxies() $mergedUser = $this->_em->merge($user); - /* @var $address Proxy */ $address = $mergedUser->address; + assert($address instanceof Proxy); $this->assertInstanceOf(Proxy::class, $address); $this->assertFalse($address->__isInitialized()); $this->assertHasDeprecationMessages(); } - public function testNotifyTrackingCalledOnProxyInitialization() + public function testNotifyTrackingCalledOnProxyInitialization(): void { $insertedAddress = new DDC2230Address(); @@ -64,7 +69,7 @@ public function testNotifyTrackingCalledOnProxyInitialization() $addressProxy = $this->_em->getReference(DDC2230Address::class, $insertedAddress->id); - /* @var $addressProxy Proxy|\Doctrine\Tests\ORM\Functional\Ticket\DDC2230Address */ + /** @var Proxy|DDC2230Address $addressProxy */ $this->assertFalse($addressProxy->__isInitialized()); $this->assertNull($addressProxy->listener); @@ -81,9 +86,7 @@ class DDC2230User /** @Id @Column(type="integer") @GeneratedValue(strategy="AUTO") */ public $id; - /** - * @OneToOne(targetEntity="DDC2230Address") - */ + /** @OneToOne(targetEntity="DDC2230Address") */ public $address; } @@ -96,9 +99,7 @@ class DDC2230Address implements NotifyPropertyChanged /** @Id @Column(type="integer") @GeneratedValue(strategy="AUTO") */ public $id; - /** - * @var \Doctrine\Common\PropertyChangedListener - */ + /** @var \Doctrine\Common\PropertyChangedListener */ public $listener; /** {@inheritDoc} */ @@ -107,4 +108,3 @@ function addPropertyChangedListener(PropertyChangedListener $listener) $this->listener = $listener; } } - diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2231Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2231Test.php index 8b5c458b7c4..11e819aef49 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2231Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2231Test.php @@ -1,30 +1,35 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2231EntityY::class), + $this->_em->getClassMetadata(DDC2231EntityY::class), ] ); } - public function testInjectObjectManagerInProxyIfInitializedInUow() + public function testInjectObjectManagerInProxyIfInitializedInUow(): void { - $y1 = new DDC2231EntityY; + $y1 = new DDC2231EntityY(); $this->_em->persist($y1); @@ -47,14 +52,12 @@ public function testInjectObjectManagerInProxyIfInitializedInUow() /** @Entity @Table(name="ddc2231_y") */ class DDC2231EntityY implements ObjectManagerAware { - /** - * @Id @Column(type="integer") @GeneratedValue - */ + /** @Id @Column(type="integer") @GeneratedValue */ public $id; public $om; - public function injectObjectManager(ObjectManager $objectManager, ClassMetadata $classMetadata) + public function injectObjectManager(ObjectManager $objectManager, ClassMetadata $classMetadata): void { $this->om = $objectManager; } @@ -64,7 +67,7 @@ public function getId() return $this->id; } - public function doSomething() + public function doSomething(): void { } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2252Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2252Test.php index 9a5e456c9fe..b955ab3beb7 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2252Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2252Test.php @@ -1,44 +1,47 @@ _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), ] ); $this->loadFixtures(); } - public function loadFixtures() + public function loadFixtures(): void { - $this->user = new DDC2252User; - $this->merchant = new DDC2252MerchantAccount; - $this->membership = new DDC2252Membership($this->user, $this->merchant); + $this->user = new DDC2252User(); + $this->merchant = new DDC2252MerchantAccount(); + $this->membership = new DDC2252Membership($this->user, $this->merchant); - $this->privileges[] = new DDC2252Privilege; - $this->privileges[] = new DDC2252Privilege; - $this->privileges[] = new DDC2252Privilege; + $this->privileges[] = new DDC2252Privilege(); + $this->privileges[] = new DDC2252Privilege(); + $this->privileges[] = new DDC2252Privilege(); $this->membership->addPrivilege($this->privileges[0]); $this->membership->addPrivilege($this->privileges[1]); @@ -56,7 +59,7 @@ public function loadFixtures() $this->_em->clear(); } - public function testIssue() + public function testIssue(): void { $identifier = [ 'merchantAccount' => $this->merchant->getAccountid(), @@ -88,7 +91,7 @@ public function testIssue() $this->assertInstanceOf(DDC2252Membership::class, $membership); $this->assertCount(0, $membership->getPrivileges()); - $membership->addPrivilege($privilege3 = new DDC2252Privilege); + $membership->addPrivilege($privilege3 = new DDC2252Privilege()); $this->_em->persist($privilege3); $this->_em->persist($membership); $this->_em->flush(); @@ -142,7 +145,8 @@ public function getAccountid() * @Entity * @Table(name="ddc2252_user_account") */ -class DDC2252User { +class DDC2252User +{ /** * @Id * @Column(type="integer") @@ -157,7 +161,7 @@ class DDC2252User { public function __construct() { - $this->memberships = new ArrayCollection; + $this->memberships = new ArrayCollection(); } public function getUid() @@ -170,7 +174,7 @@ public function getMemberships() return $this->memberships; } - public function addMembership(DDC2252Membership $membership) + public function addMembership(DDC2252Membership $membership): void { $this->memberships[] = $membership; } @@ -213,12 +217,12 @@ class DDC2252Membership public function __construct(DDC2252User $user, DDC2252MerchantAccount $merchantAccount) { - $this->userAccount = $user; - $this->merchantAccount = $merchantAccount; - $this->privileges = new ArrayCollection(); + $this->userAccount = $user; + $this->merchantAccount = $merchantAccount; + $this->privileges = new ArrayCollection(); } - public function addPrivilege($privilege) + public function addPrivilege($privilege): void { $this->privileges[] = $privilege; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2256Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2256Test.php index c38f7d645fc..9ccf1963fde 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2256Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2256Test.php @@ -1,35 +1,39 @@ _schemaTool->createSchema( [ $this->_em->getClassMetadata(DDC2256User::class), - $this->_em->getClassMetadata(DDC2256Group::class) + $this->_em->getClassMetadata(DDC2256Group::class), ] ); } - public function testIssue() + public function testIssue(): void { $config = $this->_em->getConfiguration(); $config->addEntityNamespace('MyNamespace', __NAMESPACE__); - $user = new DDC2256User(); - $user->name = 'user'; - $group = new DDC2256Group(); + $user = new DDC2256User(); + $user->name = 'user'; + $group = new DDC2256Group(); $group->name = 'group'; $user->group = $group; @@ -75,9 +79,7 @@ class DDC2256User */ public $id; - /** - * @Column(type="string") - */ + /** @Column(type="string") */ public $name; /** @@ -100,19 +102,14 @@ class DDC2256Group */ public $id; - /** - * @Column(type="string") - */ + /** @Column(type="string") */ public $name; - /** - * @OneToMany(targetEntity="DDC2256User", mappedBy="group") - */ + /** @OneToMany(targetEntity="DDC2256User", mappedBy="group") */ public $users; public function __construct() { - $this->users = new \Doctrine\Common\Collections\ArrayCollection(); + $this->users = new ArrayCollection(); } } - diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2306Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2306Test.php index baed97f1406..30085fe8ddb 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2306Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2306Test.php @@ -1,28 +1,31 @@ _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), ] ); } @@ -39,11 +42,11 @@ protected function setUp() : void * As a result, a refresh requested for an entity `Foo` with identifier `123` may cause a proxy * of type `Bar` with identifier `123` to be marked as un-managed. */ - public function testIssue() + public function testIssue(): void { $zone = new DDC2306Zone(); - $user = new DDC2306User; - $address = new DDC2306Address; + $user = new DDC2306User(); + $address = new DDC2306Address(); $userAddress = new DDC2306UserAddress($user, $address); $user->zone = $zone; $address->zone = $zone; @@ -55,10 +58,10 @@ public function testIssue() $this->_em->flush(); $this->_em->clear(); - /* @var $address DDC2306Address */ $address = $this->_em->find(DDC2306Address::class, $address->id); - /* @var $user DDC2306User|Proxy */ - $user = $address->users->first()->user; + assert($address instanceof DDC2306Address); + $user = $address->users->first()->user; + assert($user instanceof DDC2306User || $user instanceof Proxy); $this->assertInstanceOf(Proxy::class, $user); $this->assertInstanceOf(DDC2306User::class, $user); @@ -93,8 +96,7 @@ class DDC2306User public $id; /** - * @var DDC2306UserAddress[]|\Doctrine\Common\Collections\Collection - * + * @var DDC2306UserAddress[]|Collection * @OneToMany(targetEntity="DDC2306UserAddress", mappedBy="user") */ public $addresses; @@ -103,7 +105,8 @@ class DDC2306User public $zone; /** Constructor */ - public function __construct() { + public function __construct() + { $this->addresses = new ArrayCollection(); } } @@ -115,8 +118,7 @@ class DDC2306Address public $id; /** - * @var DDC2306UserAddress[]|\Doctrine\Common\Collections\Collection - * + * @var DDC2306UserAddress[]|Collection * @OneToMany(targetEntity="DDC2306UserAddress", mappedBy="address", orphanRemoval=true) */ public $users; @@ -125,7 +127,8 @@ class DDC2306Address public $zone; /** Constructor */ - public function __construct() { + public function __construct() + { $this->users = new ArrayCollection(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2346Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2346Test.php index 0cdd4607b94..80c800ec2b6 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2346Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2346Test.php @@ -1,32 +1,31 @@ _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), ] ); @@ -36,16 +35,16 @@ protected function setUp() : void /** * Verifies that fetching a OneToMany association with fetch="EAGER" does not cause N+1 queries */ - public function testIssue() + public function testIssue(): void { - $foo1 = new DDC2346Foo(); - $foo2 = new DDC2346Foo(); + $foo1 = new DDC2346Foo(); + $foo2 = new DDC2346Foo(); - $baz1 = new DDC2346Baz(); - $baz2 = new DDC2346Baz(); + $baz1 = new DDC2346Baz(); + $baz2 = new DDC2346Baz(); - $baz1->foo = $foo1; - $baz2->foo = $foo2; + $baz1->foo = $foo1; + $baz2->foo = $foo2; $foo1->bars[] = $baz1; $foo1->bars[] = $baz2; @@ -74,14 +73,14 @@ class DDC2346Foo public $id; /** - * @var DDC2346Bar[]|\Doctrine\Common\Collections\Collection - * + * @var DDC2346Bar[]|Collection * @OneToMany(targetEntity="DDC2346Bar", mappedBy="foo") */ public $bars; /** Constructor */ - public function __construct() { + public function __construct() + { $this->bars = new ArrayCollection(); } } @@ -107,5 +106,4 @@ class DDC2346Bar */ 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 5998538c05c..ed7b13c897b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2350Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2350Test.php @@ -1,33 +1,37 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2350User::class), - $this->_em->getClassMetadata(DDC2350Bug::class), + $this->_em->getClassMetadata(DDC2350User::class), + $this->_em->getClassMetadata(DDC2350Bug::class), ] ); } - public function testEagerCollectionsAreOnlyRetrievedOnce() + public function testEagerCollectionsAreOnlyRetrievedOnce(): void { - $user = new DDC2350User(); - $bug1 = new DDC2350Bug(); + $user = new DDC2350User(); + $bug1 = new DDC2350Bug(); $bug1->user = $user; - $bug2 = new DDC2350Bug(); + $bug2 = new DDC2350Bug(); $bug2->user = $user; $this->_em->persist($user); @@ -37,7 +41,7 @@ public function testEagerCollectionsAreOnlyRetrievedOnce() $this->_em->clear(); - $cnt = $this->getCurrentQueryCount(); + $cnt = $this->getCurrentQueryCount(); $user = $this->_em->find(DDC2350User::class, $user->id); $this->assertEquals($cnt + 1, $this->getCurrentQueryCount()); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2359Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2359Test.php index ad906fd912e..5dfd43f2a1d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2359Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2359Test.php @@ -1,6 +1,9 @@ createMock(MappingDriver::class); - $mockMetadata = $this->createMock(ClassMetadata::class); - $entityManager = $this->createMock(EntityManager::class); + $mockDriver = $this->createMock(MappingDriver::class); + $mockMetadata = $this->createMock(ClassMetadata::class); + $entityManager = $this->createMock(EntityManager::class); - /* @var $metadataFactory \Doctrine\ORM\Mapping\ClassMetadataFactory|\PHPUnit_Framework_MockObject_MockObject */ $metadataFactory = $this->getMockBuilder(ClassMetadataFactory::class) ->setMethods(['newClassMetadataInstance', 'wakeupReflection']) ->getMock(); + assert($metadataFactory instanceof ClassMetadataFactory || $metadataFactory instanceof PHPUnit_Framework_MockObject_MockObject); $configuration = $this->getMockBuilder(Configuration::class) ->setMethods(['getMetadataDriverImpl']) diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC237Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC237Test.php index 3dad06a4868..dd2f2c9979d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC237Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC237Test.php @@ -1,28 +1,33 @@ _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), ] ); } - public function testUninitializedProxyIsInitializedOnFetchJoin() + public function testUninitializedProxyIsInitializedOnFetchJoin(): void { - $x = new DDC237EntityX; - $y = new DDC237EntityY; - $z = new DDC237EntityZ; + $x = new DDC237EntityX(); + $y = new DDC237EntityY(); + $z = new DDC237EntityZ(); $x->data = 'X'; $y->data = 'Y'; @@ -59,7 +64,6 @@ public function testUninitializedProxyIsInitializedOnFetchJoin() $this->assertNotSame($z, $z2); $this->assertSame($z2->y, $x2->y); $this->assertInstanceOf(Proxy::class, $z2->y); - } } @@ -69,13 +73,9 @@ public function testUninitializedProxyIsInitializedOnFetchJoin() */ class DDC237EntityX { - /** - * @Id @Column(type="integer") @GeneratedValue - */ + /** @Id @Column(type="integer") @GeneratedValue */ public $id; - /** - * @Column(type="string") - */ + /** @Column(type="string") */ public $data; /** * @OneToOne(targetEntity="DDC237EntityY") @@ -88,13 +88,9 @@ class DDC237EntityX /** @Entity @Table(name="ddc237_y") */ class DDC237EntityY { - /** - * @Id @Column(type="integer") @GeneratedValue - */ + /** @Id @Column(type="integer") @GeneratedValue */ public $id; - /** - * @Column(type="string") - */ + /** @Column(type="string") */ public $data; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2387Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2387Test.php index de4e2058955..719ed49e14a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2387Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2387Test.php @@ -1,22 +1,25 @@ addColumn('id', 'integer'); $product->setPrimaryKey(['id']); - $attributes = new \Doctrine\DBAL\Schema\Table('ddc2387_attributes'); + $attributes = new Table('ddc2387_attributes'); $attributes->addColumn('product_id', 'integer'); $attributes->addColumn('attribute_name', 'string'); $attributes->setPrimaryKey(['product_id', 'attribute_name']); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2409Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2409Test.php index 04e1544e893..e5f1beb7cef 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2409Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2409Test.php @@ -1,32 +1,35 @@ useModelSet('cms'); parent::setUp(); } - public function testIssue() + public function testIssue(): void { - $em = $this->_em; - $uow = $em->getUnitOfWork(); + $em = $this->_em; + $uow = $em->getUnitOfWork(); - $originalArticle = new CmsArticle(); - $originalUser = new CmsUser(); + $originalArticle = new CmsArticle(); + $originalUser = new CmsUser(); $originalArticle->topic = 'Unit Test'; $originalArticle->text = 'How to write a test'; @@ -42,8 +45,8 @@ public function testIssue() $em->flush(); $em->clear(); - $article = $em->find(CmsArticle::class, $originalArticle->id); - $user = new CmsUser(); + $article = $em->find(CmsArticle::class, $originalArticle->id); + $user = new CmsUser(); $user->name = 'Doctrine Bot 2.0'; $user->username = 'BotDoctrine2'; @@ -59,8 +62,8 @@ public function testIssue() $em->clear(CmsUser::class); $em->clear(CmsArticle::class); - $userMerged = $em->merge($user); - $articleMerged = $em->merge($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)); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2415Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2415Test.php index 950af6c593c..56e018dd8dc 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2415Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2415Test.php @@ -1,18 +1,23 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2415ParentEntity::class), - $this->_em->getClassMetadata(DDC2415ChildEntity::class), + $this->_em->getClassMetadata(DDC2415ParentEntity::class), + $this->_em->getClassMetadata(DDC2415ChildEntity::class), ] ); } - public function testTicket() + public function testTicket(): void { - $parentMetadata = $this->_em->getClassMetadata(DDC2415ParentEntity::class); - $childMetadata = $this->_em->getClassMetadata(DDC2415ChildEntity::class); + $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"); + $e1 = new DDC2415ChildEntity('ChildEntity 1'); + $e2 = new DDC2415ChildEntity('ChildEntity 2'); $this->_em->persist($e1); $this->_em->persist($e2); @@ -57,13 +62,13 @@ public function getId() return $this->id; } - public static function loadMetadata(ClassMetadataInfo $metadata) + public static function loadMetadata(ClassMetadataInfo $metadata): void { $metadata->mapField( [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'string', + 'id' => true, + 'fieldName' => 'id', + 'type' => 'string', ] ); @@ -88,12 +93,12 @@ public function getName() return $this->name; } - public static function loadMetadata(ClassMetadataInfo $metadata) + public static function loadMetadata(ClassMetadataInfo $metadata): void { $metadata->mapField( [ - 'fieldName' => 'name', - 'type' => 'string', + 'fieldName' => 'name', + 'type' => 'string', ] ); } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2494Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2494Test.php index ffa9295e904..754a8d1c48b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2494Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2494Test.php @@ -1,17 +1,21 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2494Currency::class), - $this->_em->getClassMetadata(DDC2494Campaign::class), + $this->_em->getClassMetadata(DDC2494Currency::class), + $this->_em->getClassMetadata(DDC2494Campaign::class), ] ); } - public function testIssue() + public function testIssue(): void { $currency = new DDC2494Currency(1, 2); @@ -82,14 +86,11 @@ class DDC2494Currency */ protected $id; - /** - * @Column(name="temp", type="ddc2494_tinyint", nullable=false) - */ + /** @Column(name="temp", type="ddc2494_tinyint", nullable=false) */ protected $temp; /** - * @var \Doctrine\Common\Collections\Collection - * + * @var Collection * @OneToMany(targetEntity="DDC2494Campaign", mappedBy="currency") */ protected $campaigns; @@ -130,8 +131,7 @@ class DDC2494Campaign protected $id; /** - * @var \Doctrine\Tests\ORM\Functional\Ticket\DDC2494Currency - * + * @var DDC2494Currency * @ManyToOne(targetEntity="DDC2494Currency", inversedBy="campaigns") * @JoinColumn(name="currency_id", referencedColumnName="id", nullable=false) */ @@ -147,10 +147,7 @@ public function getId() return $this->id; } - /** - * @return \Doctrine\Tests\ORM\Functional\Ticket\DDC2494Currency - */ - public function getCurrency() + public function getCurrency(): DDC2494Currency { return $this->currency; } @@ -189,7 +186,7 @@ public function convertToDatabaseValue($value, AbstractPlatform $platform) */ public function convertToPHPValue($value, AbstractPlatform $platform) { - $return = (integer) $value; + $return = (int) $value; self::$calls[__FUNCTION__][] = [ 'value' => $value, diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2519Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2519Test.php index 3789d04a7b8..ded38c732d6 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2519Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2519Test.php @@ -1,19 +1,22 @@ useModelSet('legacy'); parent::setUp(); @@ -24,7 +27,7 @@ protected function setUp() : void /** * @group DDC-2519 */ - public function testIssue() + public function testIssue(): void { $dql = 'SELECT PARTIAL l.{_source, _target} FROM Doctrine\Tests\Models\Legacy\LegacyUserReference l'; $result = $this->_em->createQuery($dql)->getResult(); @@ -54,22 +57,22 @@ public function testIssue() $this->assertNotNull($result[1]->target()->getId()); } - public function loadFixture() + public function loadFixture(): void { - $user1 = new LegacyUser(); - $user1->_username = 'FabioBatSilva'; - $user1->_name = 'Fabio B. Silva'; - $user1->_status = 'active'; - - $user2 = new LegacyUser(); - $user2->_username = 'doctrinebot'; - $user2->_name = 'Doctrine Bot'; - $user2->_status = 'active'; - - $user3 = new LegacyUser(); - $user3->_username = 'test'; - $user3->_name = 'Tester'; - $user3->_status = 'active'; + $user1 = new LegacyUser(); + $user1->_username = 'FabioBatSilva'; + $user1->_name = 'Fabio B. Silva'; + $user1->_status = 'active'; + + $user2 = new LegacyUser(); + $user2->_username = 'doctrinebot'; + $user2->_name = 'Doctrine Bot'; + $user2->_status = 'active'; + + $user3 = new LegacyUser(); + $user3->_username = 'test'; + $user3->_name = 'Tester'; + $user3->_status = 'active'; $this->_em->persist($user1); $this->_em->persist($user2); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2575Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2575Test.php index 0e6b1a1b33f..45d9ded7964 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2575Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2575Test.php @@ -1,39 +1,43 @@ _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), ] ); $entityRoot1 = new DDC2575Root(1); - $entityB1 = new DDC2575B(2); - $entityA1 = new DDC2575A($entityRoot1, $entityB1); + $entityB1 = new DDC2575B(2); + $entityA1 = new DDC2575A($entityRoot1, $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); + $entityB2 = new DDC2575B(4); + $entityA2 = new DDC2575A($entityRoot2, $entityB2); $this->_em->persist($entityRoot2); $this->_em->persist($entityA2); @@ -53,15 +57,15 @@ protected function setUp() : void $this->_em->clear(); } - public function testHydrationIssue() + public function testHydrationIssue(): void { $repository = $this->_em->getRepository(DDC2575Root::class); - $qb = $repository->createQueryBuilder('r') + $qb = $repository->createQueryBuilder('r') ->select('r, a, b') ->leftJoin('r.aRelation', 'a') ->leftJoin('a.bRelation', 'b'); - $query = $qb->getQuery(); + $query = $qb->getQuery(); $result = $query->getResult(); $this->assertCount(2, $result); @@ -95,22 +99,17 @@ class DDC2575Root */ public $id; - /** - * @Column(type="integer") - */ + /** @Column(type="integer") */ public $sampleField; - /** - * @OneToOne(targetEntity="DDC2575A", mappedBy="rootRelation") - **/ + /** @OneToOne(targetEntity="DDC2575A", mappedBy="rootRelation") **/ public $aRelation; public function __construct($id, $value = 0) { - $this->id = $id; + $this->id = $id; $this->sampleField = $value; } - } /** @@ -134,7 +133,7 @@ class DDC2575A public function __construct(DDC2575Root $rootRelation, DDC2575B $bRelation) { $this->rootRelation = $rootRelation; - $this->bRelation = $bRelation; + $this->bRelation = $bRelation; } } @@ -149,14 +148,12 @@ class DDC2575B */ public $id; - /** - * @Column(type="integer") - */ + /** @Column(type="integer") */ public $sampleField; public function __construct($id, $value = 0) { - $this->id = $id; + $this->id = $id; $this->sampleField = $value; } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2579Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2579Test.php index 67d4712b090..ea42947a6ca 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2579Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2579Test.php @@ -1,17 +1,20 @@ _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), ] ); } - public function testIssue() + public function testIssue(): void { - $id = new DDC2579Id("foo"); + $id = new DDC2579Id('foo'); $assoc = new DDC2579AssocAssoc($id); $assocAssoc = new DDC2579EntityAssoc($assoc); $entity = new DDC2579Entity($assocAssoc); @@ -80,9 +83,7 @@ class DDC2579Entity */ public $assoc; - /** - * @Column(type="integer") - */ + /** @Column(type="integer") */ public $value; public function __construct(DDC2579EntityAssoc $assoc, $value = 0) @@ -91,7 +92,6 @@ public function __construct(DDC2579EntityAssoc $assoc, $value = 0) $this->assoc = $assoc; $this->value = $value; } - } /** @@ -125,21 +125,21 @@ class DDC2579AssocAssoc public function __construct(DDC2579Id $id) { - $this->associationId = $id; + $this->associationId = $id; } } class DDC2579Type extends StringType { - const NAME = 'ddc2579'; + public const NAME = 'ddc2579'; /** * {@inheritdoc} */ public function convertToDatabaseValue($value, AbstractPlatform $platform) { - return (string)$value; + return (string) $value; } public function convertToPhpValue($value, AbstractPlatform $platform) diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC258Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC258Test.php index 8f654987958..e69f487d65e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC258Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC258Test.php @@ -1,20 +1,22 @@ _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), ] ); } @@ -22,22 +24,22 @@ protected function setUp() : void /** * @group DDC-258 */ - public function testIssue() + public function testIssue(): void { //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $c1 = new DDC258Class1(); - $c1->title = "Foo"; - $c1->description = "Foo"; + $c1 = new DDC258Class1(); + $c1->title = 'Foo'; + $c1->description = 'Foo'; - $c2 = new DDC258Class2(); - $c2->title = "Bar"; - $c2->description = "Bar"; - $c2->text = "Bar"; + $c2 = new DDC258Class2(); + $c2->title = 'Bar'; + $c2->description = 'Bar'; + $c2->text = 'Bar'; - $c3 = new DDC258Class3(); - $c3->apples = "Baz"; - $c3->bananas = "Baz"; + $c3 = new DDC258Class3(); + $c3->apples = 'Baz'; + $c3->bananas = 'Baz'; $this->_em->persist($c1); $this->_em->persist($c2); @@ -58,12 +60,12 @@ public function testIssue() if ($obj instanceof DDC258Class1) { $this->assertEquals('Foo', $obj->title); $this->assertEquals('Foo', $obj->description); - } else if ($obj instanceof DDC258Class2) { + } elseif ($obj instanceof DDC258Class2) { $this->assertTrue($e2 === $obj); $this->assertEquals('Bar', $obj->title); $this->assertEquals('Bar', $obj->description); $this->assertEquals('Bar', $obj->text); - } else if ($obj instanceof DDC258Class3) { + } elseif ($obj instanceof DDC258Class3) { $this->assertEquals('Baz', $obj->apples); $this->assertEquals('Baz', $obj->bananas); } else { @@ -85,7 +87,7 @@ abstract class DDC258Super /** * @Id @Column(name="id", type="integer") * @GeneratedValue(strategy="AUTO") - */ + */ public $id; } @@ -94,14 +96,10 @@ abstract class DDC258Super */ class DDC258Class1 extends DDC258Super { - /** - * @Column(name="title", type="string", length=150) - */ + /** @Column(name="title", type="string", length=150) */ public $title; - /** - * @Column(name="content", type="string", length=500) - */ + /** @Column(name="content", type="string", length=500) */ public $description; } @@ -110,19 +108,13 @@ class DDC258Class1 extends DDC258Super */ class DDC258Class2 extends DDC258Super { - /** - * @Column(name="title", type="string", length=150) - */ + /** @Column(name="title", type="string", length=150) */ public $title; - /** - * @Column(name="content", type="string", length=500) - */ + /** @Column(name="content", type="string", length=500) */ public $description; - /** - * @Column(name="text", type="text") - */ + /** @Column(name="text", type="text") */ public $text; } @@ -133,13 +125,9 @@ class DDC258Class2 extends DDC258Super */ class DDC258Class3 extends DDC258Super { - /** - * @Column(name="title", type="string", length=150) - */ + /** @Column(name="title", type="string", length=150) */ public $apples; - /** - * @Column(name="content", type="string", length=500) - */ + /** @Column(name="content", type="string", length=500) */ public $bananas; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2602Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2602Test.php index 23b9f662f56..1c4156f5ab3 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2602Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2602Test.php @@ -1,5 +1,7 @@ loadFixture(); } - protected function tearDown() : void + protected function tearDown(): void { parent::tearDown(); @@ -42,7 +47,7 @@ protected function tearDown() : void ); } - public function testPostLoadListenerShouldBeAbleToRunQueries() : void + public function testPostLoadListenerShouldBeAbleToRunQueries(): void { $eventManager = $this->_em->getEventManager(); $eventManager->addEventListener([Events::postLoad], new DDC2602PostLoadListener()); @@ -55,7 +60,7 @@ public function testPostLoadListenerShouldBeAbleToRunQueries() : void self::assertCount(1, $result[1]->biography->fieldList); } - private function loadFixture() : void + private function loadFixture(): void { $user1 = new DDC2602User(); $user2 = new DDC2602User(); @@ -70,16 +75,16 @@ private function loadFixture() : void $biographyFieldChoice5 = new DDC2602BiographyFieldChoice(); $biographyFieldChoice6 = new DDC2602BiographyFieldChoice(); - $user1->name = 'Gblanco'; + $user1->name = 'Gblanco'; $user1->biography = $biography1; - $user2->name = 'Beberlei'; + $user2->name = 'Beberlei'; $user2->biography = $biography2; - $biography1->user = $user1; + $biography1->user = $user1; $biography1->content = '[{"field": 1, "choiceList": [1,3]}, {"field": 2, "choiceList": [5]}]'; - $biography2->user = $user2; + $biography2->user = $user2; $biography2->content = '[{"field": 1, "choiceList": [1,2,3,4]}]'; $biographyField1->alias = 'question_1'; @@ -126,11 +131,11 @@ private function loadFixture() : void class DDC2602PostLoadListener { - public function postLoad(LifecycleEventArgs $event) : void + public function postLoad(LifecycleEventArgs $event): void { $entity = $event->getEntity(); - if ( ! ($entity instanceof DDC2602Biography)) { + if (! ($entity instanceof DDC2602Biography)) { return; } @@ -146,12 +151,12 @@ public function postLoad(LifecycleEventArgs $event) : void $fieldList = new ArrayCollection(); foreach ($content as $selection) { - $field = $result[$selection->field]; - $choiceList = $selection->choiceList; - $fieldSelection = new DDC2602FieldSelection(); + $field = $result[$selection->field]; + $choiceList = $selection->choiceList; + $fieldSelection = new DDC2602FieldSelection(); $fieldSelection->field = $field; - $fieldSelection->choiceList = $field->choiceList->filter(function ($choice) use ($choiceList) { + $fieldSelection->choiceList = $field->choiceList->filter(static function ($choice) use ($choiceList) { return in_array($choice->id, $choiceList); }); @@ -171,14 +176,12 @@ class DDC2602User /** * @Id @GeneratedValue * @Column(type="integer") - * - * @var integer + * @var int */ public $id; /** * @Column(type="string", length=15) - * * @var string */ public $name; @@ -190,7 +193,6 @@ class DDC2602User * cascade={"persist", "merge", "refresh", "remove"} * ) * @JoinColumn(nullable=false) - * * @var DDC2602Biography */ public $biography; @@ -204,8 +206,7 @@ class DDC2602Biography /** * @Id @GeneratedValue * @Column(type="integer") - * - * @var integer + * @var int */ public $id; @@ -215,21 +216,17 @@ class DDC2602Biography * mappedBy="biography", * cascade={"persist", "merge", "refresh"} * ) - * * @var DDC2602User */ public $user; /** * @Column(type="text", nullable=true) - * * @var string */ public $content; - /** - * @var array - */ + /** @var array */ public $fieldList = []; } @@ -241,19 +238,14 @@ class DDC2602BiographyField /** * @Id @GeneratedValue * @Column(type="integer") - * - * @var integer + * @var int */ public $id; - /** - * @Column(type="string", unique=true, length=100) - */ + /** @Column(type="string", unique=true, length=100) */ public $alias; - /** - * @Column(type="string", length=100) - */ + /** @Column(type="string", length=100) */ public $label; /** @@ -262,15 +254,10 @@ class DDC2602BiographyField * mappedBy="field", * cascade={"persist", "merge", "refresh"} * ) - * - * @var \Doctrine\Common\Collections\ArrayCollection + * @var ArrayCollection */ public $choiceList; - /** - * Constructor. - * - */ public function __construct() { $this->choiceList = new ArrayCollection(); @@ -285,14 +272,11 @@ class DDC2602BiographyFieldChoice /** * @Id @GeneratedValue * @Column(type="integer") - * - * @var integer + * @var int */ public $id; - /** - * @Column(type="string", unique=true, length=100) - */ + /** @Column(type="string", unique=true, length=100) */ public $label; /** @@ -301,7 +285,6 @@ class DDC2602BiographyFieldChoice * inversedBy="choiceList" * ) * @JoinColumn(onDelete="CASCADE") - * * @var DDC2602BiographyField */ public $field; @@ -309,20 +292,12 @@ class DDC2602BiographyFieldChoice class DDC2602FieldSelection { - /** - * @var DDC2602BiographyField - */ + /** @var DDC2602BiographyField */ public $field; - /** - * @var \Doctrine\Common\Collections\ArrayCollection - */ + /** @var ArrayCollection */ public $choiceList; - /** - * Constructor. - * - */ public function __construct() { $this->choiceList = new ArrayCollection(); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2645Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2645Test.php index e71de5b3f0a..4af6bec6f71 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2645Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2645Test.php @@ -1,22 +1,25 @@ id = 123; - $foo = new DDC2645Foo(1, $bar, 'Foo'); + $foo = new DDC2645Foo(1, $bar, 'Foo'); $foo2 = new DDC2645Foo(1, $bar, 'Bar'); $this->_em->persist($bar); @@ -44,8 +47,8 @@ class DDC2645Foo public function __construct($id, $bar, $name) { - $this->id = $id; - $this->bar = $bar; + $this->id = $id; + $this->bar = $bar; $this->name = $name; } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2655Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2655Test.php index 59ef5d31f83..382aec669f0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2655Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2655Test.php @@ -1,21 +1,24 @@ useModelSet('cms'); parent::setUp(); } - public function testSingleScalarOneOrNullResult() + public function testSingleScalarOneOrNullResult(): void { $query = $this->_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)); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2660Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2660Test.php index e6e3f4c4de3..94b332c746f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2660Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2660Test.php @@ -1,37 +1,38 @@ _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) { + } catch (Exception $e) { return; } for ($i = 0; $i < 5; $i++) { - $product = new DDC2660Product(); + $product = new DDC2660Product(); $customer = new DDC2660Customer(); - $order = new DDC2660CustomerOrder($product, $customer, 'name' . $i); + $order = new DDC2660CustomerOrder($product, $customer, 'name' . $i); $this->_em->persist($product); $this->_em->persist($customer); @@ -44,9 +45,9 @@ protected function setUp() : void $this->_em->clear(); } - public function testIssueWithExtraColumn() + public function testIssueWithExtraColumn(): void { - $sql = "SELECT o.product_id, o.customer_id, o.name FROM ddc_2660_customer_order o"; + $sql = 'SELECT o.product_id, o.customer_id, o.name FROM ddc_2660_customer_order o'; $rsm = new ResultSetMappingBuilder($this->_getEntityManager()); $rsm->addRootEntityFromClassMetadata(DDC2660CustomerOrder::class, 'c'); @@ -62,9 +63,9 @@ public function testIssueWithExtraColumn() } } - public function testIssueWithoutExtraColumn() + public function testIssueWithoutExtraColumn(): void { - $sql = "SELECT o.product_id, o.customer_id FROM ddc_2660_customer_order o"; + $sql = 'SELECT o.product_id, o.customer_id FROM ddc_2660_customer_order o'; $rsm = new ResultSetMappingBuilder($this->_getEntityManager()); $rsm->addRootEntityFromClassMetadata(DDC2660CustomerOrder::class, 'c'); @@ -99,25 +100,19 @@ class DDC2660Customer /** @Entity @Table(name="ddc_2660_customer_order") */ class DDC2660CustomerOrder { - /** - * @Id @ManyToOne(targetEntity="DDC2660Product") - */ + /** @Id @ManyToOne(targetEntity="DDC2660Product") */ public $product; - /** - * @Id @ManyToOne(targetEntity="DDC2660Customer") - */ + /** @Id @ManyToOne(targetEntity="DDC2660Customer") */ public $customer; - /** - * @Column(type="string") - */ + /** @Column(type="string") */ public $name; public function __construct(DDC2660Product $product, DDC2660Customer $customer, $name) { $this->product = $product; $this->customer = $customer; - $this->name = $name; + $this->name = $name; } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2692Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2692Test.php index c88ef9ac053..b20d0e5483c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2692Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2692Test.php @@ -1,35 +1,38 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2692Foo::class), + $this->_em->getClassMetadata(DDC2692Foo::class), ] ); - } catch(\Exception $e) { + } catch (Exception $e) { return; } + $this->_em->clear(); } - public function testIsListenerCalledOnlyOnceOnPreFlush() + public function testIsListenerCalledOnlyOnceOnPreFlush(): void { $listener = $this->getMockBuilder(DDC2692Listener::class) ->setMethods(['preFlush']) @@ -39,8 +42,8 @@ public function testIsListenerCalledOnlyOnceOnPreFlush() $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(); @@ -55,12 +58,14 @@ class DDC2692Foo public $id; } -class DDC2692Listener implements EventSubscriber { - - public function getSubscribedEvents() { - return [\Doctrine\ORM\Events::preFlush]; +class DDC2692Listener implements EventSubscriber +{ + public function getSubscribedEvents() + { + return [Events::preFlush]; } - public function preFlush(PreFlushEventArgs $args) { + public function preFlush(PreFlushEventArgs $args): void + { } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2759Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2759Test.php index f76778629d7..e567ec081d6 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2759Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2759Test.php @@ -1,33 +1,35 @@ _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) { + } catch (Exception $e) { return; } - $qualification = new DDC2759Qualification(); + $qualification = new DDC2759Qualification(); $qualificationMetadata = new DDC2759QualificationMetadata($qualification); $category1 = new DDC2759Category(); @@ -49,7 +51,7 @@ protected function setUp() : void $this->_em->clear(); } - public function testCorrectNumberOfAssociationsIsReturned() + public function testCorrectNumberOfAssociationsIsReturned(): void { $repository = $this->_em->getRepository(DDC2759Qualification::class); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2775Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2775Test.php index 62d8d5fa7cf..c8ad3e32a46 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2775Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2775Test.php @@ -1,17 +1,17 @@ */ class DDC2775Test extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { parent::setUp(); @@ -28,7 +28,7 @@ protected function setUp() : void /** * @group DDC-2775 */ - public function testIssueCascadeRemove() + public function testIssueCascadeRemove(): void { $role = new AdminRole(); $user = new User(); @@ -70,20 +70,16 @@ abstract class Role */ public $id; - /** - * @ManyToOne(targetEntity="User", inversedBy="roles") - */ + /** @ManyToOne(targetEntity="User", inversedBy="roles") */ public $user; - /** - * @OneToMany(targetEntity="Authorization", mappedBy="role", cascade={"all"}, orphanRemoval=true) - */ + /** @OneToMany(targetEntity="Authorization", mappedBy="role", cascade={"all"}, orphanRemoval=true) */ public $authorizations; - public function addAuthorization(Authorization $authorization) + public function addAuthorization(Authorization $authorization): void { $this->authorizations[] = $authorization; - $authorization->role = $this; + $authorization->role = $this; } } @@ -103,14 +99,10 @@ class Authorization */ public $id; - /** - * @ManyToOne(targetEntity="User", inversedBy="authorizations") - */ + /** @ManyToOne(targetEntity="User", inversedBy="authorizations") */ public $user; - /** - * @ManyToOne(targetEntity="Role", inversedBy="authorizations") - */ + /** @ManyToOne(targetEntity="Role", inversedBy="authorizations") */ public $role; } @@ -125,25 +117,21 @@ class User */ public $id; - /** - * @OneToMany(targetEntity="Role", mappedBy="user", cascade={"all"}, orphanRemoval=true) - */ + /** @OneToMany(targetEntity="Role", mappedBy="user", cascade={"all"}, orphanRemoval=true) */ public $roles; - /** - * @OneToMany(targetEntity="Authorization", mappedBy="user", cascade={"all"}, orphanRemoval=true) - */ + /** @OneToMany(targetEntity="Authorization", mappedBy="user", cascade={"all"}, orphanRemoval=true) */ public $authorizations; - public function addRole(Role $role) + public function addRole(Role $role): void { $this->roles[] = $role; - $role->user = $this; + $role->user = $this; } - public function addAuthorization(Authorization $authorization) + public function addAuthorization(Authorization $authorization): void { $this->authorizations[] = $authorization; - $authorization->user = $this; + $authorization->user = $this; } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2780Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2780Test.php index 2fd0f2dd0f5..c207d69cf2a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2780Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2780Test.php @@ -1,25 +1,25 @@ _schemaTool->createSchema( [ $this->_em->getClassMetadata(DDC2780User::class), - $this->_em->getClassMetadata(DDC2780Project::class) + $this->_em->getClassMetadata(DDC2780Project::class), ] ); } @@ -27,10 +27,10 @@ protected function setUp() : void /** * Verifies that IS [NOT] NULL can be used on join aliases */ - public function testIssue() + public function testIssue(): void { - $user = new DDC2780User; - $project = new DDC2780Project; + $user = new DDC2780User(); + $project = new DDC2780Project(); $user->project = $project; @@ -61,7 +61,6 @@ class DDC2780User /** * @ManyToOne(targetEntity="DDC2780Project") - * * @var DDC2780Project */ public $project; @@ -75,7 +74,6 @@ class DDC2780Project /** * @OneToMany(targetEntity="DDC2780User", mappedBy="project") - * * @var DDC2780User[] */ public $users; @@ -86,4 +84,3 @@ public function __construct() $this->users = new ArrayCollection(); } } - diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2790Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2790Test.php index b14c098ff6d..e6a358429f7 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2790Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2790Test.php @@ -1,20 +1,24 @@ useModelSet('cms'); parent::setUp(); @@ -24,17 +28,17 @@ protected function setUp() : void * Verifies that entities scheduled for deletion are not treated as updated by UoW, * even if their properties are changed after the remove() call */ - public function testIssue() + public function testIssue(): void { - $this->_em->getEventManager()->addEventListener(Events::onFlush, new OnFlushListener); + $this->_em->getEventManager()->addEventListener(Events::onFlush, new OnFlushListener()); - $entity = new CmsUser; + $entity = new CmsUser(); $entity->username = 'romanb'; - $entity->name = 'Roman'; + $entity->name = 'Roman'; $qb = $this->_em->createQueryBuilder(); $qb->from(get_class($entity), 'c'); - $qb->select("count(c)"); + $qb->select('count(c)'); $initial = intval($qb->getQuery()->getSingleScalarResult()); $this->_em->persist($entity); @@ -49,7 +53,7 @@ public function testIssue() $qb = $this->_em->createQueryBuilder(); $qb->from(get_class($entity), 'c'); - $qb->select("count(c)"); + $qb->select('count(c)'); $count = intval($qb->getQuery()->getSingleScalarResult()); $this->assertEquals($initial, $count); } @@ -61,16 +65,15 @@ class OnFlushListener * onFLush listener that tries to cancel deletions by calling persist if the entity is listed * as updated in UoW */ - public function onFlush(OnFlushEventArgs $args) + public function onFlush(OnFlushEventArgs $args): void { - $em = $args->getEntityManager(); - $uow = $em->getUnitOfWork(); + $em = $args->getEntityManager(); + $uow = $em->getUnitOfWork(); $deletions = $uow->getScheduledEntityDeletions(); - $updates = $uow->getScheduledEntityUpdates(); + $updates = $uow->getScheduledEntityUpdates(); $undelete = array_intersect_key($deletions, $updates); - foreach ($undelete as $d) - { + foreach ($undelete as $d) { $em->persist($d); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC279Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC279Test.php index 278a3b47acc..0f703e98ab0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC279Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC279Test.php @@ -1,18 +1,24 @@ _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), ] ); } @@ -20,7 +26,7 @@ protected function setUp() : void /** * @group DDC-279 */ - public function testDDC279() + public function testDDC279(): void { $x = new DDC279EntityX(); $y = new DDC279EntityY(); @@ -41,7 +47,7 @@ public function testDDC279() $this->_em->clear(); $query = $this->_em->createQuery( - 'SELECT x, y, z FROM Doctrine\Tests\ORM\Functional\Ticket\DDC279EntityX x '. + '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); @@ -73,11 +79,8 @@ abstract class DDC279EntityXAbstract */ public $id; - /** - * @column(type="string") - */ + /** @column(type="string") */ public $data; - } /** @@ -103,9 +106,7 @@ class DDC279EntityY */ public $id; - /** - * @column(type="string") - */ + /** @column(type="string") */ public $data; /** @@ -126,8 +127,6 @@ class DDC279EntityZ */ public $id; - /** - * @column(type="string") - */ + /** @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 5060ec34a7e..622d1f30711 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2825Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2825Test.php @@ -1,40 +1,38 @@ _em->getConnection()->getDatabasePlatform(); - if ( ! $platform->supportsSchemas() && ! $platform->canEmulateSchemas()) { - $this->markTestSkipped("This test is only useful for databases that support schemas or can emulate them."); + if (! $platform->supportsSchemas() && ! $platform->canEmulateSchemas()) { + $this->markTestSkipped('This test is only useful for databases that support schemas or can emulate them.'); } } /** * @dataProvider getTestedClasses - * - * @param string $className - * @param string $expectedSchemaName - * @param string $expectedTableName */ - public function testClassSchemaMappingsValidity($className, $expectedSchemaName, $expectedTableName) + public function testClassSchemaMappingsValidity(string $className, string $expectedSchemaName, string $expectedTableName): void { $classMetadata = $this->_em->getClassMetadata($className); $platform = $this->_em->getConnection()->getDatabasePlatform(); @@ -61,10 +59,8 @@ public function testClassSchemaMappingsValidity($className, $expectedSchemaName, /** * @dataProvider getTestedClasses - * - * @param string $className */ - public function testPersistenceOfEntityWithSchemaMapping($className) + public function testPersistenceOfEntityWithSchemaMapping(string $className): void { try { $this->_schemaTool->createSchema([$this->_em->getClassMetadata($className)]); @@ -84,7 +80,7 @@ public function testPersistenceOfEntityWithSchemaMapping($className) * * @return string[][] */ - public function getTestedClasses() + public function getTestedClasses(): array { return [ [ExplicitSchemaAndTable::class, 'explicit_schema', 'explicit_table'], @@ -103,8 +99,7 @@ class DDC2825ClassWithImplicitlyDefinedSchemaAndQuotedTableName /** * @Id @GeneratedValue * @Column(type="integer") - * - * @var integer + * @var int */ public $id; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2862Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2862Test.php index 0a4fcbd8e1c..914d882a35e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2862Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2862Test.php @@ -1,16 +1,20 @@ enableSecondLevelCache(); parent::setUp(); @@ -18,18 +22,18 @@ protected function setUp() : void try { $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) { } } - public function testIssue() + public function testIssue(): void { - $user1 = new DDC2862User('Foo'); - $driver1 = new DDC2862Driver('Bar' , $user1); + $user1 = new DDC2862User('Foo'); + $driver1 = new DDC2862Driver('Bar', $user1); $this->_em->persist($user1); $this->_em->persist($driver1); @@ -64,10 +68,10 @@ public function testIssue() $this->assertEquals('Foo', $driver3->getUserProfile()->getName()); } - public function testIssueReopened() + public function testIssueReopened(): void { - $user1 = new DDC2862User('Foo'); - $driver1 = new DDC2862Driver('Bar' , $user1); + $user1 = new DDC2862User('Foo'); + $driver1 = new DDC2862Driver('Bar', $user1); $this->_em->persist($user1); $this->_em->persist($driver1); @@ -145,46 +149,30 @@ public function __construct($name, $userProfile = null) $this->userProfile = $userProfile; } - /** - * @return integer - */ - public function getId() + public function getId(): int { return $this->id; } - /** - * @param string $name - */ - public function setName($name) + public function setName(string $name): void { $this->name = $name; } - /** - * @return string - */ - public function getName() + public function getName(): string { return $this->name; } - /** - * @param \Entities\User $userProfile - */ - public function setUserProfile($userProfile) + public function setUserProfile(User $userProfile): void { $this->userProfile = $userProfile; } - /** - * @return \Entities\User - */ - public function getUserProfile() + public function getUserProfile(): User { return $this->userProfile; } - } /** @@ -212,28 +200,18 @@ public function __construct($name) $this->name = $name; } - /** - * @return integer - */ - public function getId() + public function getId(): int { return $this->id; } - /** - * @param string $name - */ - public function setName($name) + public function setName(string $name): void { $this->name = $name; } - /** - * @return string - */ - public function getName() + public function getName(): string { return $this->name; } - } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2895Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2895Test.php index fdebb43a6fb..15607a492cb 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2895Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2895Test.php @@ -1,36 +1,39 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2895::class), + $this->_em->getClassMetadata(DDC2895::class), ] ); - } catch(\Exception $e) { - + } catch (Exception $e) { } } - public function testPostLoadOneToManyInheritance() + public function testPostLoadOneToManyInheritance(): void { $cm = $this->_em->getClassMetadata(DDC2895::class); $this->assertEquals( [ - "prePersist" => ["setLastModifiedPreUpdate"], - "preUpdate" => ["setLastModifiedPreUpdate"], + 'prePersist' => ['setLastModifiedPreUpdate'], + 'preUpdate' => ['setLastModifiedPreUpdate'], ], $cm->lifecycleCallbacks ); @@ -41,11 +44,10 @@ public function testPostLoadOneToManyInheritance() $this->_em->flush(); $this->_em->clear(); - /** @var DDC2895 $ddc2895 */ $ddc2895 = $this->_em->find(get_class($ddc2895), $ddc2895->id); + assert($ddc2895 instanceof DDC2895); $this->assertNotNull($ddc2895->getLastModified()); - } } @@ -57,7 +59,7 @@ abstract class AbstractDDC2895 { /** * @Column(name="last_modified", type="datetimetz", nullable=false) - * @var \DateTime + * @var DateTime */ protected $lastModified; @@ -65,23 +67,17 @@ abstract class AbstractDDC2895 * @PrePersist * @PreUpdate */ - public function setLastModifiedPreUpdate() + public function setLastModifiedPreUpdate(): void { - $this->setLastModified(new \DateTime()); + $this->setLastModified(new DateTime()); } - /** - * @param \DateTime $lastModified - */ - public function setLastModified( $lastModified ) + public function setLastModified(DateTime $lastModified): void { $this->lastModified = $lastModified; } - /** - * @return \DateTime - */ - public function getLastModified() + public function getLastModified(): DateTime { return $this->lastModified; } @@ -99,7 +95,7 @@ class DDC2895 extends AbstractDDC2895 /** * @param mixed $id */ - public function setId( $id ) + public function setId($id): void { $this->id = $id; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2931Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2931Test.php index b4b92e3198b..f218d3d2803 100755 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2931Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2931Test.php @@ -1,30 +1,34 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2931User::class), + $this->_em->getClassMetadata(DDC2931User::class), ] ); - } catch (\Exception $e) { + } catch (Exception $e) { // no action needed - schema seems to be already in place } } - public function testIssue() + public function testIssue(): void { $first = new DDC2931User(); $second = new DDC2931User(); @@ -45,7 +49,7 @@ public function testIssue() $this->assertSame(2, $second->getRank()); } - public function testFetchJoinedEntitiesCanBeRefreshed() + public function testFetchJoinedEntitiesCanBeRefreshed(): void { $first = new DDC2931User(); $second = new DDC2931User(); @@ -89,7 +93,6 @@ public function testFetchJoinedEntitiesCanBeRefreshed() /** @Entity */ class DDC2931User { - /** @Id @Column(type="integer") @GeneratedValue(strategy="AUTO") */ public $id; @@ -105,14 +108,13 @@ class DDC2931User /** * Return Rank recursively * My rank is 1 + rank of my parent - * @return int */ - public function getRank() + public function getRank(): int { return 1 + ($this->parent ? $this->parent->getRank() : 0); } - public function __wakeup() + public function __wakeup(): void { } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2943Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2943Test.php index 823110cdaef..65c87ea68c1 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2943Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2943Test.php @@ -1,35 +1,37 @@ enableSecondLevelCache(); $this->useModelSet('cache'); parent::setUp(); } - private function loadFixtures() + private function loadFixtures(): void { - $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->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() + public function testIssue(): void { $this->loadFixtures(); @@ -48,7 +50,7 @@ public function testIssue() $this->assertPaginatorQueryHit(new Paginator(clone $query), $region->getName(), 4, 2); } - public function testIssueNonFetchJoin() + public function testIssueNonFetchJoin(): void { $this->loadFixtures(); @@ -67,7 +69,7 @@ public function testIssueNonFetchJoin() $this->assertPaginatorQueryHit(new Paginator(clone $query, false), $region->getName(), 4, 2); } - public function assertPaginatorQueryPut(Paginator $paginator, $regionName, $count, $pageSize) + public function assertPaginatorQueryPut(Paginator $paginator, $regionName, $count, $pageSize): void { $this->assertCount($count, $paginator); $this->assertCount($pageSize, $paginator->getIterator()); @@ -78,7 +80,7 @@ public function assertPaginatorQueryPut(Paginator $paginator, $regionName, $coun $this->assertEquals($count, $this->secondLevelCacheLogger->getRegionPutCount($regionName)); } - public function assertPaginatorQueryHit(Paginator $paginator, $regionName, $count, $pageSize) + public function assertPaginatorQueryHit(Paginator $paginator, $regionName, $count, $pageSize): void { $this->assertCount($count, $paginator); $this->assertCount($pageSize, $paginator->getIterator()); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2984Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2984Test.php index 191da80f729..d0f7cf38a75 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2984Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2984Test.php @@ -1,22 +1,28 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2984User::class), + $this->_em->getClassMetadata(DDC2984User::class), ] ); - } catch (\Exception $e) { + } catch (Exception $e) { // no action needed - schema seems to be already in place } } - public function testIssue() + public function testIssue(): void { $user = new DDC2984User(new DDC2984DomainUserId('unique_id_within_a_vo')); $user->applyName('Alex'); @@ -42,7 +48,7 @@ public function testIssue() $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')); @@ -65,7 +71,6 @@ class DDC2984User /** * @Id @Column(type="ddc2984_domain_user_id") * @GeneratedValue(strategy="NONE") - * * @var DDC2984DomainUserId */ private $userId; @@ -78,35 +83,22 @@ public function __construct(DDC2984DomainUserId $aUserId) $this->userId = $aUserId; } - /** - * @return DDC2984DomainUserId - */ - public function userId() + public function userId(): DDC2984DomainUserId { return $this->userId; } - /** - * @return string - */ - public function name() + public function name(): string { return $this->name; } - /** - * @param string $name - */ - public function applyName($name) + public function applyName(string $name): void { $this->name = $name; } - /** - * @param DDC2984User $other - * @return bool - */ - public function sameIdentityAs(DDC2984User $other) + public function sameIdentityAs(DDC2984User $other): bool { return $this->userId()->sameValueAs($other->userId()); } @@ -114,61 +106,40 @@ public function sameIdentityAs(DDC2984User $other) /** * DDC2984DomainUserId ValueObject - * - * @author Alexander Miertsch */ class DDC2984DomainUserId { - /** - * @var string - */ + /** @var string */ private $userIdString; - /** - * @param string $aUserIdString - */ - public function __construct($aUserIdString) + public function __construct(string $aUserIdString) { $this->userIdString = $aUserIdString; } - /** - * @return string - */ - public function toString() + public function toString(): string { return $this->userIdString; } - /** - * @return string - */ - public function __toString() + public function __toString(): string { return $this->toString(); } - /** - * @param DDC2984DomainUserId $other - * @return bool - */ - public function sameValueAs(DDC2984DomainUserId $other) + public function sameValueAs(DDC2984DomainUserId $other): bool { return $this->toString() === $other->toString(); } } -/** - * Class DDC2984UserIdCustomDbalType - * - * @author Alexander Miertsch - */ class DDC2984UserIdCustomDbalType extends StringType { public function getName() { return 'ddc2984_domain_user_id'; } + /** * {@inheritDoc} */ @@ -192,7 +163,7 @@ public function convertToDatabaseValue($value, AbstractPlatform $platform) return $value; } - if ( ! $value instanceof DDC2984DomainUserId) { + if (! $value instanceof DDC2984DomainUserId) { throw ConversionException::conversionFailed($value, $this->getName()); } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2996Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2996Test.php index 4a2436330f0..ff7c0acd58f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2996Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2996Test.php @@ -1,30 +1,36 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2996User::class), - $this->_em->getClassMetadata(DDC2996UserPreference::class), + $this->_em->getClassMetadata(DDC2996User::class), + $this->_em->getClassMetadata(DDC2996UserPreference::class), ] ); - $pref = new DDC2996UserPreference(); - $pref->user = new DDC2996User(); - $pref->value = "foo"; + $pref = new DDC2996UserPreference(); + $pref->user = new DDC2996User(); + $pref->value = 'foo'; $this->_em->persist($pref); $this->_em->persist($pref->user); $this->_em->flush(); - $pref->value = "bar"; + $pref->value = 'bar'; $this->_em->flush(); $this->assertEquals(1, $pref->user->counter); @@ -41,13 +47,9 @@ public function testIssue() */ class DDC2996User { - /** - * @Id @GeneratedValue @Column(type="integer") - */ + /** @Id @GeneratedValue @Column(type="integer") */ public $id; - /** - * @Column(type="integer") - */ + /** @Column(type="integer") */ public $counter = 0; } @@ -56,26 +58,20 @@ class DDC2996User */ class DDC2996UserPreference { - /** - * @Id @GeneratedValue @Column(type="integer") - */ + /** @Id @GeneratedValue @Column(type="integer") */ public $id; - /** - * @Column(type="string") - */ + /** @Column(type="string") */ public $value; - /** - * @ManyToOne(targetEntity="DDC2996User") - */ + /** @ManyToOne(targetEntity="DDC2996User") */ public $user; /** * @PreFlush */ - public function preFlush($event) + public function preFlush($event): void { - $em = $event->getEntityManager(); + $em = $event->getEntityManager(); $uow = $em->getUnitOfWork(); if ($uow->getOriginalEntityData($this->user)) { diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3033Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3033Test.php index b25686dce10..945736ff426 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3033Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3033Test.php @@ -1,40 +1,45 @@ _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"; + $user = new DDC3033User(); + $user->name = 'Test User'; $this->_em->persist($user); - $user2 = new DDC3033User(); - $user2->name = "Test User 2"; + $user2 = new DDC3033User(); + $user2->name = 'Test User 2'; $this->_em->persist($user2); - $product = new DDC3033Product(); - $product->title = "Test product"; + $product = new DDC3033Product(); + $product->title = 'Test product'; $product->buyers[] = $user; $this->_em->persist($product); $this->_em->flush(); - $product->title = "Test Change title"; + $product->title = 'Test Change title'; $product->buyers[] = $user2; $this->_em->persist($product); @@ -61,7 +66,6 @@ class DDC3033Product /** * @var int $id - * * @Column(name="id", type="integer") * @Id * @GeneratedValue(strategy="AUTO") @@ -70,7 +74,6 @@ class DDC3033Product /** * @var string $title - * * @Column(name="title", type="string", length=255) */ public $title; @@ -96,14 +99,14 @@ public function __construct() /** * @PreUpdate */ - public function preUpdate(LifecycleEventArgs $eventArgs) + public function preUpdate(LifecycleEventArgs $eventArgs): void { } /** * @PostUpdate */ - public function postUpdate(LifecycleEventArgs $eventArgs) + public function postUpdate(LifecycleEventArgs $eventArgs): void { $em = $eventArgs->getEntityManager(); $uow = $em->getUnitOfWork(); @@ -123,7 +126,6 @@ class DDC3033User { /** * @var int - * * @Column(name="id", type="integer") * @Id * @GeneratedValue(strategy="AUTO") @@ -132,7 +134,6 @@ class DDC3033User /** * @var string - * * @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 5b783df8407..78cbf748478 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3042Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3042Test.php @@ -1,5 +1,7 @@ _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() + public function testSQLGenerationDoesNotProvokeAliasCollisions(): void { $this->assertStringNotMatchesFormat( '%sfield11%sfield11%s', diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3068Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3068Test.php index 61d892b4c40..9eb4135d411 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3068Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3068Test.php @@ -1,22 +1,23 @@ */ -class DDC3068Test extends \Doctrine\Tests\OrmFunctionalTestCase +class DDC3068Test extends OrmFunctionalTestCase { private $foo; private $merc; - protected function setUp() : void + protected function setUp(): void { $this->useModelSet('taxi'); parent::setUp(); @@ -38,21 +39,19 @@ protected function setUp() : void $this->_em->flush(); } - public function testFindUsingAnArrayOfObjectAsPrimaryKey() + public function testFindUsingAnArrayOfObjectAsPrimaryKey(): void { $ride1 = $this->_em->find(Ride::class, [ 'driver' => $this->foo->getId(), - 'car' => $this->merc->getBrand() - ] - ); + 'car' => $this->merc->getBrand(), + ]); $this->assertInstanceOf(Ride::class, $ride1); $ride2 = $this->_em->find(Ride::class, [ 'driver' => $this->foo, - 'car' => $this->merc - ] - ); + 'car' => $this->merc, + ]); $this->assertInstanceOf(Ride::class, $ride2); $this->assertSame($ride1, $ride2); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC309Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC309Test.php index 557aa1106fc..14c3c256108 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC309Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC309Test.php @@ -1,23 +1,25 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC309Country::class), - $this->_em->getClassMetadata(DDC309User::class), + $this->_em->getClassMetadata(DDC309Country::class), + $this->_em->getClassMetadata(DDC309User::class), ] ); } - public function testTwoIterateHydrations() + public function testTwoIterateHydrations(): void { $c1 = new DDC309Country(); $c2 = new DDC309Country(); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3103Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3103Test.php index fe8329345ca..5b9ff2f391e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3103Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3103Test.php @@ -1,18 +1,24 @@ useModelSet('cms'); parent::setUp(); } - public function testIssue() + public function testIssue(): void { $test = $this; $user = new CmsUser(); @@ -30,14 +33,14 @@ public function testIssue() $this->_em->persist($user); $uow->scheduleExtraUpdate($user, ['name' => 'changed name']); - $listener = $this->getMockBuilder(\stdClass::class) + $listener = $this->getMockBuilder(stdClass::class) ->setMethods([Events::postFlush]) ->getMock(); $listener ->expects($this->once()) ->method(Events::postFlush) - ->will($this->returnCallback(function () use ($uow, $test) { + ->will($this->returnCallback(static function () use ($uow, $test): void { $reflection = new ReflectionObject($uow); $property = $reflection->getProperty('extraUpdates'); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3160Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3160Test.php index 1eae53f4773..ba2b125a653 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3160Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3160Test.php @@ -1,20 +1,22 @@ useModelSet('cms'); parent::setUp(); @@ -23,15 +25,15 @@ protected function setUp() : void /** * @group DDC-3160 */ - public function testNoUpdateOnInsert() + public function testNoUpdateOnInsert(): void { $listener = new DDC3160OnFlushListener(); $this->_em->getEventManager()->addEventListener(Events::onFlush, $listener); - $user = new CmsUser; + $user = new CmsUser(); $user->username = 'romanb'; - $user->name = 'Roman'; - $user->status = 'Dev'; + $user->name = 'Roman'; + $user->status = 'Dev'; $this->_em->persist($user); $this->_em->flush(); @@ -49,16 +51,16 @@ class DDC3160OnFlushListener public $inserts = 0; public $updates = 0; - public function onFlush(OnFlushEventArgs $args) + public function onFlush(OnFlushEventArgs $args): void { - $em = $args->getEntityManager(); + $em = $args->getEntityManager(); $uow = $em->getUnitOfWork(); foreach ($uow->getScheduledEntityInsertions() as $entity) { $this->inserts++; if ($entity instanceof CmsUser) { $entity->username = 'romanc'; - $cm = $em->getClassMetadata(get_class($entity)); + $cm = $em->getClassMetadata(get_class($entity)); $uow->recomputeSingleEntityChangeSet($cm, $entity); } } @@ -68,4 +70,3 @@ public function onFlush(OnFlushEventArgs $args) } } } - diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3170Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3170Test.php index b24f977c8cf..410cd4b6f11 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3170Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3170Test.php @@ -1,19 +1,18 @@ _em->persist($productJoined); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3192Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3192Test.php index ae142776285..e9a8cc1cd0b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3192Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3192Test.php @@ -1,18 +1,23 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC3192Currency::class), - $this->_em->getClassMetadata(DDC3192Transaction::class), + $this->_em->getClassMetadata(DDC3192Currency::class), + $this->_em->getClassMetadata(DDC3192Transaction::class), ] ); } - public function testIssue() + public function testIssue(): void { $currency = new DDC3192Currency('BYR'); $this->_em->persist($currency); $this->_em->flush(); - $amount = 50; + $amount = 50; $transaction = new DDC3192Transaction($amount, $currency); $this->_em->persist($transaction); @@ -79,8 +84,7 @@ class DDC3192Currency public $code; /** - * @var \Doctrine\Common\Collections\Collection - * + * @var Collection * @OneToMany(targetEntity="DDC3192Transaction", mappedBy="currency") */ public $transactions; @@ -106,14 +110,12 @@ class DDC3192Transaction /** * @var int - * * @Column(type="integer") */ public $amount; /** - * @var \Doctrine\Tests\ORM\Functional\Ticket\DDC3192Currency - * + * @var DDC3192Currency * @ManyToOne(targetEntity="DDC3192Currency", inversedBy="transactions") * @JoinColumn(name="currency_id", referencedColumnName="code", nullable=false) */ @@ -121,16 +123,14 @@ class DDC3192Transaction public function __construct($amount, DDC3192Currency $currency) { - $this->amount = $amount; + $this->amount = $amount; $this->currency = $currency; } } class DDC3192CurrencyCode extends Type { - private static $map = [ - 'BYR' => 974, - ]; + private static $map = ['BYR' => 974]; /** * {@inheritdoc} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3223Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3223Test.php index 813af9a9fa1..5848913e509 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3223Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3223Test.php @@ -1,35 +1,35 @@ */ class DDC3223Test extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { parent::setUp(); $this->setUpEntitySchema( [ - Journalist::class, - Participant::class, - Status::class, - ProfileStatus::class, + Journalist::class, + Participant::class, + Status::class, + ProfileStatus::class, ] ); } - public function testIssueGetId() + public function testIssueGetId(): void { $profileStatus = new ProfileStatus(); - $participant = new Journalist(); + $participant = new Journalist(); $participant->profileStatus = $profileStatus; $this->_em->persist($profileStatus); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3300Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3300Test.php index 17de7d217e1..d951a4b0e60 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3300Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3300Test.php @@ -1,15 +1,18 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC3300Person::class), + $this->_em->getClassMetadata(DDC3300Person::class), ] ); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3303Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3303Test.php index 77e1e5837d0..7a7276ff30a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3303Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3303Test.php @@ -1,11 +1,14 @@ */ -class DDC331Test extends \Doctrine\Tests\OrmFunctionalTestCase +class DDC331Test extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { $this->useModelSet('company'); parent::setUp(); @@ -18,7 +22,7 @@ protected function setUp() : void /** * @group DDC-331 */ - public function testSelectFieldOnRootEntity() + public function testSelectFieldOnRootEntity(): void { $q = $this->_em->createQuery('SELECT e.name FROM Doctrine\Tests\Models\Company\CompanyEmployee e'); $this->assertEquals( diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3330Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3330Test.php index 5af4d0669b4..77775ed3f26 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3330Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3330Test.php @@ -1,30 +1,33 @@ */ class DDC3330Test extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { parent::setUp(); $this->setUpEntitySchema( [ - DDC3330_Building::class, - DDC3330_Hall::class, + DDC3330_Building::class, + DDC3330_Hall::class, ] ); } - public function testIssueCollectionOrderWithPaginator() + public function testIssueCollectionOrderWithPaginator(): void { $this->createBuildingAndHalls(); $this->createBuildingAndHalls(); @@ -33,9 +36,9 @@ public function testIssueCollectionOrderWithPaginator() $this->_em->clear(); $query = $this->_em->createQuery( - 'SELECT b, h'. - ' FROM Doctrine\Tests\ORM\Functional\Ticket\DDC3330_Building b'. - ' LEFT JOIN b.halls h'. + 'SELECT b, h' . + ' FROM Doctrine\Tests\ORM\Functional\Ticket\DDC3330_Building b' . + ' LEFT JOIN b.halls h' . ' ORDER BY b.id ASC, h.name DESC' ) ->setMaxResults(3); @@ -48,13 +51,13 @@ public function testIssueCollectionOrderWithPaginator() /** * Create a building and 10 halls */ - private function createBuildingAndHalls() + private function createBuildingAndHalls(): void { $building = new DDC3330_Building(); for ($i = 0; $i < 10; $i++) { - $hall = new DDC3330_Hall(); - $hall->name = 'HALL-'.$i; + $hall = new DDC3330_Hall(); + $hall->name = 'HALL-' . $i; $building->addHall($hall); } @@ -74,14 +77,12 @@ class DDC3330_Building */ public $id; - /** - * @OneToMany(targetEntity="DDC3330_Hall", mappedBy="building", cascade={"persist"}) - */ + /** @OneToMany(targetEntity="DDC3330_Hall", mappedBy="building", cascade={"persist"}) */ public $halls; - public function addHall(DDC3330_Hall $hall) + public function addHall(DDC3330_Hall $hall): void { - $this->halls[] = $hall; + $this->halls[] = $hall; $hall->building = $this; } } @@ -97,13 +98,9 @@ class DDC3330_Hall */ public $id; - /** - * @ManyToOne(targetEntity="DDC3330_Building", inversedBy="halls") - */ + /** @ManyToOne(targetEntity="DDC3330_Building", inversedBy="halls") */ public $building; - /** - * @Column(type="string", length=100) - */ + /** @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 eeafa12beac..c3575abfc65 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3346Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3346Test.php @@ -1,16 +1,21 @@ useModelSet('ddc3346'); @@ -19,19 +24,19 @@ protected function setUp() : void $this->loadAuthorFixture(); } - public function testFindOneWithEagerFetchWillNotHydrateLimitedCollection() + public function testFindOneWithEagerFetchWillNotHydrateLimitedCollection(): void { - /* @var DDC3346Author $author */ $author = $this->_em->getRepository(DDC3346Author::class)->findOneBy( ['username' => 'bwoogy'] ); + assert($author instanceof DDC3346Author); $this->assertCount(2, $author->articles); } - public function testFindLimitedWithEagerFetchWillNotHydrateLimitedCollection() + public function testFindLimitedWithEagerFetchWillNotHydrateLimitedCollection(): void { - /* @var DDC3346Author[] $authors */ + /** @var DDC3346Author[] $authors */ $authors = $this->_em->getRepository(DDC3346Author::class)->findBy( ['username' => 'bwoogy'], null, @@ -42,9 +47,9 @@ public function testFindLimitedWithEagerFetchWillNotHydrateLimitedCollection() $this->assertCount(2, $authors[0]->articles); } - public function testFindWithEagerFetchAndOffsetWillNotHydrateLimitedCollection() + public function testFindWithEagerFetchAndOffsetWillNotHydrateLimitedCollection(): void { - /* @var DDC3346Author[] $authors */ + /** @var DDC3346Author[] $authors */ $authors = $this->_em->getRepository(DDC3346Author::class)->findBy( ['username' => 'bwoogy'], null, @@ -56,7 +61,7 @@ public function testFindWithEagerFetchAndOffsetWillNotHydrateLimitedCollection() $this->assertCount(2, $authors[0]->articles); } - private function loadAuthorFixture() + private function loadAuthorFixture(): void { $user = new DDC3346Author(); $article1 = new DDC3346Article(); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC345Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC345Test.php index e570f1e3a8e..bc45e5e4e1b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC345Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC345Test.php @@ -1,37 +1,43 @@ _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), ] ); } - public function testTwoIterateHydrations() + public function testTwoIterateHydrations(): void { // Create User - $user = new DDC345User; + $user = new DDC345User(); $user->name = 'Test User'; $this->_em->persist($user); // $em->flush() does not change much here // Create Group - $group = new DDC345Group; + $group = new DDC345Group(); $group->name = 'Test Group'; $this->_em->persist($group); // $em->flush() does not change much here - $membership = new DDC345Membership; + $membership = new DDC345Membership(); $membership->group = $group; - $membership->user = $user; + $membership->user = $user; $membership->state = 'active'; //$this->_em->persist($membership); // COMMENT OUT TO SEE BUG @@ -72,7 +78,7 @@ class DDC345User public function __construct() { - $this->Memberships = new \Doctrine\Common\Collections\ArrayCollection; + $this->Memberships = new ArrayCollection(); } } @@ -94,10 +100,9 @@ class DDC345Group /** @OneToMany(targetEntity="DDC345Membership", mappedBy="group", cascade={"persist"}) */ public $Memberships; - public function __construct() { - $this->Memberships = new \Doctrine\Common\Collections\ArrayCollection; + $this->Memberships = new ArrayCollection(); } } @@ -136,22 +141,21 @@ class DDC345Membership public $updated; public $prePersistCallCount = 0; - public $preUpdateCallCount = 0; + public $preUpdateCallCount = 0; /** @PrePersist */ - public function doStuffOnPrePersist() + public function doStuffOnPrePersist(): void { //echo "***** PrePersist\n"; ++$this->prePersistCallCount; - $this->updated = new \DateTime; + $this->updated = new DateTime(); } /** @PreUpdate */ - public function doStuffOnPreUpdate() + public function doStuffOnPreUpdate(): void { //echo "***** PreUpdate\n"; ++$this->preUpdateCallCount; - $this->updated = new \DateTime; + $this->updated = new DateTime(); } } - diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC353Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC353Test.php index cdc780b9513..588c56257c1 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC353Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC353Test.php @@ -1,29 +1,34 @@ _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) {} + } catch (Exception $ignored) { + } } - public function testWorkingCase() + public function testWorkingCase(): void { - $file = new DDC353File; + $file = new DDC353File(); - $picture = new DDC353Picture; + $picture = new DDC353Picture(); $picture->setFile($file); $em = $this->_em; @@ -35,20 +40,20 @@ public function testWorkingCase() $this->assertTrue($fileId > 0); $file = $em->getReference(DDC353File::class, $fileId); - $this->assertEquals(UnitOfWork::STATE_MANAGED, $em->getUnitOfWork()->getEntityState($file), "Reference Proxy should be marked MANAGED."); + $this->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."); + $this->assertEquals(UnitOfWork::STATE_MANAGED, $em->getUnitOfWork()->getEntityState($picture->getFile()), 'Lazy Proxy should be marked MANAGED.'); $em->remove($picture); $em->flush(); } - public function testFailingCase() + public function testFailingCase(): void { - $file = new DDC353File; + $file = new DDC353File(); - $picture = new DDC353Picture; + $picture = new DDC353Picture(); $picture->setFile($file); $em = $this->_em; @@ -56,13 +61,13 @@ public function testFailingCase() $em->flush(); $em->clear(); - $fileId = $file->getFileId(); + $fileId = $file->getFileId(); $pictureId = $picture->getPictureId(); $this->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."); + $this->assertEquals(UnitOfWork::STATE_MANAGED, $em->getUnitOfWork()->getEntityState($picture->getFile()), 'Lazy Proxy should be marked MANAGED.'); $em->remove($picture); $em->flush(); @@ -99,7 +104,7 @@ public function getPictureId() /** * Set product */ - public function setProduct($value) + public function setProduct($value): void { $this->product = $value; } @@ -115,7 +120,7 @@ public function getProduct() /** * Set file */ - public function setFile($value) + public function setFile($value): void { $this->file = $value; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3582Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3582Test.php index 17b4bed85e4..d2ec7ae4825 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3582Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3582Test.php @@ -1,18 +1,24 @@ _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'); + assert($entity instanceof DDC3582Entity); $this->assertInstanceOf(DDC3582Embeddable1::class, $entity->embeddable1); $this->assertInstanceOf(DDC3582Embeddable2::class, $entity->embeddable1->embeddable2); @@ -31,7 +37,7 @@ class DDC3582Entity public function __construct($id) { - $this->id = $id; + $this->id = $id; $this->embeddable1 = new DDC3582Embeddable1(); } } @@ -42,7 +48,10 @@ class DDC3582Embeddable1 /** @Embedded(class="DDC3582Embeddable2") @var DDC3582Embeddable2 */ public $embeddable2; - public function __construct() { $this->embeddable2 = new DDC3582Embeddable2(); } + public function __construct() + { + $this->embeddable2 = new DDC3582Embeddable2(); + } } /** @Embeddable */ @@ -51,7 +60,10 @@ class DDC3582Embeddable2 /** @Embedded(class="DDC3582Embeddable3") @var DDC3582Embeddable3 */ public $embeddable3; - public function __construct() { $this->embeddable3 = new DDC3582Embeddable3(); } + public function __construct() + { + $this->embeddable3 = new DDC3582Embeddable3(); + } } /** @Embeddable */ diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3597Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3597Test.php index 736f29d934d..41334f3f573 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->_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), ] ); } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3634Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3634Test.php index 2dccf237b31..b42af6f62ee 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3634Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3634Test.php @@ -1,25 +1,33 @@ _em->getClassMetadata(DDC3634Entity::class); - if ( ! $metadata->idGenerator->isPostInsertGenerator()) { + if (! $metadata->idGenerator->isPostInsertGenerator()) { $this->markTestSkipped('Need a post-insert ID generator in order to make this test work correctly'); } @@ -34,7 +42,7 @@ protected function setUp() : void } } - public function testSavesVeryLargeIntegerAutoGeneratedValue() + public function testSavesVeryLargeIntegerAutoGeneratedValue(): void { $veryLargeId = PHP_INT_MAX . PHP_INT_MAX; @@ -51,7 +59,7 @@ public function testSavesVeryLargeIntegerAutoGeneratedValue() $this->assertSame($veryLargeId, $entity->id); } - public function testSavesIntegerAutoGeneratedValueAsString() + public function testSavesIntegerAutoGeneratedValueAsString(): void { $entity = new DDC3634Entity(); @@ -61,7 +69,7 @@ public function testSavesIntegerAutoGeneratedValueAsString() $this->assertIsString($entity->id); } - public function testSavesIntegerAutoGeneratedValueAsStringWithJoinedInheritance() + public function testSavesIntegerAutoGeneratedValueAsStringWithJoinedInheritance(): void { $entity = new DDC3634JTIChildEntity(); @@ -100,21 +108,13 @@ class DDC3634JTIChildEntity extends DDC3634JTIBaseEntity class DDC3634LastInsertIdMockingConnection extends Connection { - /** - * @var Connection - */ + /** @var Connection */ private $realConnection; - /** - * @var int - */ + /** @var int */ private $identifier; - /** - * @param int $identifier - * @param Connection $realConnection - */ - public function __construct($identifier, Connection $realConnection) + public function __construct(int $identifier, Connection $realConnection) { $this->realConnection = $realConnection; $this->identifier = $identifier; @@ -277,7 +277,7 @@ public function prepare($statement) return $this->forwardCall(); } - public function executeQuery($query, array $params = [], $types = [], QueryCacheProfile $qcp = null) + public function executeQuery($query, array $params = [], $types = [], ?QueryCacheProfile $qcp = null) { return $this->forwardCall(); } @@ -287,7 +287,7 @@ public function executeCacheQuery($query, $params, $types, QueryCacheProfile $qc return $this->forwardCall(); } - public function project($query, array $params, \Closure $function) + public function project($query, array $params, Closure $function) { return $this->forwardCall(); } @@ -327,7 +327,7 @@ public function lastInsertId($seqName = null) return $this->identifier; } - public function transactional(\Closure $func) + public function transactional(Closure $func) { return $this->forwardCall(); } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3644Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3644Test.php index 6c667664835..c4e835c4578 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3644Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3644Test.php @@ -1,5 +1,7 @@ setUpEntitySchema( [ - DDC3644User::class, - DDC3644Address::class, - DDC3644Animal::class, - DDC3644Pet::class, + DDC3644User::class, + DDC3644Address::class, + DDC3644Animal::class, + DDC3644Pet::class, ] ); } @@ -29,7 +31,7 @@ protected function setUp() : void /** * @group DDC-3644 */ - public function testIssueWithRegularEntity() + public function testIssueWithRegularEntity(): void { // Define initial dataset $current = new DDC3644Address('Sao Paulo, SP, Brazil'); @@ -81,7 +83,7 @@ public function testIssueWithRegularEntity() /** * @group DDC-3644 */ - public function testIssueWithJoinedEntity() + public function testIssueWithJoinedEntity(): void { // Define initial dataset $actual = new DDC3644Pet('Catharina'); @@ -141,39 +143,33 @@ class DDC3644User */ public $id; - /** - * @Column(type="string") - */ + /** @Column(type="string") */ public $name; - /** - * @OneToMany(targetEntity="DDC3644Address", mappedBy="user", orphanRemoval=true) - */ + /** @OneToMany(targetEntity="DDC3644Address", mappedBy="user", orphanRemoval=true) */ public $addresses = []; - /** - * @OneToMany(targetEntity="DDC3644Pet", mappedBy="owner", orphanRemoval=true) - */ + /** @OneToMany(targetEntity="DDC3644Pet", mappedBy="owner", orphanRemoval=true) */ public $pets = []; - public function setAddresses(Collection $addresses) + public function setAddresses(Collection $addresses): void { $self = $this; $this->addresses = $addresses; - $addresses->map(function ($address) use ($self) { + $addresses->map(static function ($address) use ($self): void { $address->user = $self; }); } - public function setPets(Collection $pets) + public function setPets(Collection $pets): void { $self = $this; $this->pets = $pets; - $pets->map(function ($pet) use ($self) { + $pets->map(static function ($pet) use ($self): void { $pet->owner = $self; }); } @@ -197,9 +193,7 @@ class DDC3644Address */ public $user; - /** - * @Column(type="string") - */ + /** @Column(type="string") */ public $address; public function __construct($address) @@ -223,9 +217,7 @@ abstract class DDC3644Animal */ public $id; - /** - * @Column(type="string") - */ + /** @Column(type="string") */ public $name; public function __construct($name) diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3699Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3699Test.php index f36c19254ed..b6bcca11fe0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3699Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3699Test.php @@ -1,18 +1,21 @@ useModelSet('ddc3699'); @@ -20,7 +23,7 @@ protected function setUp() : void } /** @after */ - public function ensureTestGeneratedDeprecationMessages() : void + public function ensureTestGeneratedDeprecationMessages(): void { $this->assertHasDeprecationMessages(); } @@ -28,7 +31,7 @@ public function ensureTestGeneratedDeprecationMessages() : void /** * @group DDC-3699 */ - public function testMergingParentClassFieldsDoesNotStopMergingScalarFieldsForToOneUninitializedAssociations() + public function testMergingParentClassFieldsDoesNotStopMergingScalarFieldsForToOneUninitializedAssociations(): void { $id = 1; @@ -41,7 +44,7 @@ public function testMergingParentClassFieldsDoesNotStopMergingScalarFieldsForToO $relation = new DDC3699RelationOne(); $relation->id = $id; - $relation->child = $child ; + $relation->child = $child; $child->oneRelation = $relation; $this->_em->persist($relation); @@ -49,9 +52,8 @@ public function testMergingParentClassFieldsDoesNotStopMergingScalarFieldsForToO $this->_em->flush(); $this->_em->clear(); - // fixtures loaded - /* @var $unManagedChild DDC3699Child */ $unManagedChild = $this->_em->find(DDC3699Child::class, $id); + assert($unManagedChild instanceof DDC3699Child); $this->_em->detach($unManagedChild); @@ -61,8 +63,8 @@ public function testMergingParentClassFieldsDoesNotStopMergingScalarFieldsForToO $unManagedChild->childField = 'modifiedChildValue'; $unManagedChild->parentField = 'modifiedParentValue'; - /* @var $mergedChild DDC3699Child */ $mergedChild = $this->_em->merge($unManagedChild); + assert($mergedChild instanceof DDC3699Child); $this->assertSame($mergedChild->childField, 'modifiedChildValue'); $this->assertSame($mergedChild->parentField, 'modifiedParentValue'); @@ -71,7 +73,7 @@ public function testMergingParentClassFieldsDoesNotStopMergingScalarFieldsForToO /** * @group DDC-3699 */ - public function testMergingParentClassFieldsDoesNotStopMergingScalarFieldsForToManyUninitializedAssociations() + public function testMergingParentClassFieldsDoesNotStopMergingScalarFieldsForToManyUninitializedAssociations(): void { $id = 2; @@ -84,7 +86,7 @@ public function testMergingParentClassFieldsDoesNotStopMergingScalarFieldsForToM $relation = new DDC3699RelationMany(); $relation->id = $id; - $relation->child = $child ; + $relation->child = $child; $child->relations[] = $relation; $this->_em->persist($relation); @@ -92,8 +94,8 @@ public function testMergingParentClassFieldsDoesNotStopMergingScalarFieldsForToM $this->_em->flush(); $this->_em->clear(); - /* @var $unmanagedChild DDC3699Child */ $unmanagedChild = $this->_em->find(DDC3699Child::class, $id); + assert($unmanagedChild instanceof DDC3699Child); $this->_em->detach($unmanagedChild); // make it managed again @@ -102,8 +104,8 @@ public function testMergingParentClassFieldsDoesNotStopMergingScalarFieldsForToM $unmanagedChild->childField = 'modifiedChildValue'; $unmanagedChild->parentField = 'modifiedParentValue'; - /* @var $mergedChild DDC3699Child */ $mergedChild = $this->_em->merge($unmanagedChild); + assert($mergedChild instanceof DDC3699Child); $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 index dc633c7aa88..2c9de67c9a4 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3711Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3711Test.php @@ -1,34 +1,33 @@ - */ class DDC3711Test extends YamlMappingDriverTest { use VerifyDeprecations; - public function testCompositeKeyForJoinTableInManyToManyCreation() + public function testCompositeKeyForJoinTableInManyToManyCreation(): void { $yamlDriver = $this->_loadDriver(); $em = $this->_getTestEntityManager(); $em->getConfiguration()->setMetadataDriverImpl($yamlDriver); - $factory = new \Doctrine\ORM\Mapping\ClassMetadataFactory(); + $factory = new 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']); + $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']); $this->assertHasDeprecationMessages(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3719Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3719Test.php index 803367b8d83..dbaf68e42af 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3719Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3719Test.php @@ -1,18 +1,17 @@ - */ -class DDC3719Test extends \Doctrine\Tests\OrmFunctionalTestCase +class DDC3719Test extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { $this->useModelSet('company'); parent::setUp(); @@ -21,7 +20,7 @@ protected function setUp() : void /** * @group DDC-3719 */ - public function testCriteriaOnNotOwningSide() + public function testCriteriaOnNotOwningSide(): void { $manager = new CompanyManager(); $manager->setName('Gandalf'); @@ -46,7 +45,7 @@ public function testCriteriaOnNotOwningSide() static::assertCount(2, $contracts); $criteria = Criteria::create(); - $criteria->where(Criteria::expr()->eq("completed", true)); + $criteria->where(Criteria::expr()->eq('completed', true)); $completedContracts = $contracts->matching($criteria); static::assertCount(1, $completedContracts); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC371Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC371Test.php index d306676629a..999dcbd14d4 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC371Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC371Test.php @@ -1,33 +1,40 @@ _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), ] ); } - public function testIssue() + public function testIssue(): void { - $parent = new DDC371Parent; - $parent->data = 'parent'; - $parent->children = new \Doctrine\Common\Collections\ArrayCollection; + $parent = new DDC371Parent(); + $parent->data = 'parent'; + $parent->children = new ArrayCollection(); - $child = new DDC371Child; + $child = new DDC371Child(); $child->data = 'child'; $child->parent = $parent; @@ -39,7 +46,7 @@ public function testIssue() $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(); @@ -52,7 +59,8 @@ public function testIssue() } /** @Entity */ -class DDC371Child { +class DDC371Child +{ /** @Id @Column(type="integer") @GeneratedValue */ private $id; /** @Column(type="string") */ @@ -62,7 +70,8 @@ class DDC371Child { } /** @Entity */ -class DDC371Parent { +class DDC371Parent +{ /** @Id @Column(type="integer") @GeneratedValue */ private $id; /** @Column(type="string") */ @@ -70,4 +79,3 @@ class DDC371Parent { /** @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 6b1dd59fb54..cb11361347f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3785Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3785Test.php @@ -1,14 +1,18 @@ _em->getClassMetadata(DDC3785_Asset::class), $this->_em->getClassMetadata(DDC3785_AssetId::class), - $this->_em->getClassMetadata(DDC3785_Attribute::class) + $this->_em->getClassMetadata(DDC3785_Attribute::class), ] ); - } catch(\Exception $e) { + } catch (Exception $e) { } } /** * @group DDC-3785 */ - public function testOwningValueObjectIdIsCorrectlyTransformedWhenRemovingOrphanedChildEntities() + public function testOwningValueObjectIdIsCorrectlyTransformedWhenRemovingOrphanedChildEntities(): void { $id = new DDC3785_AssetId('919609ba-57d9-4a13-be1d-d202521e858a'); $attributes = [ $attribute1 = new DDC3785_Attribute('foo1', 'bar1'), - $attribute2 = new DDC3785_Attribute('foo2', 'bar2') + $attribute2 = new DDC3785_Attribute('foo2', 'bar2'), ]; $this->_em->persist($asset = new DDC3785_Asset($id, $attributes)); @@ -60,9 +64,7 @@ public function testOwningValueObjectIdIsCorrectlyTransformedWhenRemovingOrphane */ class DDC3785_Asset { - /** - * @Id @GeneratedValue(strategy="NONE") @Column(type="ddc3785_asset_id") - */ + /** @Id @GeneratedValue(strategy="NONE") @Column(type="ddc3785_asset_id") */ private $id; /** @@ -76,7 +78,7 @@ class DDC3785_Asset public function __construct(DDC3785_AssetId $id, $attributes = []) { - $this->id = $id; + $this->id = $id; $this->attributes = new ArrayCollection(); foreach ($attributes as $attribute) { @@ -115,7 +117,7 @@ class DDC3785_Attribute public function __construct($name, $value) { - $this->name = $name; + $this->name = $name; $this->value = $value; } } @@ -152,7 +154,7 @@ public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $pla */ public function convertToDatabaseValue($value, AbstractPlatform $platform) { - return (string)$value; + return (string) $value; } /** diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC381Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC381Test.php index 4bfe606529f..5e68818f3a7 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC381Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC381Test.php @@ -1,25 +1,32 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC381Entity::class), + $this->_em->getClassMetadata(DDC381Entity::class), ] ); - } catch(\Exception $e) { - + } catch (Exception $e) { } } - public function testCallUnserializedProxyMethods() + public function testCallUnserializedProxyMethods(): void { $entity = new DDC381Entity(); @@ -33,7 +40,7 @@ public function testCallUnserializedProxyMethods() // explicitly load proxy (getId() does not trigger reload of proxy) $id = $entity->getOtherMethod(); - $data = serialize($entity); + $data = serialize($entity); $entity = unserialize($data); $this->assertEquals($persistedId, $entity->getId()); @@ -45,9 +52,7 @@ public function testCallUnserializedProxyMethods() */ class DDC381Entity { - /** - * @Id @Column(type="integer") @GeneratedValue - */ + /** @Id @Column(type="integer") @GeneratedValue */ protected $id; public function getId() @@ -55,8 +60,7 @@ public function getId() return $this->id; } - public function getOtherMethod() + public function getOtherMethod(): void { - } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3967Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3967Test.php index 36dc82250c4..8fb691fc694 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3967Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3967Test.php @@ -1,13 +1,18 @@ _em->clear(); } - public function testIdentifierCachedWithProperType() + public function testIdentifierCachedWithProperType(): void { $country = array_pop($this->countries); - $id = $country->getId(); + $id = $country->getId(); // First time, loaded from database $this->_em->find(Country::class, "$id"); $this->_em->clear(); - // Second time, loaded from cache - /** @var Country $country */ $country = $this->_em->find(Country::class, "$id"); + assert($country instanceof Country); // Identifier type should be integer $this->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..914aaa7fc15 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC4003Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC4003Test.php @@ -1,13 +1,18 @@ loadFixturesCountries(); $this->loadFixturesStates(); @@ -23,10 +28,9 @@ public function test_reads_through_repository_same_data_that_it_wrote_in_cache() * This instance is fresh new, no QueryCache, so the full entity gets loaded from DB. * It will be saved in the WRONG KEY (notice the cache.bar at the end): * doctrine_tests_models_cache_attraction[doctrine_tests_models_cache_attraction_doctrine.tests.models.cache.bar_1][1] - * - * @var Bar $bar */ $bar = $repository->findOneBy(['id' => $id]); + assert($bar instanceof Bar); // Let's change it so that we can compare its state $bar->setName($newName = uniqid()); @@ -51,10 +55,9 @@ public function test_reads_through_repository_same_data_that_it_wrote_in_cache() * Right now QueryCache will HIT, as nothing changed between the last one and now. * QueryCache holds a reference to the WRONG KEY, as we saw was formed in line 24 of this test. * So this instance won't be updated and will have the original name ("Boteco São Bento"), and not the uniqid(). - * - * @var Bar $cached */ $cached = $repository->findOneBy(['id' => $id]); + assert($cached instanceof Bar); $this->assertEquals($newName, $cached->getName()); } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC4024Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC4024Test.php index fa1208292bc..60e622285c2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC4024Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC4024Test.php @@ -1,22 +1,25 @@ getMessage()); } - public function testADefaultMessageShouldBeUsedWhenNothingWasProvided() : void + public function testADefaultMessageShouldBeUsedWhenNothingWasProvided(): void { $exception = new NonUniqueResultException(); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC422Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC422Test.php index dc4b31669e7..0cf98532e78 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC422Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC422Test.php @@ -1,20 +1,26 @@ _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), ] ); } @@ -22,9 +28,9 @@ protected function setUp() : void /** * @group DDC-422 */ - public function testIssue() + public function testIssue(): void { - $customer = new DDC422Customer; + $customer = new DDC422Customer(); $this->_em->persist($customer); $this->_em->flush(); $this->_em->clear(); @@ -33,13 +39,13 @@ public function testIssue() $this->assertInstanceOf(PersistentCollection::class, $customer->contacts); $this->assertFalse($customer->contacts->isInitialized()); - $contact = new DDC422Contact; + $contact = new DDC422Contact(); $customer->contacts->add($contact); $this->assertTrue($customer->contacts->isDirty()); $this->assertFalse($customer->contacts->isInitialized()); $this->_em->flush(); - $this->assertEquals(1, $this->_em->getConnection()->fetchColumn("select count(*) from ddc422_customers_contacts")); + $this->assertEquals(1, $this->_em->getConnection()->fetchColumn('select count(*) from ddc422_customers_contacts')); } } @@ -49,13 +55,15 @@ public function testIssue() * @DiscriminatorColumn(name="discr", type="string") * @DiscriminatorMap({"guest" = "DDC422Guest", "customer" = "DDC422Customer"}) */ -class DDC422Guest { +class DDC422Guest +{ /** @Id @Column(type="integer") @GeneratedValue */ public $id; } /** @Entity */ -class DDC422Customer extends DDC422Guest { +class DDC422Customer extends DDC422Guest +{ /** * @ManyToMany(targetEntity="DDC422Contact", cascade={"persist","remove"}) * @JoinTable(name="ddc422_customers_contacts", @@ -65,14 +73,15 @@ class DDC422Customer extends DDC422Guest { */ public $contacts; - public function __construct() { - $this->contacts = new \Doctrine\Common\Collections\ArrayCollection; + public function __construct() + { + $this->contacts = new ArrayCollection(); } } /** @Entity */ -class DDC422Contact { +class DDC422Contact +{ /** @Id @Column(type="integer") @GeneratedValue */ public $id; } - diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC425Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC425Test.php index 9c5ea5cda69..b0f4b64c737 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->_em->getClassMetadata(DDC425Entity::class), + $this->_em->getClassMetadata(DDC425Entity::class), ] ); } @@ -18,19 +22,20 @@ protected function setUp() : void /** * @group DDC-425 */ - public function testIssue() + public function testIssue(): void { //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $num = $this->_em->createQuery('DELETE '.__NAMESPACE__.'\DDC425Entity e WHERE e.someDatetimeField > ?1') - ->setParameter(1, new DateTime, Type::DATETIME) + $num = $this->_em->createQuery('DELETE ' . __NAMESPACE__ . '\DDC425Entity e WHERE e.someDatetimeField > ?1') + ->setParameter(1, new DateTime(), Type::DATETIME) ->getResult(); $this->assertEquals(0, $num); } } /** @Entity */ -class DDC425Entity { +class DDC425Entity +{ /** * @Id @Column(type="integer") * @GeneratedValue diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC440Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC440Test.php index aff0b0567e3..5771f5f6885 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC440Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC440Test.php @@ -1,20 +1,25 @@ _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) { + } catch (Exception $e) { // Swallow all exceptions. We do not test the schema tool here. } } @@ -22,10 +27,8 @@ protected function setUp() : void /** * @group DDC-440 */ - public function testOriginalEntityDataEmptyWhenProxyLoadedFromTwoAssociations() + public function testOriginalEntityDataEmptyWhenProxyLoadedFromTwoAssociations(): void { - - /* 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) @@ -36,15 +39,15 @@ public function testOriginalEntityDataEmptyWhenProxyLoadedFromTwoAssociations() */ //Initialize some data - $client = new DDC440Client; + $client = new DDC440Client(); $client->setName('Client1'); - $phone = new DDC440Phone; + $phone = new DDC440Phone(); $phone->setId(1); $phone->setNumber('418 111-1111'); $phone->setClient($client); - $phone2 = new DDC440Phone; + $phone2 = new DDC440Phone(); $phone->setId(2); $phone2->setNumber('418 222-2222'); $phone2->setClient($client); @@ -56,8 +59,8 @@ public function testOriginalEntityDataEmptyWhenProxyLoadedFromTwoAssociations() $id = $client->getId(); $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]; @@ -70,13 +73,11 @@ public function testOriginalEntityDataEmptyWhenProxyLoadedFromTwoAssociations() $originalData = $uw->getOriginalEntityData($p1); $this->assertEquals($phone->getNumber(), $originalData['number']); - //If you comment out previous test, this one should pass $this->assertInstanceOf(DDC440Phone::class, $p2); $originalData = $uw->getOriginalEntityData($p2); $this->assertEquals($phone2->getNumber(), $originalData['number']); } - } /** @@ -85,7 +86,6 @@ public function testOriginalEntityDataEmptyWhenProxyLoadedFromTwoAssociations() */ class DDC440Phone { - /** * @Column(name="id", type="integer") * @Id @@ -99,12 +99,10 @@ class DDC440Phone * }) */ protected $client; - /** - * @Column(name="phonenumber", type="string") - */ + /** @Column(name="phonenumber", type="string") */ protected $number; - public function setNumber($value) + public function setNumber($value): void { $this->number = $value; } @@ -114,7 +112,7 @@ public function getNumber() return $this->number; } - public function setClient(DDC440Client $value, $update_inverse=true) + public function setClient(DDC440Client $value, $update_inverse = true): void { $this->client = $value; if ($update_inverse) { @@ -132,11 +130,10 @@ public function getId() return $this->id; } - public function setId($value) + public function setId($value): void { $this->id = $value; } - } /** @@ -145,7 +142,6 @@ public function setId($value) */ class DDC440Client { - /** * @Column(name="id", type="integer") * @Id @@ -164,17 +160,14 @@ class DDC440Client * @OrderBy({"number"="ASC"}) */ protected $phones; - /** - * @Column(name="name", type="string") - */ + /** @Column(name="name", type="string") */ protected $name; public function __construct() { - } - public function setName($value) + public function setName($value): void { $this->name = $value; } @@ -184,7 +177,7 @@ public function getName() return $this->name; } - public function addPhone(DDC440Phone $value) + public function addPhone(DDC440Phone $value): void { $this->phones[] = $value; $value->setClient($this, false); @@ -195,7 +188,7 @@ public function getPhones() return $this->phones; } - public function setMainPhone(DDC440Phone $value) + public function setMainPhone(DDC440Phone $value): void { $this->main_phone = $value; } @@ -210,9 +203,8 @@ public function getId() return $this->id; } - public function setId($value) + public function setId($value): void { $this->id = $value; } - } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC444Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC444Test.php index 9607d22de72..f2f72adbd5c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC444Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC444Test.php @@ -1,26 +1,30 @@ _em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); $this->_schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC444User::class), + $this->_em->getClassMetadata(DDC444User::class), ] ); } - public function testExplicitPolicy() + public function testExplicitPolicy(): void { $classname = DDC444User::class; - $u = new $classname; - $u->name = "Initial value"; + $u = new $classname(); + $u->name = 'Initial value'; $this->_em->persist($u); $this->_em->flush(); @@ -28,22 +32,20 @@ public function testExplicitPolicy() $q = $this->_em->createQuery("SELECT u FROM $classname u"); $u = $q->getSingleResult(); - $this->assertEquals("Initial value", $u->name); + $this->assertEquals('Initial value', $u->name); - $u->name = "Modified value"; + $u->name = 'Modified value'; // This should be NOOP as the change hasn't been persisted $this->_em->flush(); $this->_em->clear(); - $u = $this->_em->createQuery("SELECT u FROM $classname u"); $u = $q->getSingleResult(); - $this->assertEquals("Initial value", $u->name); + $this->assertEquals('Initial value', $u->name); - - $u->name = "Modified value"; + $u->name = 'Modified value'; $this->_em->persist($u); // Now we however persisted it, and this should have updated our friend $this->_em->flush(); @@ -51,7 +53,7 @@ public function testExplicitPolicy() $q = $this->_em->createQuery("SELECT u FROM $classname u"); $u = $q->getSingleResult(); - $this->assertEquals("Modified value", $u->name); + $this->assertEquals('Modified value', $u->name); } } @@ -68,8 +70,6 @@ class DDC444User */ public $id; - /** - * @Column(name="name", type="string") - */ + /** @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 7d0ddd3b57e..b5d8d4dd371 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC448Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC448Test.php @@ -1,26 +1,30 @@ _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() + public function testIssue(): void { - $q = $this->_em->createQuery("select b from ".__NAMESPACE__."\\DDC448SubTable b where b.connectedClassId = ?1"); + $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()) diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC493Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC493Test.php index 4fa82abccf6..b4e1bef14fc 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC493Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC493Test.php @@ -1,24 +1,30 @@ _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() + public function testIssue(): void { - $q = $this->_em->createQuery("select u, c.data from ".__NAMESPACE__."\\DDC493Distributor u JOIN u.contact c"); + $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()) @@ -32,7 +38,8 @@ public function testIssue() * @DiscriminatorColumn(name="discr", type="string") * @DiscriminatorMap({"distributor" = "DDC493Distributor", "customer" = "DDC493Customer"}) */ -class DDC493Customer { +class DDC493Customer +{ /** * @Id * @Column(type="integer") @@ -44,18 +51,18 @@ class DDC493Customer { * @JoinColumn(name="contact", referencedColumnName="id") */ public $contact; - } /** * @Entity */ -class DDC493Distributor extends DDC493Customer { +class DDC493Distributor extends DDC493Customer +{ } /** * @Entity - */ + */ class DDC493Contact { /** diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC501Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC501Test.php index 1aca0a39adf..86c7b03834f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC501Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC501Test.php @@ -1,12 +1,19 @@ useModelSet('cms'); parent::setUp(); } - public function testMergeUnitializedManyToManyAndOneToManyCollections() + public function testMergeUnitializedManyToManyAndOneToManyCollections(): void { // Create User $user = $this->createAndPersistUser(); @@ -53,17 +58,17 @@ public function testMergeUnitializedManyToManyAndOneToManyCollections() // 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."); + $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."); + $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. + // 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" @@ -88,19 +93,19 @@ public function testMergeUnitializedManyToManyAndOneToManyCollections() protected function createAndPersistUser() { - $user = new CmsUser(); - $user->name = 'Luka'; + $user = new CmsUser(); + $user->name = 'Luka'; $user->username = 'lukacho'; - $user->status = 'developer'; + $user->status = 'developer'; - foreach([1111,2222,3333,4444] as $number) { - $phone = new CmsPhonenumber; + foreach ([1111, 2222, 3333, 4444] as $number) { + $phone = new CmsPhonenumber(); $phone->phonenumber = $number; $user->addPhonenumber($phone); } - foreach(['Moshers', 'Headbangers'] as $groupName) { - $group = new CmsGroup; + foreach (['Moshers', 'Headbangers'] as $groupName) { + $group = new CmsGroup(); $group->setName($groupName); $user->addGroup($group); } @@ -110,15 +115,11 @@ protected function createAndPersistUser() return $user; } - /** - * @return Doctrine\Tests\Models\CMS\CmsUser - */ - protected function loadUserFromEntityManager() + protected function loadUserFromEntityManager(): Doctrine\Tests\Models\CMS\CmsUser { 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 9e4f80bfa10..0c133115bfc 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC512Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC512Test.php @@ -1,27 +1,31 @@ _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), ] ); } - public function testIssue() + public function testIssue(): void { - $customer1 = new DDC512Customer(); - $item = new DDC512OfferItem(); + $customer1 = new DDC512Customer(); + $item = new DDC512OfferItem(); $customer1->item = $item; $this->_em->persist($customer1); @@ -31,13 +35,13 @@ public function testIssue() $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]); - if ($result[0]->id == $customer1->id) { + 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); @@ -51,7 +55,8 @@ public function testIssue() /** * @Entity */ -class DDC512Customer { +class DDC512Customer +{ /** * @Id * @Column(type="integer") @@ -71,7 +76,7 @@ class DDC512Customer { /** * @Entity - */ + */ class DDC512OfferItem extends DDC512Item { } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC513Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC513Test.php index 13255382a0b..6bb34d95839 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC513Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC513Test.php @@ -1,24 +1,30 @@ _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() + public function testIssue(): void { - $q = $this->_em->createQuery("select u from ".__NAMESPACE__."\\DDC513OfferItem u left join u.price p"); + $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()) @@ -28,7 +34,7 @@ public function testIssue() /** * @Entity - */ + */ class DDC513OfferItem extends DDC513Item { } @@ -58,7 +64,8 @@ class DDC513Item /** * @Entity */ -class DDC513Price { +class DDC513Price +{ /** * @Id * @Column(type="integer") diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC518Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC518Test.php index 864c5eb3b6f..e2e1aa98000 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC518Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC518Test.php @@ -1,35 +1,40 @@ useModelSet('cms'); parent::setUp(); } - public function testMergeWithRelatedNew() + public function testMergeWithRelatedNew(): void { - $article = new \Doctrine\Tests\Models\CMS\CmsArticle(); - $article->text = "foo"; - $article->topic = "bar"; + $article = new 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; + $user = new CmsUser(); + $user->username = 'beberlei'; + $user->name = 'Benjamin Eberlei'; + $user->status = 'active'; + $article->user = $user; $this->_em->persist($user); $managedArticle = $this->_em->merge($article); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC522Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC522Test.php index 58e8a69145a..7f501f9654b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC522Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC522Test.php @@ -1,16 +1,22 @@ _em->getClassMetadata(DDC522Customer::class), $this->_em->getClassMetadata(DDC522Cart::class), - $this->_em->getClassMetadata(DDC522ForeignKeyTest::class) + $this->_em->getClassMetadata(DDC522ForeignKeyTest::class), ] ); - } catch(\Exception $e) { + } catch (Exception $e) { } } /** * @group DDC-522 */ - public function testJoinColumnWithSameNameAsAssociationField() + public function testJoinColumnWithSameNameAsAssociationField(): void { - $cust = new DDC522Customer; - $cust->name = "name"; - $cart = new DDC522Cart; - $cart->total = 0; - $cust->cart = $cart; + $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); @@ -51,9 +57,9 @@ public function testJoinColumnWithSameNameAsAssociationField() $this->assertNotInstanceOf(Proxy::class, $r[0]->customer); $this->assertEquals('name', $r[0]->customer->name); - $fkt = new DDC522ForeignKeyTest(); + $fkt = new DDC522ForeignKeyTest(); $fkt->cartId = $r[0]->id; // ignored for persistence - $fkt->cart = $r[0]; // must be set properly + $fkt->cart = $r[0]; // must be set properly $this->_em->persist($fkt); $this->_em->flush(); $this->_em->clear(); @@ -68,9 +74,9 @@ public function testJoinColumnWithSameNameAsAssociationField() * @group DDC-522 * @group DDC-762 */ - public function testJoinColumnWithNullSameNameAssociationField() + public function testJoinColumnWithNullSameNameAssociationField(): void { - $fkCust = new DDC522ForeignKeyTest; + $fkCust = new DDC522ForeignKeyTest(); $fkCust->name = 'name'; $fkCust->cart = null; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC531Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC531Test.php index 77ea2024bf4..63e60433a23 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC531Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC531Test.php @@ -1,26 +1,30 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC531Item::class), - $this->_em->getClassMetadata(DDC531SubItem::class), + $this->_em->getClassMetadata(DDC531Item::class), + $this->_em->getClassMetadata(DDC531SubItem::class), ] ); } - public function testIssue() + public function testIssue(): void { - $item1 = new DDC531Item; - $item2 = new DDC531Item; + $item1 = new DDC531Item(); + $item2 = new DDC531Item(); $item2->parent = $item1; $item1->getChildren()->add($item2); $this->_em->persist($item1); @@ -55,9 +59,7 @@ class DDC531Item */ public $id; - /** - * @OneToMany(targetEntity="DDC531Item", mappedBy="parent") - */ + /** @OneToMany(targetEntity="DDC531Item", mappedBy="parent") */ protected $children; /** @@ -68,7 +70,7 @@ class DDC531Item public function __construct() { - $this->children = new \Doctrine\Common\Collections\ArrayCollection; + $this->children = new ArrayCollection(); } public function getParent() diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC5684Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC5684Test.php index 5b14cd06860..f0b42660bcd 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)]); } - protected function tearDown() : void + protected function tearDown(): void { $this->_schemaTool->dropSchema([$this->_em->getClassMetadata(DDC5684Object::class)]); parent::tearDown(); } - public function testAutoIncrementIdWithCustomType() + public function testAutoIncrementIdWithCustomType(): void { $object = new DDC5684Object(); $this->_em->persist($object); @@ -43,14 +46,14 @@ public function testAutoIncrementIdWithCustomType() $this->assertInstanceOf(DDC5684ObjectId::class, $object->id); } - public function testFetchObjectWithAutoIncrementedCustomType() + public function testFetchObjectWithAutoIncrementedCustomType(): void { $object = new DDC5684Object(); $this->_em->persist($object); $this->_em->flush(); $this->_em->clear(); - $rawId = $object->id->value; + $rawId = $object->id->value; $object = $this->_em->find(DDC5684Object::class, new DDC5684ObjectId($rawId)); $this->assertInstanceOf(DDC5684ObjectId::class, $object->id); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC588Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC588Test.php index cbd895c3d0d..5ef558a8aea 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC588Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC588Test.php @@ -1,10 +1,14 @@ _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->_em->getClassMetadata(DDC599Item::class), + $this->_em->getClassMetadata(DDC599Subitem::class), + $this->_em->getClassMetadata(DDC599Child::class), ] ); - } catch (\Exception $ignored) {} + } catch (Exception $ignored) { + } } - public function testCascadeRemoveOnInheritanceHierarchy() + public function testCascadeRemoveOnInheritanceHierarchy(): void { - $item = new DDC599Subitem; - $item->elem = "foo"; - $child = new DDC599Child; + $item = new DDC599Subitem(); + $item->elem = 'foo'; + $child = new DDC599Child(); $child->parent = $item; $item->getChildren()->add($child); $this->_em->persist($item); @@ -42,13 +49,12 @@ public function testCascadeRemoveOnInheritanceHierarchy() $this->_em->clear(); - - $item2 = new DDC599Subitem; - $item2->elem = "bar"; + $item2 = new DDC599Subitem(); + $item2->elem = 'bar'; $this->_em->persist($item2); $this->_em->flush(); - $child2 = new DDC599Child; + $child2 = new DDC599Child(); $child2->parent = $item2; $item2->getChildren()->add($child2); $this->_em->persist($child2); @@ -62,7 +68,7 @@ public function testCascadeRemoveOnInheritanceHierarchy() $this->assertFalse($this->_em->contains($children[0])); } - public function testCascadeRemoveOnChildren() + public function testCascadeRemoveOnChildren(): void { $class = $this->_em->getClassMetadata(DDC599Subitem::class); @@ -86,14 +92,12 @@ class DDC599Item */ public $id; - /** - * @OneToMany(targetEntity="DDC599Child", mappedBy="parent", cascade={"remove"}) - */ + /** @OneToMany(targetEntity="DDC599Child", mappedBy="parent", cascade={"remove"}) */ protected $children; public function __construct() { - $this->children = new \Doctrine\Common\Collections\ArrayCollection; + $this->children = new ArrayCollection(); } public function getChildren() @@ -107,9 +111,7 @@ public function getChildren() */ class DDC599Subitem extends DDC599Item { - /** - * @Column(type="string") - */ + /** @Column(type="string") */ public $elem; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC618Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC618Test.php index 44daf38e5fb..eab4beb0524 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC618Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC618Test.php @@ -1,32 +1,41 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC618Author::class), - $this->_em->getClassMetadata(DDC618Book::class) + $this->_em->getClassMetadata(DDC618Author::class), + $this->_em->getClassMetadata(DDC618Book::class), ] ); // Create author 10/Joe with two books 22/JoeA and 20/JoeB - $author = new DDC618Author(); - $author->id = 10; + $author = new DDC618Author(); + $author->id = 10; $author->name = 'Joe'; $this->_em->persist($author); // Create author 11/Alice with two books 21/AliceA and 23/AliceB - $author = new DDC618Author(); - $author->id = 11; + $author = new DDC618Author(); + $author->id = 11; $author->name = 'Alice'; $author->addBook('In Wonderland'); $author->addBook('Reloaded'); @@ -36,30 +45,29 @@ protected function setUp() : void $this->_em->flush(); $this->_em->clear(); - } catch(\Exception $e) { - + } catch (Exception $e) { } } - public function testIndexByHydrateObject() + public function testIndexByHydrateObject(): void { - $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); + $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(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'."); } - public function testIndexByHydrateArray() + public function testIndexByHydrateArray(): void { - $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); + $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(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'."); @@ -68,62 +76,62 @@ public function testIndexByHydrateArray() /** * @group DDC-1018 */ - public function testIndexByJoin() + public function testIndexByJoin(): void { - $dql = 'SELECT A, B FROM Doctrine\Tests\ORM\Functional\Ticket\DDC618Author A '. + $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(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."); + $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.'); - $result = $this->_em->createQuery($dql)->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY); + $result = $this->_em->createQuery($dql)->getResult(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."); + $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.'); } /** * @group DDC-1018 */ - public function testIndexByToOneJoinSilentlyIgnored() + public function testIndexByToOneJoinSilentlyIgnored(): void { - $dql = 'SELECT B, A FROM Doctrine\Tests\ORM\Functional\Ticket\DDC618Book B '. + $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(Query::HYDRATE_OBJECT); $this->assertInstanceOf(DDC618Book::class, $result[0]); $this->assertInstanceOf(DDC618Author::class, $result[0]->author); - $dql = 'SELECT B, A FROM Doctrine\Tests\ORM\Functional\Ticket\DDC618Book B '. + $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(Query::HYDRATE_ARRAY); - $this->assertEquals("Alice", $result[0]['author']['name']); + $this->assertEquals('Alice', $result[0]['author']['name']); } /** * @group DDC-1018 */ - public function testCombineIndexBy() + public function testCombineIndexBy(): void { - $dql = 'SELECT A, B FROM Doctrine\Tests\ORM\Functional\Ticket\DDC618Author A INDEX BY A.id '. + $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(Query::HYDRATE_OBJECT); $this->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."); + $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.'); } } @@ -141,19 +149,17 @@ class DDC618Author /** @Column(type="string") */ public $name; - /** - * @OneToMany(targetEntity="DDC618Book", mappedBy="author", cascade={"persist"}) - */ + /** @OneToMany(targetEntity="DDC618Book", mappedBy="author", cascade={"persist"}) */ public $books; public function __construct() { - $this->books = new \Doctrine\Common\Collections\ArrayCollection; + $this->books = new ArrayCollection(); } - public function addBook($title) + public function addBook($title): void { - $book = new DDC618Book($title, $this); + $book = new DDC618Book($title, $this); $this->books[] = $book; } } @@ -177,7 +183,7 @@ class DDC618Book function __construct($title, $author) { - $this->title = $title; + $this->title = $title; $this->author = $author; } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC6303Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC6303Test.php index 432cc7ec346..3fb2a327f37 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC6303Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC6303Test.php @@ -1,18 +1,25 @@ new DDC6303ChildA('a', 'authorized'), 'b' => new DDC6303ChildB('b', ['accepted', 'authorized']), ]); - } - public function testEmptyValuesInJoinedInheritance() : void + public function testEmptyValuesInJoinedInheritance(): void { $this->assertHydratedEntitiesSameToPersistedOnes([ 'stringEmpty' => new DDC6303ChildA('stringEmpty', ''), @@ -51,16 +57,16 @@ public function testEmptyValuesInJoinedInheritance() : void * @param DDC6303BaseClass[] $persistedEntities indexed by identifier * * @throws MappingException - * @throws \Doctrine\ORM\ORMException - * @throws \Doctrine\ORM\OptimisticLockException + * @throws ORMException + * @throws OptimisticLockException */ - private function assertHydratedEntitiesSameToPersistedOnes(array $persistedEntities) : void + private function assertHydratedEntitiesSameToPersistedOnes(array $persistedEntities): void { array_walk($persistedEntities, [$this->_em, 'persist']); $this->_em->flush(); $this->_em->clear(); - /* @var $entities DDC6303BaseClass[] */ + /** @var DDC6303BaseClass[] $entities */ $entities = $this ->_em ->getRepository(DDC6303BaseClass::class) diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC633Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC633Test.php index a5facde97b5..1e8160fdd84 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC633Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC633Test.php @@ -1,23 +1,26 @@ _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) { - + } catch (Exception $e) { } } @@ -26,11 +29,11 @@ protected function setUp() : void * @group DDC-952 * @group DDC-914 */ - public function testOneToOneEager() + public function testOneToOneEager(): void { - $app = new DDC633Appointment(); - $pat = new DDC633Patient(); - $app->patient = $pat; + $app = new DDC633Appointment(); + $pat = new DDC633Patient(); + $app->patient = $pat; $pat->appointment = $app; $this->_em->persist($app); @@ -49,25 +52,26 @@ public function testOneToOneEager() * @group DDC-633 * @group DDC-952 */ - public function testDQLDeferredEagerLoad() + public function testDQLDeferredEagerLoad(): void { for ($i = 0; $i < 10; $i++) { - $app = new DDC633Appointment(); - $pat = new DDC633Patient(); - $app->patient = $pat; + $app = new DDC633Appointment(); + $pat = new DDC633Patient(); + $app->patient = $pat; $pat->appointment = $app; $this->_em->persist($app); $this->_em->persist($pat); } + $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) { + foreach ($appointments as $eagerAppointment) { $this->assertInstanceOf(Proxy::class, $eagerAppointment->patient); - $this->assertTrue($eagerAppointment->patient->__isInitialized__, "Proxy should already be initialized due to eager loading!"); + $this->assertTrue($eagerAppointment->patient->__isInitialized__, 'Proxy should already be initialized due to eager loading!'); } } } @@ -80,11 +84,8 @@ class DDC633Appointment /** @Id @Column(type="integer") @GeneratedValue */ public $id; - /** - * @OneToOne(targetEntity="DDC633Patient", inversedBy="appointment", fetch="EAGER") - */ + /** @OneToOne(targetEntity="DDC633Patient", inversedBy="appointment", fetch="EAGER") */ public $patient; - } /** @@ -95,8 +96,6 @@ class DDC633Patient /** @Id @Column(type="integer") @GeneratedValue */ public $id; - /** - * @OneToOne(targetEntity="DDC633Appointment", mappedBy="patient") - */ + /** @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 f0147cfa6ab..e70d4aac443 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC6460Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC6460Test.php @@ -1,19 +1,22 @@ _em ->getClassMetadata(DDC6460Entity::class) @@ -43,16 +46,16 @@ public function testInlineEmbeddable() /** * @group DDC-6460 */ - public function testInlineEmbeddableProxyInitialization() + public function testInlineEmbeddableProxyInitialization(): void { - $entity = new DDC6460Entity(); - $entity->id = 1; - $entity->embedded = new DDC6460Embeddable(); + $entity = new DDC6460Entity(); + $entity->id = 1; + $entity->embedded = new DDC6460Embeddable(); $entity->embedded->field = 'test'; $this->_em->persist($entity); - $second = new DDC6460ParentEntity(); - $second->id = 1; + $second = new DDC6460ParentEntity(); + $second->id = 1; $second->lazyLoaded = $entity; $this->_em->persist($second); $this->_em->flush(); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC656Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC656Test.php index 3ee395adfdd..2b1289767e7 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC656Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC656Test.php @@ -1,24 +1,31 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC656Entity::class) + $this->_em->getClassMetadata(DDC656Entity::class), ] ); - } catch(\Exception $e) { - + } catch (Exception $e) { } } - public function testRecomputeSingleEntityChangeSet_PreservesFieldOrder() + public function testRecomputeSingleEntityChangeSet_PreservesFieldOrder(): void { $entity = new DDC656Entity(); $entity->setName('test1'); @@ -47,34 +54,32 @@ public function testRecomputeSingleEntityChangeSet_PreservesFieldOrder() */ class DDC656Entity { - /** - * @Column(type="string") - */ + /** @Column(type="string") */ public $name; - /** - * @Column(type="string") - */ + /** @Column(type="string") */ public $type; - /** - * @Id @Column(type="integer") @GeneratedValue - */ + /** @Id @Column(type="integer") @GeneratedValue */ public $specificationId; - public function getName() { + public function getName() + { return $this->name; } - public function setName($name) { + public function setName($name): void + { $this->name = $name; } - public function getType() { + public function getType() + { return $this->type; } - public function setType($type) { + public function setType($type): void + { $this->type = $type; } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC657Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC657Test.php index 68a718f1d09..788ff9e0915 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC657Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC657Test.php @@ -1,15 +1,22 @@ useModelSet('generic'); parent::setUp(); @@ -17,10 +24,10 @@ protected function setUp() : void $this->loadFixtures(); } - public function testEntitySingleResult() + public function testEntitySingleResult(): void { - $query = $this->_em->createQuery('SELECT d FROM ' . DateTimeModel::class . ' d'); - $datetime = $query->setMaxResults(1)->getSingleResult(); + $query = $this->_em->createQuery('SELECT d FROM ' . DateTimeModel::class . ' d'); + $datetime = $query->setMaxResults(1)->getSingleResult(); $this->assertInstanceOf(DateTimeModel::class, $datetime); @@ -29,12 +36,12 @@ public function testEntitySingleResult() $this->assertInstanceOf('DateTime', $datetime->date); } - public function testScalarResult() + public function testScalarResult(): void { - $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(); + $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); + $this->assertCount(2, $result); $this->assertStringContainsString('11:11:11', $result[0]['time']); $this->assertStringContainsString('2010-01-01', $result[0]['date']); @@ -45,12 +52,12 @@ public function testScalarResult() $this->assertStringContainsString('2010-02-02 12:12:12', $result[1]['datetime']); } - public function testaTicketEntityArrayResult() + public function testaTicketEntityArrayResult(): void { - $query = $this->_em->createQuery('SELECT d FROM ' . DateTimeModel::class . ' d ORDER BY d.date ASC'); - $result = $query->getArrayResult(); + $query = $this->_em->createQuery('SELECT d FROM ' . DateTimeModel::class . ' d ORDER BY d.date ASC'); + $result = $query->getArrayResult(); - $this->assertCount(2,$result); + $this->assertCount(2, $result); $this->assertInstanceOf('DateTime', $result[0]['datetime']); $this->assertInstanceOf('DateTime', $result[0]['time']); @@ -61,10 +68,10 @@ public function testaTicketEntityArrayResult() $this->assertInstanceOf('DateTime', $result[1]['date']); } - public function testTicketSingleResult() + public function testTicketSingleResult(): void { - $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(); + $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)); @@ -73,12 +80,12 @@ public function testTicketSingleResult() $this->assertInstanceOf('DateTime', $datetime['date']); } - public function testTicketResult() + public function testTicketResult(): void { - $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(); + $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); + $this->assertCount(2, $result); $this->assertInstanceOf('DateTime', $result[0]['time']); $this->assertInstanceOf('DateTime', $result[0]['date']); @@ -93,20 +100,20 @@ public function testTicketResult() $this->assertEquals('2010-02-02 12:12:12', $result[1]['datetime']->format('Y-m-d G:i:s')); } - public function loadFixtures() + public function loadFixtures(): void { - $timezone = new \DateTimeZone('America/Sao_Paulo'); + $timezone = new DateTimeZone('America/Sao_Paulo'); - $dateTime1 = new DateTimeModel(); - $dateTime2 = new DateTimeModel(); + $dateTime1 = new DateTimeModel(); + $dateTime2 = new DateTimeModel(); - $dateTime1->date = new \DateTime('2010-01-01', $timezone); - $dateTime1->time = new \DateTime('2010-01-01 11:11:11', $timezone); - $dateTime1->datetime= new \DateTime('2010-01-01 11:11:11', $timezone); + $dateTime1->date = new DateTime('2010-01-01', $timezone); + $dateTime1->time = new DateTime('2010-01-01 11:11:11', $timezone); + $dateTime1->datetime = new DateTime('2010-01-01 11:11:11', $timezone); - $dateTime2->date = new \DateTime('2010-02-02', $timezone); - $dateTime2->time = new \DateTime('2010-02-02 12:12:12', $timezone); - $dateTime2->datetime= new \DateTime('2010-02-02 12:12:12', $timezone); + $dateTime2->date = new DateTime('2010-02-02', $timezone); + $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); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC698Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC698Test.php index 7dd584af344..88f9f4ec917 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC698Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC698Test.php @@ -1,30 +1,36 @@ _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) { - + } catch (Exception $e) { } } - public function testTicket() + public function testTicket(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('p', 'r') - ->from(__NAMESPACE__ . '\DDC698Privilege', 'p') - ->leftJoin('p.roles', 'r'); + ->from(__NAMESPACE__ . '\DDC698Privilege', 'p') + ->leftJoin('p.roles', 'r'); $sql = $qb->getQuery()->getSQL(); @@ -36,70 +42,51 @@ public function testTicket() } /** - * * @Table(name="Roles") * @Entity */ class DDC698Role { - /** - * @Id @Column(name="roleID", type="integer") - * @GeneratedValue(strategy="AUTO") - * - */ - protected $roleID; - - /** - * @Column(name="name", type="string", length=45) - * - * - */ - protected $name; - - /** - * @Column(name="shortName", type="string", length=45) - * - * - */ - protected $shortName; - - - - /** - * @ManyToMany(targetEntity="DDC698Privilege", inversedBy="roles") - * @JoinTable(name="RolePrivileges", - * joinColumns={@JoinColumn(name="roleID", referencedColumnName="roleID")}, - * inverseJoinColumns={@JoinColumn(name="privilegeID", referencedColumnName="privilegeID")} - * ) - */ - protected $privilege; + /** + * @Id @Column(name="roleID", type="integer") + * @GeneratedValue(strategy="AUTO") + */ + protected $roleID; + + /** @Column(name="name", type="string", length=45) */ + protected $name; + /** @Column(name="shortName", type="string", length=45) */ + protected $shortName; + + + + /** + * @ManyToMany(targetEntity="DDC698Privilege", inversedBy="roles") + * @JoinTable(name="RolePrivileges", + * joinColumns={@JoinColumn(name="roleID", referencedColumnName="roleID")}, + * inverseJoinColumns={@JoinColumn(name="privilegeID", referencedColumnName="privilegeID")} + * ) + */ + protected $privilege; } /** - * * @Table(name="Privileges") * @Entity() */ class DDC698Privilege { - /** - * @Id @Column(name="privilegeID", type="integer") - * @GeneratedValue(strategy="AUTO") - * - */ - protected $privilegeID; - - /** - * @Column(name="name", type="string", length=45) - * - * - */ - protected $name; - - /** - * @ManyToMany(targetEntity="DDC698Role", mappedBy="privilege") + /** + * @Id @Column(name="privilegeID", type="integer") + * @GeneratedValue(strategy="AUTO") */ - protected $roles; + protected $privilegeID; + + /** @Column(name="name", type="string", length=45) */ + protected $name; + + /** @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 1818e7a80ed..10dc6bc6b6b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC719Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC719Test.php @@ -1,21 +1,27 @@ _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() + public function testIsEmptySqlGeneration(): void { $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'); @@ -39,76 +45,104 @@ class Entity */ protected $id; - public function getId() { return $this->id; } + public function getId() + { + return $this->id; + } } /** * @Entity * @Table(name="groups") */ -class DDC719Group extends Entity { +class DDC719Group extends Entity +{ /** @Column(type="string", nullable=false) */ protected $name; - /** @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")} - * ) - */ - protected $children = NULL; - - /** - * @ManyToMany(targetEntity="DDC719Group", mappedBy="children") - */ - protected $parents = NULL; - - /** - * construct - */ - public function __construct() { - parent::__construct(); - - $this->channels = new ArrayCollection(); - $this->children = new ArrayCollection(); - $this->parents = new ArrayCollection(); - } - - /** - * adds group as new child - * - * @param Group $child - */ - public function addGroup(Group $child) { - if ( ! $this->children->contains($child)) { + /** @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")} + * ) + */ + protected $children = null; + + /** @ManyToMany(targetEntity="DDC719Group", mappedBy="children") */ + protected $parents = null; + + /** + * construct + */ + public function __construct() + { + parent::__construct(); + + $this->channels = new ArrayCollection(); + $this->children = new ArrayCollection(); + $this->parents = new ArrayCollection(); + } + + /** + * adds group as new child + */ + public function addGroup(Group $child): void + { + if (! $this->children->contains($child)) { $this->children->add($child); $child->addGroup($this); } - } - - /** - * adds channel as new child - * - * @param Channel $child - */ - public function addChannel(Channel $child) { - if ( ! $this->channels->contains($child)) { + } + + /** + * adds channel as new child + */ + public function addChannel(Channel $child): void + { + if (! $this->channels->contains($child)) { $this->channels->add($child); } - } - - /** - * getter & setter - */ - public function getName() { return $this->name; } - public function setName($name) { $this->name = $name; } - public function getDescription() { return $this->description; } - public function setDescription($description) { $this->description = $description; } - public function getChildren() { return $this->children; } - public function getParents() { return $this->parents; } - public function getChannels() { return $this->channels; } + } + + /** + * getter & setter + */ + public function getName() + { + return $this->name; + } + + public function setName($name): void + { + $this->name = $name; + } + + public function getDescription() + { + return $this->description; + } + + public function setDescription($description): void + { + $this->description = $description; + } + + public function getChildren() + { + return $this->children; + } + + public function getParents() + { + return $this->parents; + } + + public function getChannels() + { + return $this->channels; + } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC729Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC729Test.php index ce9dd157b9b..dcf82a9b242 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC729Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC729Test.php @@ -1,42 +1,48 @@ _em); + $schemaTool = new SchemaTool($this->_em); $schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC729A::class), - $this->_em->getClassMetadata(DDC729B::class), + $this->_em->getClassMetadata(DDC729A::class), + $this->_em->getClassMetadata(DDC729B::class), ] ); - } catch(\Exception $e) { - + } catch (Exception $e) { } } /** @after */ - public function ensureTestGeneratedDeprecationMessages() : void + public function ensureTestGeneratedDeprecationMessages(): void { $this->assertHasDeprecationMessages(); } - public function testMergeManyToMany() + public function testMergeManyToMany(): void { - $a = new DDC729A(); - $b = new DDC729B(); + $a = new DDC729A(); + $b = new DDC729B(); $a->related[] = $b; $this->_em->persist($a); @@ -45,7 +51,7 @@ public function testMergeManyToMany() $this->_em->clear(); $aId = $a->id; - $a = new DDC729A(); + $a = new DDC729A(); $a->id = $aId; $this->assertInstanceOf(ArrayCollection::class, $a->related); @@ -54,8 +60,8 @@ public function testMergeManyToMany() $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->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(); @@ -64,11 +70,11 @@ public function testMergeManyToMany() $this->assertEquals(1, count($a->related)); } - public function testUnidirectionalMergeManyToMany() + public function testUnidirectionalMergeManyToMany(): void { - $a = new DDC729A(); - $b1 = new DDC729B(); - $b2 = new DDC729B(); + $a = new DDC729A(); + $b1 = new DDC729B(); + $b2 = new DDC729B(); $a->related[] = $b1; $this->_em->persist($a); @@ -78,7 +84,7 @@ public function testUnidirectionalMergeManyToMany() $this->_em->clear(); $aId = $a->id; - $a = new DDC729A(); + $a = new DDC729A(); $a->id = $aId; $a = $this->_em->merge($a); @@ -94,11 +100,11 @@ public function testUnidirectionalMergeManyToMany() $this->assertEquals(2, count($a->related)); } - public function testBidirectionalMergeManyToMany() + public function testBidirectionalMergeManyToMany(): void { - $a = new DDC729A(); - $b1 = new DDC729B(); - $b2 = new DDC729B(); + $a = new DDC729A(); + $b1 = new DDC729B(); + $b2 = new DDC729B(); $a->related[] = $b1; $this->_em->persist($a); @@ -108,7 +114,7 @@ public function testBidirectionalMergeManyToMany() $this->_em->clear(); $aId = $a->id; - $a = new DDC729A(); + $a = new DDC729A(); $a->id = $aId; $a = $this->_em->merge($a); @@ -126,11 +132,11 @@ public function testBidirectionalMergeManyToMany() $this->assertEquals(2, count($a->related)); } - public function testBidirectionalMultiMergeManyToMany() + public function testBidirectionalMultiMergeManyToMany(): void { - $a = new DDC729A(); - $b1 = new DDC729B(); - $b2 = new DDC729B(); + $a = new DDC729A(); + $b1 = new DDC729B(); + $b2 = new DDC729B(); $a->related[] = $b1; $this->_em->persist($a); @@ -140,7 +146,7 @@ public function testBidirectionalMultiMergeManyToMany() $this->_em->clear(); $aId = $a->id; - $a = new DDC729A(); + $a = new DDC729A(); $a->id = $aId; $a = $this->_em->merge($a); @@ -172,7 +178,7 @@ class DDC729A public function __construct() { - $this->related = new \Doctrine\Common\Collections\ArrayCollection(); + $this->related = new ArrayCollection(); } } @@ -189,6 +195,6 @@ class DDC729B public function __construct() { - $this->related = new \Doctrine\Common\Collections\ArrayCollection(); + $this->related = new ArrayCollection(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC735Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC735Test.php index 2e91e34dcb7..cdef46214de 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC735Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC735Test.php @@ -1,30 +1,35 @@ _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) { - + } catch (Exception $e) { } } - public function testRemoveElement_AppliesOrphanRemoval() + public function testRemoveElement_AppliesOrphanRemoval(): void { // Create a product and its first review - $product = new DDC735Product; + $product = new DDC735Product(); $review = new DDC735Review($product); // Persist and flush @@ -58,9 +63,7 @@ public function testRemoveElement_AppliesOrphanRemoval() */ class DDC735Product { - /** - * @Id @Column(type="integer") @GeneratedValue - */ + /** @Id @Column(type="integer") @GeneratedValue */ protected $id; /** @@ -75,7 +78,7 @@ class DDC735Product public function __construct() { - $this->reviews = new ArrayCollection; + $this->reviews = new ArrayCollection(); } public function getReviews() @@ -83,12 +86,12 @@ public function getReviews() return $this->reviews; } - public function addReview(DDC735Review $review) + public function addReview(DDC735Review $review): void { $this->reviews->add($review); } - public function removeReview(DDC735Review $review) + public function removeReview(DDC735Review $review): void { $this->reviews->removeElement($review); } @@ -99,14 +102,10 @@ public function removeReview(DDC735Review $review) */ class DDC735Review { - /** - * @Id @Column(type="integer") @GeneratedValue - */ + /** @Id @Column(type="integer") @GeneratedValue */ protected $id; - /** - * @ManyToOne(targetEntity="DDC735Product", inversedBy="reviews") - */ + /** @ManyToOne(targetEntity="DDC735Product", inversedBy="reviews") */ protected $product; public function __construct(DDC735Product $product) diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC736Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC736Test.php index 7987c6da661..2e66e91605a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC736Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC736Test.php @@ -1,16 +1,24 @@ useModelSet('ecommerce'); parent::setUp(); @@ -19,12 +27,12 @@ protected function setUp() : void /** * @group DDC-736 */ - public function testReorderEntityFetchJoinForHydration() + public function testReorderEntityFetchJoinForHydration(): void { - $cust = new ECommerceCustomer; + $cust = new ECommerceCustomer(); $cust->setName('roman'); - $cart = new ECommerceCart; + $cart = new ECommerceCart(); $cart->setPayment('cash'); $cart->setCustomer($cust); @@ -33,7 +41,7 @@ public function testReorderEntityFetchJoinForHydration() $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]; @@ -50,12 +58,12 @@ public function testReorderEntityFetchJoinForHydration() * @group DDC-925 * @group DDC-915 */ - public function testDqlTreeWalkerReordering() + public function testDqlTreeWalkerReordering(): void { - $cust = new ECommerceCustomer; + $cust = new ECommerceCustomer(); $cust->setName('roman'); - $cart = new ECommerceCart; + $cart = new ECommerceCart(); $cart->setPayment('cash'); $cart->setCustomer($cust); @@ -64,36 +72,32 @@ public function testDqlTreeWalkerReordering() $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"; + $dql = 'select c, c.name, ca, ca.payment from Doctrine\Tests\Models\ECommerce\ECommerceCart ca join ca.customer c'; $result = $this->_em->createQuery($dql) ->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [DisableFetchJoinTreeWalker::class]) ->getResult(); - /* @var $cart2 ECommerceCart */ $cart2 = $result[0][0]; + assert($cart2 instanceof ECommerceCart); $this->assertInstanceOf(Proxy::class, $cart2->getCustomer()); } } -class DisableFetchJoinTreeWalker extends \Doctrine\ORM\Query\TreeWalkerAdapter +class DisableFetchJoinTreeWalker extends TreeWalkerAdapter { - public function walkSelectStatement(AST\SelectStatement $AST) + public function walkSelectStatement(AST\SelectStatement $AST): void { $this->walkSelectClause($AST->selectClause); } - /** - * @param \Doctrine\ORM\Query\AST\SelectClause $selectClause - */ - public function walkSelectClause($selectClause) + public function walkSelectClause(SelectClause $selectClause): void { - foreach ($selectClause->selectExpressions AS $key => $selectExpr) { - /* @var $selectExpr \Doctrine\ORM\Query\AST\SelectExpression */ - if ($selectExpr->expression == "c") { + foreach ($selectClause->selectExpressions as $key => $selectExpr) { + assert($selectExpr instanceof SelectExpression); + if ($selectExpr->expression === 'c') { unset($selectClause->selectExpressions[$key]); break; } } } } - diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC742Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC742Test.php index 6758e842d3d..0bf183c282f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC742Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC742Test.php @@ -1,19 +1,25 @@ _schemaTool->createSchema( [ $this->_em->getClassMetadata(DDC742User::class), - $this->_em->getClassMetadata(DDC742Comment::class) + $this->_em->getClassMetadata(DDC742Comment::class), ] ); - } catch(\Exception $e) { + } catch (Exception $e) { } // make sure classes will be deserialized from caches @@ -39,20 +45,20 @@ protected function setUp() : void $this->_em->getMetadataFactory()->setMetadataFor(DDC742Comment::class, null); } - public function testIssue() + public function testIssue(): void { - $user = new DDC742User(); - $user->title = "Foo"; + $user = new DDC742User(); + $user->title = 'Foo'; $user->favoriteComments = new ArrayCollection(); - $comment1 = new DDC742Comment(); - $comment1->content = "foo"; + $comment1 = new DDC742Comment(); + $comment1->content = 'foo'; - $comment2 = new DDC742Comment(); - $comment2->content = "bar"; + $comment2 = new DDC742Comment(); + $comment2->content = 'bar'; - $comment3 = new DDC742Comment(); - $comment3->content = "baz"; + $comment3 = new DDC742Comment(); + $comment3->content = 'baz'; $user->favoriteComments->add($comment1); $user->favoriteComments->add($comment2); @@ -101,8 +107,7 @@ class DDC742User * joinColumns={@JoinColumn(name="user_id",referencedColumnName="id")}, * inverseJoinColumns={@JoinColumn(name="comment_id", referencedColumnName="id")} * ) - * - * @var \Doctrine\ORM\PersistentCollection + * @var PersistentCollection */ public $favoriteComments; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC748Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC748Test.php index 2d73f0e8936..ede9a604a00 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC748Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC748Test.php @@ -1,31 +1,34 @@ useModelSet('cms'); parent::setUp(); } - public function testRefreshWithManyToOne() + public function testRefreshWithManyToOne(): void { - $user = new CmsUser(); - $user->name = "beberlei"; - $user->status = "active"; - $user->username = "beberlei"; + $user = new CmsUser(); + $user->name = 'beberlei'; + $user->status = 'active'; + $user->username = 'beberlei'; $article = new CmsArticle(); $article->setAuthor($user); - $article->text = "foo"; - $article->topic = "bar"; + $article->text = 'foo'; + $article->topic = 'bar'; $this->_em->persist($user); $this->_em->persist($article); @@ -33,22 +36,22 @@ public function testRefreshWithManyToOne() $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->assertTrue($article !== $user->articles, 'The article should not be replaced on the inverse side of the relation.'); $this->assertInstanceOf(Collection::class, $user->articles); } - public function testRefreshOneToOne() + public function testRefreshOneToOne(): void { - $user = new CmsUser(); - $user->name = "beberlei"; - $user->status = "active"; - $user->username = "beberlei"; - - $address = new CmsAddress(); - $address->city = "Bonn"; - $address->country = "Germany"; - $address->street = "A street"; - $address->zip = 12345; + $user = new CmsUser(); + $user->name = 'beberlei'; + $user->status = 'active'; + $user->username = 'beberlei'; + + $address = new CmsAddress(); + $address->city = 'Bonn'; + $address->country = 'Germany'; + $address->street = 'A street'; + $address->zip = 12345; $address->setUser($user); $this->_em->persist($user); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC758Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC758Test.php index 20399cb7596..82a1e7972d4 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC758Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC758Test.php @@ -1,26 +1,31 @@ markTestSkipped('Destroys testsuite'); - $this->useModelSet("cms"); + $this->useModelSet('cms'); parent::setUp(); } /** @after */ - public function ensureTestGeneratedDeprecationMessages() : void + public function ensureTestGeneratedDeprecationMessages(): void { $this->assertHasDeprecationMessages(); } @@ -28,14 +33,14 @@ public function ensureTestGeneratedDeprecationMessages() : void /** * Helper method to set cascade to merge only */ - private function setCascadeMergeFor($class) + private function setCascadeMergeFor($class): void { $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; + $metadata->associationMappings[$key]['isCascadePersist'] = false; + $metadata->associationMappings[$key]['isCascadeMerge'] = true; + $metadata->associationMappings[$key]['isCascadeRemove'] = false; + $metadata->associationMappings[$key]['isCascadeDetach'] = false; } } @@ -44,22 +49,22 @@ private function setCascadeMergeFor($class) * causes the database to be updated with the new associations. * This specifically tests adding new associations. */ - public function testManyToManyMergeAssociationAdds() + public function testManyToManyMergeAssociationAdds(): void { $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"; + $cmsUser = new CmsUser(); + $cmsUser->username = 'dave'; + $cmsUser->name = 'Dave Keen'; + $cmsUser->status = 'testing'; - $group1 = new CmsGroup(); - $group1->name = "Group 1"; + $group1 = new CmsGroup(); + $group1->name = 'Group 1'; - $group2 = new CmsGroup(); - $group2->name = "Group 2"; + $group2 = new CmsGroup(); + $group2->name = 'Group 2'; $this->_em->persist($cmsUser); $this->_em->persist($group1); @@ -67,27 +72,27 @@ public function testManyToManyMergeAssociationAdds() $this->_em->flush(); $cmsUserId = $cmsUser->id; - $group1Id = $group1->id; - $group2Id = $group2->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"; + $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 = new CmsGroup(); + $group2->id = $group2Id; + $group2->name = 'Group 2'; $group2->users = new ArrayCollection(); $cmsUser->addGroup($group1); @@ -99,7 +104,7 @@ public function testManyToManyMergeAssociationAdds() $this->_em->clear(); - $cmsUsers = $this->_em->getRepository(CmsUser::class)->findAll(); + $cmsUsers = $this->_em->getRepository(CmsUser::class)->findAll(); $cmsGroups = $this->_em->getRepository(CmsGroup::class)->findAll(); // Check the entities are in the database @@ -121,21 +126,21 @@ public function testManyToManyMergeAssociationAdds() * 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() + public function testManyToManyMergeAssociationRemoves(): void { $this->setCascadeMergeFor(CmsUser::class); $this->setCascadeMergeFor(CmsGroup::class); - $cmsUser = new CmsUser(); - $cmsUser->username = "dave"; - $cmsUser->name = "Dave Keen"; - $cmsUser->status = "testing"; + $cmsUser = new CmsUser(); + $cmsUser->username = 'dave'; + $cmsUser->name = 'Dave Keen'; + $cmsUser->status = 'testing'; - $group1 = new CmsGroup(); - $group1->name = "Group 1"; + $group1 = new CmsGroup(); + $group1->name = 'Group 1'; - $group2 = new CmsGroup(); - $group2->name = "Group 2"; + $group2 = new CmsGroup(); + $group2->name = 'Group 2'; $cmsUser->addGroup($group1); $cmsUser->addGroup($group2); @@ -146,27 +151,27 @@ public function testManyToManyMergeAssociationRemoves() $this->_em->flush(); $cmsUserId = $cmsUser->id; - $group1Id = $group1->id; - $group2Id = $group2->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"; + $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 = 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 @@ -175,7 +180,7 @@ public function testManyToManyMergeAssociationRemoves() $this->_em->clear(); - $cmsUsers = $this->_em->getRepository(CmsUser::class)->findAll(); + $cmsUsers = $this->_em->getRepository(CmsUser::class)->findAll(); $cmsGroups = $this->_em->getRepository(CmsGroup::class)->findAll(); // Check the entities are in the database diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC767Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC767Test.php index 6fdd2bab153..f90deb45914 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC767Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC767Test.php @@ -1,13 +1,20 @@ useModelSet('cms'); parent::setUp(); @@ -16,21 +23,21 @@ protected function setUp() : void /** * @group DDC-767 */ - public function testCollectionChangesInsideTransaction() + public function testCollectionChangesInsideTransaction(): void { - $user = new CmsUser(); - $user->name = "beberlei"; - $user->status = "active"; - $user->username = "beberlei"; + $user = new CmsUser(); + $user->name = 'beberlei'; + $user->status = 'active'; + $user->username = 'beberlei'; - $group1 = new CmsGroup(); - $group1->name = "foo"; + $group1 = new CmsGroup(); + $group1->name = 'foo'; - $group2 = new CmsGroup(); - $group2->name = "bar"; + $group2 = new CmsGroup(); + $group2->name = 'bar'; - $group3 = new CmsGroup(); - $group3->name = "baz"; + $group3 = new CmsGroup(); + $group3->name = 'baz'; $user->addGroup($group1); $user->addGroup($group2); @@ -43,10 +50,10 @@ public function testCollectionChangesInsideTransaction() $this->_em->flush(); $this->_em->clear(); - /* @var $pUser CmsUser */ $pUser = $this->_em->find(get_class($user), $user->id); + assert($pUser instanceof CmsUser); - $this->assertNotNull($pUser, "User not retrieved from database."); + $this->assertNotNull($pUser, 'User not retrieved from database.'); $groups = [$group2->id, $group3->id]; @@ -64,7 +71,7 @@ public function testCollectionChangesInsideTransaction() $this->_em->flush(); $this->_em->commit(); - } catch(\Exception $e) { + } catch (Exception $e) { $this->_em->rollback(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC7969Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC7969Test.php index 7d9592714e5..ecfce0d7482 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC7969Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC7969Test.php @@ -9,9 +9,11 @@ use Doctrine\Tests\Models\Cache\Bar; use Doctrine\Tests\ORM\Functional\SecondLevelCacheAbstractTest; +use function assert; + class DDC7969Test extends SecondLevelCacheAbstractTest { - public function testChildEntityRetrievedFromCache() : void + public function testChildEntityRetrievedFromCache(): void { $this->loadFixturesCountries(); $this->loadFixturesStates(); @@ -25,8 +27,8 @@ public function testChildEntityRetrievedFromCache() : void $region->getCache()->flushAll(); } - /** @var Bar $bar */ $bar = $this->attractions[0]; + assert($bar instanceof Bar); $repository = $this->_em->getRepository(Bar::class); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC809Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC809Test.php index 0a190c9b4d7..994ce7979e3 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC809Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC809Test.php @@ -1,16 +1,22 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC809Variant::class), - $this->_em->getClassMetadata(DDC809SpecificationValue::class) + $this->_em->getClassMetadata(DDC809Variant::class), + $this->_em->getClassMetadata(DDC809SpecificationValue::class), ] ); @@ -39,7 +45,7 @@ protected function setUp() : void /** * @group DDC-809 */ - public function testIssue() + public function testIssue(): void { $result = $this->_em->createQueryBuilder() ->select('Variant, SpecificationValue') @@ -48,8 +54,8 @@ public function testIssue() ->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."); + $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.'); } } @@ -98,7 +104,6 @@ class DDC809SpecificationValue /** * @var Variant - * * @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 49159e68b3e..d34e043edc3 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC812Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC812Test.php @@ -1,13 +1,18 @@ useModelSet('cms'); parent::setUp(); @@ -16,16 +21,16 @@ protected function setUp() : void /** * @group DDC-812 */ - public function testFetchJoinInitializesPreviouslyUninitializedCollectionOfManagedEntity() + public function testFetchJoinInitializesPreviouslyUninitializedCollectionOfManagedEntity(): void { //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $article = new CmsArticle; - $article->topic = "hello"; - $article->text = "talk talk talk"; + $article = new CmsArticle(); + $article->topic = 'hello'; + $article->text = 'talk talk talk'; - $comment = new CmsComment; - $comment->topic = "good!"; - $comment->text = "stuff!"; + $comment = new CmsComment(); + $comment->topic = 'good!'; + $comment->text = 'stuff!'; $comment->article = $article; $this->_em->persist($article); @@ -36,7 +41,8 @@ public function testFetchJoinInitializesPreviouslyUninitializedCollectionOfManag $article2 = $this->_em->find(get_class($article), $article->id); $article2Again = $this->_em->createQuery( - "select a, c from Doctrine\Tests\Models\CMS\CmsArticle a join a.comments c where a.id = ?1") + 'select a, c from Doctrine\Tests\Models\CMS\CmsArticle a join a.comments c where a.id = ?1' + ) ->setParameter(1, $article->id) ->getSingleResult(); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC832Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC832Test.php index 0205f99d92e..e20932651a8 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC832Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC832Test.php @@ -1,10 +1,17 @@ markTestSkipped('Doesnt run on Oracle.'); } - $this->_em->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger()); + $this->_em->getConfiguration()->setSQLLogger(new EchoSQLLogger()); try { $this->_schemaTool->createSchema( @@ -24,13 +31,13 @@ protected function setUp() : void $this->_em->getClassMetadata(DDC832Like::class), ] ); - } catch(\Exception $e) { + } catch (Exception $e) { } } - public function tearDown() : void + public function tearDown(): void { - /* @var $sm \Doctrine\DBAL\Schema\AbstractSchemaManager */ + /** @var AbstractSchemaManager $sm */ $platform = $this->_em->getConnection()->getDatabasePlatform(); $sm = $this->_em->getConnection()->getSchemaManager(); @@ -42,7 +49,7 @@ public function tearDown() : void /** * @group DDC-832 */ - public function testQuotedTableBasicUpdate() + public function testQuotedTableBasicUpdate(): void { $like = new DDC832Like('test'); $this->_em->persist($like); @@ -58,7 +65,7 @@ public function testQuotedTableBasicUpdate() /** * @group DDC-832 */ - public function testQuotedTableBasicRemove() + public function testQuotedTableBasicRemove(): void { $like = new DDC832Like('test'); $this->_em->persist($like); @@ -76,7 +83,7 @@ public function testQuotedTableBasicRemove() /** * @group DDC-832 */ - public function testQuotedTableJoinedUpdate() + public function testQuotedTableJoinedUpdate(): void { $index = new DDC832JoinedIndex('test'); $this->_em->persist($index); @@ -92,7 +99,7 @@ public function testQuotedTableJoinedUpdate() /** * @group DDC-832 */ - public function testQuotedTableJoinedRemove() + public function testQuotedTableJoinedRemove(): void { $index = new DDC832JoinedIndex('test'); $this->_em->persist($index); @@ -110,7 +117,7 @@ public function testQuotedTableJoinedRemove() /** * @group DDC-832 */ - public function testQuotedTableJoinedChildUpdate() + public function testQuotedTableJoinedChildUpdate(): void { $index = new DDC832JoinedTreeIndex('test', 1, 2); $this->_em->persist($index); @@ -126,7 +133,7 @@ public function testQuotedTableJoinedChildUpdate() /** * @group DDC-832 */ - public function testQuotedTableJoinedChildRemove() + public function testQuotedTableJoinedChildRemove(): void { $index = new DDC832JoinedTreeIndex('test', 1, 2); $this->_em->persist($index); @@ -148,18 +155,13 @@ public function testQuotedTableJoinedChildRemove() */ class DDC832Like { - /** - * @Id @Column(type="integer") @GeneratedValue - */ + /** @Id @Column(type="integer") @GeneratedValue */ public $id; /** @Column(type="string") */ public $word; - /** - * @version - * @Column(type="integer") - */ + /** @Column(type="integer") */ public $version; public function __construct($word) @@ -177,18 +179,13 @@ public function __construct($word) */ class DDC832JoinedIndex { - /** - * @Id @Column(type="integer") @GeneratedValue - */ + /** @Id @Column(type="integer") @GeneratedValue */ public $id; /** @Column(type="string") */ public $name; - /** - * @version - * @Column(type="integer") - */ + /** @Column(type="integer") */ public $version; public function __construct($name) @@ -212,7 +209,7 @@ class DDC832JoinedTreeIndex extends DDC832JoinedIndex public function __construct($name, $lft, $rgt) { $this->name = $name; - $this->lft = $lft; - $this->rgt = $rgt; + $this->lft = $lft; + $this->rgt = $rgt; } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC837Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC837Test.php index 1c93cffae3d..a698594c7b1 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->_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), ] ); } @@ -21,26 +25,26 @@ protected function setUp() : void /** * @group DDC-837 */ - public function testIssue() + public function testIssue(): void { //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $c1 = new DDC837Class1(); - $c1->title = "Foo"; - $c1->description = "Foo"; - $aggregate1 = new DDC837Aggregate('test1'); - $c1->aggregate = $aggregate1; + $c1 = new DDC837Class1(); + $c1->title = 'Foo'; + $c1->description = 'Foo'; + $aggregate1 = new DDC837Aggregate('test1'); + $c1->aggregate = $aggregate1; - $c2 = new DDC837Class2(); - $c2->title = "Bar"; - $c2->description = "Bar"; - $c2->text = "Bar"; - $aggregate2 = new DDC837Aggregate('test2'); - $c2->aggregate = $aggregate2; + $c2 = new DDC837Class2(); + $c2->title = 'Bar'; + $c2->description = 'Bar'; + $c2->text = 'Bar'; + $aggregate2 = new DDC837Aggregate('test2'); + $c2->aggregate = $aggregate2; - $c3 = new DDC837Class3(); - $c3->apples = "Baz"; - $c3->bananas = "Baz"; + $c3 = new DDC837Class3(); + $c3->apples = 'Baz'; + $c3->bananas = 'Baz'; $this->_em->persist($c1); $this->_em->persist($aggregate1); @@ -75,12 +79,12 @@ public function testIssue() if ($obj instanceof DDC837Class1) { $this->assertEquals('Foo', $obj->title); $this->assertEquals('Foo', $obj->description); - } else if ($obj instanceof DDC837Class2) { + } elseif ($obj instanceof DDC837Class2) { $this->assertTrue($e2 === $obj); $this->assertEquals('Bar', $obj->title); $this->assertEquals('Bar', $obj->description); $this->assertEquals('Bar', $obj->text); - } else if ($obj instanceof DDC837Class3) { + } elseif ($obj instanceof DDC837Class3) { $this->assertEquals('Baz', $obj->apples); $this->assertEquals('Baz', $obj->bananas); } else { @@ -102,7 +106,7 @@ abstract class DDC837Super /** * @Id @Column(name="id", type="integer") * @GeneratedValue(strategy="AUTO") - */ + */ public $id; } @@ -111,19 +115,13 @@ abstract class DDC837Super */ class DDC837Class1 extends DDC837Super { - /** - * @Column(name="title", type="string", length=150) - */ + /** @Column(name="title", type="string", length=150) */ public $title; - /** - * @Column(name="content", type="string", length=500) - */ + /** @Column(name="content", type="string", length=500) */ public $description; - /** - * @OneToOne(targetEntity="DDC837Aggregate") - */ + /** @OneToOne(targetEntity="DDC837Aggregate") */ public $aggregate; } @@ -132,24 +130,16 @@ class DDC837Class1 extends DDC837Super */ class DDC837Class2 extends DDC837Super { - /** - * @Column(name="title", type="string", length=150) - */ + /** @Column(name="title", type="string", length=150) */ public $title; - /** - * @Column(name="content", type="string", length=500) - */ + /** @Column(name="content", type="string", length=500) */ public $description; - /** - * @Column(name="text", type="text") - */ + /** @Column(name="text", type="text") */ public $text; - /** - * @OneToOne(targetEntity="DDC837Aggregate") - */ + /** @OneToOne(targetEntity="DDC837Aggregate") */ public $aggregate; } @@ -160,14 +150,10 @@ class DDC837Class2 extends DDC837Super */ class DDC837Class3 extends DDC837Super { - /** - * @Column(name="title", type="string", length=150) - */ + /** @Column(name="title", type="string", length=150) */ public $apples; - /** - * @Column(name="content", type="string", length=500) - */ + /** @Column(name="content", type="string", length=500) */ public $bananas; } @@ -182,9 +168,7 @@ class DDC837Aggregate */ public $id; - /** - * @Column(name="sysname", type="string") - */ + /** @Column(name="sysname", type="string") */ protected $sysname; public function __construct($sysname) diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC849Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC849Test.php index 19af190ee28..4a7df435c13 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC849Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC849Test.php @@ -1,30 +1,35 @@ useModelSet('cms'); parent::setUp(); - $this->user = new CmsUser(); - $this->user->username = "beberlei"; - $this->user->name = "Benjamin"; - $this->user->status = "active"; + $this->user = new CmsUser(); + $this->user->username = 'beberlei'; + $this->user->name = 'Benjamin'; + $this->user->status = 'active'; - $this->group1 = new CmsGroup(); - $this->group1->name = "Group 1"; - $this->group2 = new CmsGroup(); - $this->group2->name = "Group 2"; + $this->group1 = new CmsGroup(); + $this->group1->name = 'Group 1'; + $this->group2 = new CmsGroup(); + $this->group2->name = 'Group 2'; $this->user->addGroup($this->group1); $this->user->addGroup($this->group2); @@ -39,7 +44,7 @@ protected function setUp() : void $this->user = $this->_em->find(CmsUser::class, $this->user->getId()); } - public function testRemoveContains() + public function testRemoveContains(): void { $group1 = $this->user->groups[0]; $group2 = $this->user->groups[1]; @@ -54,9 +59,9 @@ public function testRemoveContains() $this->assertFalse($this->user->groups->contains($group2)); } - public function testClearCount() + public function testClearCount(): void { - $this->user->addGroup(new CmsGroup); + $this->user->addGroup(new CmsGroup()); $this->assertEquals(3, count($this->user->groups)); $this->user->groups->clear(); @@ -65,7 +70,7 @@ public function testClearCount() $this->assertEquals(0, count($this->user->groups)); } - public function testClearContains() + public function testClearContains(): void { $group1 = $this->user->groups[0]; $group2 = $this->user->groups[1]; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC881Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC881Test.php index 376477a16d3..3188014e5c2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC881Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC881Test.php @@ -1,26 +1,32 @@ _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) { - + } catch (Exception $e) { } } @@ -28,15 +34,15 @@ protected function setUp() : void * @group DDC-117 * @group DDC-881 */ - public function testIssue() + public function testIssue(): void { /* Create two test users: albert and alfons */ - $albert = new DDC881User; - $albert->setName("albert"); + $albert = new DDC881User(); + $albert->setName('albert'); $this->_em->persist($albert); - $alfons = new DDC881User; - $alfons->setName("alfons"); + $alfons = new DDC881User(); + $alfons->setName('alfons'); $this->_em->persist($alfons); $this->_em->flush(); @@ -45,25 +51,25 @@ public function testIssue() $phoneAlbert1 = new DDC881PhoneNumber(); $phoneAlbert1->setUser($albert); $phoneAlbert1->setId(1); - $phoneAlbert1->setPhoneNumber("albert home: 012345"); + $phoneAlbert1->setPhoneNumber('albert home: 012345'); $this->_em->persist($phoneAlbert1); $phoneAlbert2 = new DDC881PhoneNumber(); $phoneAlbert2->setUser($albert); $phoneAlbert2->setId(2); - $phoneAlbert2->setPhoneNumber("albert mobile: 67890"); + $phoneAlbert2->setPhoneNumber('albert mobile: 67890'); $this->_em->persist($phoneAlbert2); $phoneAlfons1 = new DDC881PhoneNumber(); $phoneAlfons1->setId(1); $phoneAlfons1->setUser($alfons); - $phoneAlfons1->setPhoneNumber("alfons home: 012345"); + $phoneAlfons1->setPhoneNumber('alfons home: 012345'); $this->_em->persist($phoneAlfons1); $phoneAlfons2 = new DDC881PhoneNumber(); $phoneAlfons2->setId(2); $phoneAlfons2->setUser($alfons); - $phoneAlfons2->setPhoneNumber("alfons mobile: 67890"); + $phoneAlfons2->setPhoneNumber('alfons mobile: 67890'); $this->_em->persist($phoneAlfons2); /* We call alfons and albert once on their mobile numbers */ @@ -79,21 +85,20 @@ public function testIssue() $this->_em->clear(); // fetch-join that foreign-key/primary-key entity association - $dql = "SELECT c, p FROM " . DDC881PhoneCall::class . " c JOIN c.phonenumber p"; + $dql = 'SELECT c, p FROM ' . DDC881PhoneCall::class . ' c JOIN c.phonenumber p'; $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()); - $dql = "SELECT p, c FROM " . DDC881PhoneNumber::class . " p JOIN p.calls c"; + $dql = 'SELECT p, c FROM ' . DDC881PhoneNumber::class . ' p JOIN p.calls c'; $numbers = $this->_em->createQuery($dql)->getResult(); $this->assertEquals(2, count($numbers)); $this->assertInstanceOf(PersistentCollection::class, $numbers[0]->getCalls()); $this->assertTrue($numbers[0]->getCalls()->isInitialized()); } - } /** @@ -101,20 +106,15 @@ public function testIssue() */ class DDC881User { - /** * @Id * @Column(type="integer") * @GeneratedValue(strategy="AUTO") */ private $id; - /** - * @Column(type="string") - */ + /** @Column(type="string") */ private $name; - /** - * @OneToMany(targetEntity="DDC881PhoneNumber",mappedBy="id") - */ + /** @OneToMany(targetEntity="DDC881PhoneNumber",mappedBy="id") */ private $phoneNumbers; public function getName() @@ -122,7 +122,7 @@ public function getName() return $this->name; } - public function setName($name) + public function setName($name): void { $this->name = $name; } @@ -133,7 +133,6 @@ public function setName($name) */ class DDC881PhoneNumber { - /** * @Id * @Column(type="integer") @@ -144,32 +143,28 @@ class DDC881PhoneNumber * @ManyToOne(targetEntity="DDC881User",cascade={"all"}) */ private $user; - /** - * @Column(type="string") - */ + /** @Column(type="string") */ private $phonenumber; - /** - * @OneToMany(targetEntity="DDC881PhoneCall", mappedBy="phonenumber") - */ + /** @OneToMany(targetEntity="DDC881PhoneCall", mappedBy="phonenumber") */ private $calls; public function __construct() { - $this->calls = new \Doctrine\Common\Collections\ArrayCollection(); + $this->calls = new ArrayCollection(); } - public function setId($id) + public function setId($id): void { $this->id = $id; } - public function setUser(DDC881User $user) + public function setUser(DDC881User $user): void { $this->user = $user; } - public function setPhoneNumber($phoneNumber) + public function setPhoneNumber($phoneNumber): void { $this->phonenumber = $phoneNumber; } @@ -185,7 +180,6 @@ public function getCalls() */ class DDC881PhoneCall { - /** * @Id * @Column(type="integer") @@ -200,12 +194,10 @@ class DDC881PhoneCall * }) */ private $phonenumber; - /** - * @Column(type="string",nullable=true) - */ + /** @Column(type="string",nullable=true) */ private $callDate; - public function setPhoneNumber(DDC881PhoneNumber $phoneNumber) + public function setPhoneNumber(DDC881PhoneNumber $phoneNumber): void { $this->phonenumber = $phoneNumber; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC933Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC933Test.php index d7539c41bc1..e14eb4a6114 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC933Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC933Test.php @@ -1,16 +1,23 @@ useModelSet('company'); @@ -20,7 +27,7 @@ protected function setUp() : void /** * @group DDC-933 */ - public function testLockCTIClass() + public function testLockCTIClass(): void { if ($this->_em->getConnection()->getDatabasePlatform()->getName() === 'sqlite') { self::markTestSkipped('It should not run on in-memory databases'); @@ -30,7 +37,7 @@ public function testLockCTIClass() $manager->setName('beberlei'); $manager->setSalary(1234); $manager->setTitle('Vice President of This Test'); - $manager->setDepartment("Foo"); + $manager->setDepartment('Foo'); $this->_em->persist($manager); $this->_em->flush(); @@ -44,22 +51,17 @@ public function testLockCTIClass() } /** - * @param int $id - * @param string $newName - * - * @return void - * * @throws MappingException - * @throws \Doctrine\ORM\ORMException - * @throws \Doctrine\ORM\OptimisticLockException - * @throws \Doctrine\ORM\TransactionRequiredException + * @throws ORMException + * @throws OptimisticLockException + * @throws TransactionRequiredException */ - private function assertManagerCanBeUpdatedOnAnotherConnection(int $id, string $newName) + private function assertManagerCanBeUpdatedOnAnotherConnection(int $id, string $newName): void { $em = $this->_getEntityManager(TestUtil::getConnection()); - /** @var CompanyManager $manager */ $manager = $em->find(CompanyManager::class, $id); + assert($manager instanceof CompanyManager); $manager->setName($newName); $em->flush(); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC949Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC949Test.php index 68e9187eccf..ab5ff8965db 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC949Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC949Test.php @@ -1,5 +1,7 @@ useModelSet('generic'); parent::setUp(); @@ -16,12 +18,12 @@ protected function setUp() : void /** * @group DDC-949 */ - public function testBooleanThroughRepository() + public function testBooleanThroughRepository(): void { - $true = new BooleanModel(); + $true = new BooleanModel(); $true->booleanField = true; - $false = new BooleanModel(); + $false = new BooleanModel(); $false->booleanField = false; $this->_em->persist($true); @@ -29,13 +31,13 @@ public function testBooleanThroughRepository() $this->_em->flush(); $this->_em->clear(); - $true = $this->_em->getRepository(BooleanModel::class)->findOneBy(['booleanField' => true]); + $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."); + $this->assertInstanceOf(BooleanModel::class, $true, 'True model not found'); + $this->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."); + $this->assertInstanceOf(BooleanModel::class, $false, 'False model not found'); + $this->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 f9b609f868f..e3c84780a9c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC960Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC960Test.php @@ -1,36 +1,38 @@ _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) { - + } catch (Exception $e) { } } /** * @group DDC-960 */ - public function testUpdateRootVersion() + public function testUpdateRootVersion(): void { $child = new DDC960Child('Test'); $this->_em->persist($child); $this->_em->flush(); - $child->setName("Test2"); + $child->setName('Test2'); $this->_em->flush(); @@ -48,14 +50,10 @@ public function testUpdateRootVersion() */ class DDC960Root { - /** - * @Id @GeneratedValue @Column(type="integer") - */ + /** @Id @GeneratedValue @Column(type="integer") */ private $id; - /** - * @Column(type="integer") @Version - */ + /** @Column(type="integer") @Version */ private $version; public function getId() @@ -85,7 +83,7 @@ public function __construct($name) $this->name = $name; } - public function setName($name) + public function setName($name): void { $this->name = $name; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC992Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC992Test.php index ae975412493..03700eb33c3 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC992Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC992Test.php @@ -1,58 +1,64 @@ _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) { - + } catch (Exception $e) { } } - public function testIssue() + public function testIssue(): void { - $role = new DDC992Role(); - $role->name = "Parent"; - $child = new DDC992Role(); - $child->name = "child"; + $role = new DDC992Role(); + $role->name = 'Parent'; + $child = new DDC992Role(); + $child->name = 'child'; $role->extendedBy[] = $child; - $child->extends[] = $role; + $child->extends[] = $role; $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); - foreach ($child->extends AS $parent) { + foreach ($child->extends as $parent) { $this->assertEquals($role->getRoleID(), $parent->getRoleID()); } } - public function testOneToManyChild() + public function testOneToManyChild(): void { - $parent = new DDC992Parent(); - $child = new DDC992Child(); - $child->parent = $parent; + $parent = new DDC992Parent(); + $child = new DDC992Child(); + $child->parent = $parent; $parent->childs[] = $child; $this->_em->persist($parent); @@ -61,13 +67,13 @@ public function testOneToManyChild() $this->_em->clear(); $parentRepository = $this->_em->getRepository(get_class($parent)); - $childRepository = $this->_em->getRepository(get_class($child)); + $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())); - $child = $parentRepository->findOneBy(["id" => $child->id]); + $child = $parentRepository->findOneBy(['id' => $child->id]); $this->assertSame($parent->childs[0], $child); $this->_em->clear(); @@ -123,13 +129,9 @@ public function getRoleID() * @GeneratedValue(strategy="AUTO") */ public $roleID; - /** - * @Column (name="name", type="string", length=45) - */ + /** @Column (name="name", type="string", length=45) */ public $name; - /** - * @ManyToMany (targetEntity="DDC992Role", mappedBy="extends") - */ + /** @ManyToMany (targetEntity="DDC992Role", mappedBy="extends") */ public $extendedBy; /** * @ManyToMany (targetEntity="DDC992Role", inversedBy="extendedBy") @@ -140,8 +142,9 @@ public function getRoleID() */ public $extends; - public function __construct() { - $this->extends = new ArrayCollection; - $this->extendedBy = new ArrayCollection; + public function __construct() + { + $this->extends = new ArrayCollection(); + $this->extendedBy = new ArrayCollection(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH2947Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH2947Test.php index 2f9516536bf..574581f3e02 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH2947Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH2947Test.php @@ -1,5 +1,7 @@ resultCacheImpl = new ArrayCache(); @@ -19,7 +21,7 @@ protected function setUp() : void $this->_schemaTool->createSchema([$this->_em->getClassMetadata(GH2947Car::class)]); } - public function testIssue() + public function testIssue(): void { $this->createData(); $initialQueryCount = $this->getCurrentQueryCount(); @@ -50,14 +52,14 @@ private function createQuery() ->useResultCache(true, 3600, 'foo-cache-id'); } - private function createData() + private function createData(): void { $this->_em->persist(new GH2947Car('BMW')); $this->_em->flush(); $this->_em->clear(); } - private function updateData() + private function updateData(): void { $this->_em->createQueryBuilder() ->update(GH2947Car::class, 'car') diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5562Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5562Test.php index 31366feabfa..07ee93b9094 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5562Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5562Test.php @@ -1,15 +1,16 @@ enableSecondLevelCache(); @@ -27,9 +28,9 @@ protected function setUp() : void /** * @group GH-5562 */ - public function testCacheShouldBeUpdatedWhenAssociationChanges() + public function testCacheShouldBeUpdatedWhenAssociationChanges(): void { - $manager = new GH5562Manager(); + $manager = new GH5562Manager(); $merchant = new GH5562Merchant(); $manager->username = 'username'; @@ -45,7 +46,7 @@ public function testCacheShouldBeUpdatedWhenAssociationChanges() $merchant = $this->_em->find(GH5562Merchant::class, $merchant->id); - $merchant->name = mt_rand(); + $merchant->name = mt_rand(); $merchant->manager->username = 'usernameUPDATE'; $this->_em->flush(); @@ -64,8 +65,7 @@ public function testCacheShouldBeUpdatedWhenAssociationChanges() class GH5562Merchant { /** - * @var integer - * + * @var int * @Id * @Column(name="id", type="integer") * @GeneratedValue(strategy="IDENTITY") @@ -74,7 +74,6 @@ class GH5562Merchant /** * @var GH5562Manager - * * @OneToOne(targetEntity=GH5562Manager::class, mappedBy="merchant") * @Cache(usage="NONSTRICT_READ_WRITE") */ @@ -82,7 +81,6 @@ class GH5562Merchant /** * @var string - * * @Column(name="name", type="string", length=255, nullable=false) */ public $name; @@ -96,8 +94,7 @@ class GH5562Merchant abstract class GH5562User { /** - * @var integer - * + * @var int * @Id * @Column(name="id", type="integer") * @GeneratedValue(strategy="IDENTITY") @@ -111,17 +108,14 @@ abstract class GH5562User */ class GH5562Manager extends GH5562User { - /** * @var string - * * @Column */ public $username; /** * @var GH5562Merchant - * * @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 e966d744030..72755c48915 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5762Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5762Test.php @@ -1,30 +1,35 @@ _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), ] ); } - public function testIssue() + public function testIssue(): void { $result = $this->fetchData(); @@ -61,7 +66,7 @@ private function fetchData() return $qb->getQuery()->getSingleResult(); } - private function createData() + private function createData(): void { $car1 = new GH5762Car('BMW', '7 Series'); $car2 = new GH5762Car('Crysler', '300'); @@ -109,21 +114,17 @@ class GH5762Driver */ public $id; - /** - * @Column(type="string", length=255); - */ + /** @Column(type="string", length=255); */ public $name; - /** - * @OneToMany(targetEntity="GH5762DriverRide", mappedBy="driver") - */ + /** @OneToMany(targetEntity="GH5762DriverRide", mappedBy="driver") */ public $driverRides; public function __construct($id, $name) { $this->driverRides = new ArrayCollection(); - $this->id = $id; - $this->name = $name; + $this->id = $id; + $this->name = $name; } } @@ -150,7 +151,7 @@ class GH5762DriverRide function __construct(GH5762Driver $driver, GH5762Car $car) { $this->driver = $driver; - $this->car = $car; + $this->car = $car; $this->driver->driverRides->add($this); $this->car->carRides->add($this); @@ -163,7 +164,6 @@ function __construct(GH5762Driver $driver, GH5762Car $car) */ class GH5762Car { - /** * @Id * @Column(type="string", length=25) @@ -171,20 +171,16 @@ class GH5762Car */ public $brand; - /** - * @Column(type="string", length=255); - */ + /** @Column(type="string", length=255); */ public $model; - /** - * @OneToMany(targetEntity="GH5762DriverRide", mappedBy="car") - */ + /** @OneToMany(targetEntity="GH5762DriverRide", mappedBy="car") */ public $carRides; public function __construct($brand, $model) { $this->carRides = new ArrayCollection(); - $this->brand = $brand; - $this->model = $model; + $this->brand = $brand; + $this->model = $model; } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5804Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5804Test.php index 684e08ead3e..7715a97b826 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5804Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5804Test.php @@ -1,5 +1,7 @@ text = 'Max'; $this->_em->persist($firstArticle); $this->_em->flush(); @@ -54,7 +56,7 @@ public function generate(EntityManager $em, $entity) final class GH5804Type extends Type { - const NAME = 'GH5804Type'; + public const NAME = 'GH5804Type'; public function getName() { @@ -101,8 +103,6 @@ class GH5804Article */ public $version; - /** - * @Column(type="text") - */ + /** @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 7503c20d665..30d5341e1d2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5887Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5887Test.php @@ -1,18 +1,22 @@ setId($customerId); $cartId = 2; - $cart = new GH5887Cart(); + $cart = new GH5887Cart(); $cart->setId($cartId); $cart->setCustomer($customer); @@ -45,12 +49,12 @@ public function testLazyLoadsForeignEntitiesInOneToOneRelationWhileHavingCustomI $this->_em->clear(); $customerRepository = $this->_em->getRepository(GH5887Customer::class); - /** @var GH5887Customer $customer */ - $customer = $customerRepository->createQueryBuilder('c') + $customer = $customerRepository->createQueryBuilder('c') ->where('c.id = :id') ->setParameter('id', $customerId->getId()) ->getQuery() ->getOneOrNullResult(); + assert($customer instanceof GH5887Customer); $this->assertInstanceOf(GH5887Cart::class, $customer->getCart()); } @@ -63,7 +67,6 @@ class GH5887Cart { /** * @var int - * * @Id * @Column(type="integer") * @GeneratedValue(strategy="NONE") @@ -74,40 +77,27 @@ class GH5887Cart * One Cart has One Customer. * * @var GH5887Customer - * * @OneToOne(targetEntity="GH5887Customer", inversedBy="cart") * @JoinColumn(name="customer_id", referencedColumnName="id") */ private $customer; - /** - * @return int - */ - public function getId() + public function getId(): int { return $this->id; } - /** - * @param int $id - */ - public function setId($id) + public function setId(int $id): void { $this->id = $id; } - /** - * @return GH5887Customer - */ - public function getCustomer() + public function getCustomer(): GH5887Customer { return $this->customer; } - /** - * @param GH5887Customer $customer - */ - public function setCustomer(GH5887Customer $customer) + public function setCustomer(GH5887Customer $customer): void { if ($this->customer !== $customer) { $this->customer = $customer; @@ -123,7 +113,6 @@ class GH5887Customer { /** * @var GH5887CustomIdObject - * * @Id * @Column(type="GH5887CustomIdObject") * @GeneratedValue(strategy="NONE") @@ -134,39 +123,26 @@ class GH5887Customer * One Customer has One Cart. * * @var GH5887Cart - * * @OneToOne(targetEntity="GH5887Cart", mappedBy="customer") */ private $cart; - /** - * @return GH5887CustomIdObject - */ - public function getId() + public function getId(): GH5887CustomIdObject { return $this->id; } - /** - * @param GH5887CustomIdObject $id - */ - public function setId(GH5887CustomIdObject $id) + public function setId(GH5887CustomIdObject $id): void { $this->id = $id; } - /** - * @return GH5887Cart - */ public function getCart(): GH5887Cart { return $this->cart; } - /** - * @param GH5887Cart $cart - */ - public function setCart(GH5887Cart $cart) + public function setCart(GH5887Cart $cart): void { if ($this->cart !== $cart) { $this->cart = $cart; @@ -177,22 +153,14 @@ public function setCart(GH5887Cart $cart) class GH5887CustomIdObject { - /** - * @var int - */ + /** @var int */ private $id; - /** - * @param int $id - */ - public function __construct($id) + public function __construct(int $id) { $this->id = $id; } - /** - * @return int - */ public function getId(): int { return $this->id; @@ -206,7 +174,7 @@ public function __toString() class GH5887CustomIdObjectType extends StringType { - const NAME = 'GH5887CustomIdObject'; + public const NAME = 'GH5887CustomIdObject'; /** * {@inheritdoc} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6029Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6029Test.php index acd91231b31..37791b9672e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6029Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6029Test.php @@ -1,17 +1,18 @@ groups->add(new GH6029Group2()); @@ -57,7 +58,7 @@ public function testManyToManyAssociation() : void * * @group GH-6029 */ - public function testOneToManyAssociation() : void + public function testOneToManyAssociation(): void { $product = new GH6029Product(); $product->features->add(new GH6029Group2()); @@ -112,9 +113,7 @@ class GH6029Product /** @Id @Column(type="integer") @GeneratedValue */ public $id; - /** - * @OneToMany(targetEntity=GH6029Feature::class, mappedBy="product", cascade={"all"}) - */ + /** @OneToMany(targetEntity=GH6029Feature::class, mappedBy="product", cascade={"all"}) */ public $features; public function __construct() diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6141Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6141Test.php index b6fd3e2e350..17973b506a4 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6141Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6141Test.php @@ -1,4 +1,7 @@ _em->persist($boss); @@ -67,14 +73,14 @@ public function testEnumDiscriminatorsShouldBeConvertedToString() class GH6141PeopleType extends StringType { - const NAME = 'gh6141people'; + public const NAME = 'gh6141people'; /** * {@inheritdoc} */ public function convertToDatabaseValue($value, AbstractPlatform $platform) { - if (!$value instanceof GH6141People) { + if (! $value instanceof GH6141People) { $value = GH6141People::get($value); } @@ -100,60 +106,40 @@ public function getName() class GH6141People { - const BOSS = 'boss'; - const EMPLOYEE = 'employee'; + public const BOSS = 'boss'; + public const EMPLOYEE = 'employee'; - /** - * @var string - */ + /** @var string */ private $value; /** - * @param string $value - * - * @return GH6141People - * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ - public static function get($value) + public static function get(string $value): GH6141People { - if (!self::isValid($value)) { - throw new \InvalidArgumentException(); + if (! self::isValid($value)) { + throw new InvalidArgumentException(); } return new self($value); } - /** - * @param string $valid - * - * @return bool - */ - private static function isValid($valid) + private static function isValid(string $valid): bool { return in_array($valid, [self::BOSS, self::EMPLOYEE]); } - /** - * @param string $value - */ - private function __construct($value) + private function __construct(string $value) { $this->value = $value; } - /** - * @return string - */ - public function getValue() + public function getValue(): string { return $this->value; } - /** - * @return string - */ - public function __toString() + public function __toString(): string { return $this->value; } @@ -177,15 +163,10 @@ abstract class GH6141Person */ public $id; - /** - * @Column(type="string") - */ + /** @Column(type="string") */ public $name; - /** - * @param string $name - */ - public function __construct($name) + public function __construct(string $name) { $this->name = $name; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6217Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6217Test.php index 590793e26cf..1995c49f1a0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6217Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6217Test.php @@ -1,14 +1,19 @@ enableSecondLevelCache(); @@ -20,10 +25,10 @@ protected function setUp() : void ]); } - public function testLoadingOfSecondLevelCacheOnEagerAssociations() : void + public function testLoadingOfSecondLevelCacheOnEagerAssociations(): void { - $lazy = new GH6217AssociatedEntity(); - $eager = new GH6217AssociatedEntity(); + $lazy = new GH6217AssociatedEntity(); + $eager = new GH6217AssociatedEntity(); $fetched = new GH6217FetchedEntity($lazy, $eager); $this->_em->persist($eager); @@ -38,7 +43,7 @@ public function testLoadingOfSecondLevelCacheOnEagerAssociations() : void self::assertCount(1, $repository->findBy($filters)); $queryCount = $this->getCurrentQueryCount(); - /* @var $found GH6217FetchedEntity[] */ + /** @var GH6217FetchedEntity[] $found */ $found = $repository->findBy($filters); self::assertCount(1, $found); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6362Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6362Test.php index 40259653d53..be8ff37dcd5 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6362Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6362Test.php @@ -1,15 +1,18 @@ addEntityResult(GH6362Start::class, 'a', 'base'); $rsm->addJoinedEntityResult(GH6362Base::class, 'b', 'a', 'bases'); $rsm->addEntityResult(GH6362Child::class, 'c'); @@ -67,7 +70,7 @@ public function testInheritanceJoinAlias() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new ObjectHydrator($this->_em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $this->assertInstanceOf(GH6362Start::class, $result[0]['base']); @@ -87,9 +90,7 @@ class GH6362Start */ protected $id; - /** - * @ManyToOne(targetEntity="GH6362Base", inversedBy="starts") - */ + /** @ManyToOne(targetEntity="GH6362Base", inversedBy="starts") */ private $bases; } @@ -108,9 +109,7 @@ abstract class GH6362Base */ protected $id; - /** - * @OneToMany(targetEntity="GH6362Start", mappedBy="bases") - */ + /** @OneToMany(targetEntity="GH6362Start", mappedBy="bases") */ private $starts; } @@ -119,9 +118,7 @@ abstract class GH6362Base */ class GH6362Child extends GH6362Base { - /** - * @OneToMany(targetEntity="GH6362Join", mappedBy="child") - */ + /** @OneToMany(targetEntity="GH6362Join", mappedBy="child") */ private $joins; } @@ -137,8 +134,6 @@ class GH6362Join */ private $id; - /** - * @ManyToOne(targetEntity="GH6362Child", inversedBy="joins") - */ + /** @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 d517f7168f0..7db1a07b3f3 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6402Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6402Test.php @@ -1,5 +1,7 @@ useModelSet('quote'); parent::setUp(); } - public function testFind() + public function testFind(): void { $id = $this->createAddress(); @@ -28,7 +30,7 @@ public function testFind() self::assertNotNull($address->user); } - public function testQuery() + public function testQuery(): void { $id = $this->createAddress(); @@ -40,7 +42,7 @@ public function testQuery() self::assertNotNull($addresses[0]->user); } - public function testFindWithSubClass() + public function testFindWithSubClass(): void { $id = $this->createFullAddress(); @@ -48,7 +50,7 @@ public function testFindWithSubClass() self::assertNotNull($address->user); } - public function testQueryWithSubClass() + public function testQueryWithSubClass(): void { $id = $this->createFullAddress(); @@ -62,7 +64,7 @@ public function testQueryWithSubClass() private function createAddress() { - $address = new Address(); + $address = new Address(); $address->zip = 'bar'; $this->persistAddress($address); @@ -72,8 +74,8 @@ private function createAddress() private function createFullAddress() { - $address = new FullAddress(); - $address->zip = 'bar'; + $address = new FullAddress(); + $address->zip = 'bar'; $address->city = new City('London'); $this->persistAddress($address); @@ -81,10 +83,10 @@ private function createFullAddress() return $address->id; } - private function persistAddress(Address $address) + private function persistAddress(Address $address): void { - $user = new User(); - $user->name = "foo"; + $user = new User(); + $user->name = 'foo'; $user->setAddress($address); $this->_em->persist($user); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6464Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6464Test.php index 1d75cdf3dc2..f5a682d05d1 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6464Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6464Test.php @@ -1,5 +1,7 @@ _em->createQueryBuilder() ->select('p') diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6531Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6531Test.php index a8096afb517..3d73a8a67de 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6531Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6531Test.php @@ -1,12 +1,15 @@ addAttribute('name', 'value'); @@ -60,7 +63,7 @@ public function testDynamicAttributes() : void /** * @group GH-6531 */ - public function testJoinTableWithMetadata() : void + public function testJoinTableWithMetadata(): void { $product = new GH6531Product(); $this->_em->persist($product); @@ -108,7 +111,7 @@ class GH6531Article /** @OneToMany(targetEntity=GH6531ArticleAttribute::class, mappedBy="article", cascade={"ALL"}, indexBy="attribute") */ public $attributes; - public function addAttribute(string $name, string $value) + public function addAttribute(string $name, string $value): void { $this->attributes[$name] = new GH6531ArticleAttribute($name, $value, $this); } @@ -152,7 +155,7 @@ public function __construct() $this->items = new ArrayCollection(); } - public function addItem(GH6531Product $product, int $amount) : void + public function addItem(GH6531Product $product, int $amount): void { $this->items->add(new GH6531OrderItem($this, $product, $amount)); } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6682Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6682Test.php index 4d11eb79b4e..63922eaa8f2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6682Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6682Test.php @@ -1,5 +1,7 @@ 'test_sequence', diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6699Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6699Test.php index 3929f3d6409..8405bf6e502 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6699Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6699Test.php @@ -1,5 +1,7 @@ useModelSet('cms'); parent::setUp(); } - public function testMixedParametersWithZeroNumber() : void + public function testMixedParametersWithZeroNumber(): void { $query = $this->_em->createQueryBuilder() ->select('u') @@ -36,7 +38,7 @@ public function testMixedParametersWithZeroNumber() : void self::assertSame('bar', $query->getParameter('username')->getValue()); } - public function testMixedParametersWithZeroNumberOnQueryBuilder() : void + public function testMixedParametersWithZeroNumberOnQueryBuilder(): void { $query = $this->_em->createQueryBuilder() ->select('u') diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6740Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6740Test.php index 58b49bdc8e0..9ebe631f330 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6740Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6740Test.php @@ -1,30 +1,26 @@ useModelSet('ecommerce'); @@ -54,7 +50,7 @@ protected function setUp() : void /** * @group GH-6740 */ - public function testCollectionFilteringLteOperator() : void + public function testCollectionFilteringLteOperator(): void { $product = $this->_em->find(ECommerceProduct::class, $this->productId); $criteria = Criteria::create()->where(Criteria::expr()->lte('id', $this->secondCategoryId)); @@ -65,7 +61,7 @@ public function testCollectionFilteringLteOperator() : void /** * @group GH-6740 */ - public function testCollectionFilteringLtOperator() : void + public function testCollectionFilteringLtOperator(): void { $product = $this->_em->find(ECommerceProduct::class, $this->productId); $criteria = Criteria::create()->where(Criteria::expr()->lt('id', $this->secondCategoryId)); @@ -76,7 +72,7 @@ public function testCollectionFilteringLtOperator() : void /** * @group GH-6740 */ - public function testCollectionFilteringGteOperator() : void + public function testCollectionFilteringGteOperator(): void { $product = $this->_em->find(ECommerceProduct::class, $this->productId); $criteria = Criteria::create()->where(Criteria::expr()->gte('id', $this->firstCategoryId)); @@ -87,7 +83,7 @@ public function testCollectionFilteringGteOperator() : void /** * @group GH-6740 */ - public function testCollectionFilteringGtOperator() : void + public function testCollectionFilteringGtOperator(): void { $product = $this->_em->find(ECommerceProduct::class, $this->productId); $criteria = Criteria::create()->where(Criteria::expr()->gt('id', $this->firstCategoryId)); @@ -98,7 +94,7 @@ public function testCollectionFilteringGtOperator() : void /** * @group GH-6740 */ - public function testCollectionFilteringEqualsOperator() : void + public function testCollectionFilteringEqualsOperator(): void { $product = $this->_em->find(ECommerceProduct::class, $this->productId); $criteria = Criteria::create()->where(Criteria::expr()->eq('id', $this->firstCategoryId)); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6937Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6937Test.php index 091e500e6a0..d41e36a71ba 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6937Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6937Test.php @@ -1,5 +1,7 @@ setUpEntitySchema([GH6937Person::class, GH6937Employee::class, GH6937Manager::class]); } - public function testPhoneNumberIsPopulatedWithFind() : void + public function testPhoneNumberIsPopulatedWithFind(): void { $manager = new GH6937Manager(); $manager->name = 'Kevin'; @@ -38,7 +37,7 @@ public function testPhoneNumberIsPopulatedWithFind() : void self::assertSame('Accounting', $persistedManager->department); } - public function testPhoneNumberIsPopulatedWithQueryBuilderUsingSimpleObjectHydrator() : void + public function testPhoneNumberIsPopulatedWithQueryBuilderUsingSimpleObjectHydrator(): void { $manager = new GH6937Manager(); $manager->name = 'Kevin'; @@ -61,7 +60,7 @@ public function testPhoneNumberIsPopulatedWithQueryBuilderUsingSimpleObjectHydra self::assertSame('Accounting', $persistedManager->department); } - public function testPhoneNumberIsPopulatedWithQueryBuilder() : void + public function testPhoneNumberIsPopulatedWithQueryBuilder(): void { $manager = new GH6937Manager(); $manager->name = 'Kevin'; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7012Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7012Test.php index 069e5b37c38..77de7b100dc 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7012Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7012Test.php @@ -7,9 +7,11 @@ use Doctrine\Tests\Models\Quote\User as QuotedUser; use Doctrine\Tests\OrmFunctionalTestCase; +use function sprintf; + final class GH7012Test extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { $this->useModelSet('quote'); @@ -21,7 +23,7 @@ protected function setUp() : void /** * @group GH-7012 */ - public function testUpdateEntityWithIdentifierAssociationWithQuotedJoinColumn() : void + public function testUpdateEntityWithIdentifierAssociationWithQuotedJoinColumn(): void { $user = new QuotedUser(); $user->name = 'John Doe'; @@ -69,9 +71,7 @@ class GH7012UserData */ public $user; - /** - * @Column(type="string", name="`name`") - */ + /** @Column(type="string", name="`name`") */ public $name; public function __construct(QuotedUser $user, string $name) diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7062Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7062Test.php index 2b167ec4208..e558586e82c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7062Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7062Test.php @@ -1,4 +1,5 @@ createInitialRankingWithRelatedEntities(); $this->modifyRanking(); $this->verifyRanking(); } - private function createInitialRankingWithRelatedEntities() : void + private function createInitialRankingWithRelatedEntities(): void { - $team = new GH7062Team(self::TEAM_ID); - $season = new GH7062Season(self::SEASON_ID); + $team = new GH7062Team(self::TEAM_ID); + $season = new GH7062Season(self::SEASON_ID); $season->ranking = new GH7062Ranking($season, [$team]); @@ -53,10 +56,10 @@ private function createInitialRankingWithRelatedEntities() : void } } - private function modifyRanking() : void + private function modifyRanking(): void { - /** @var GH7062Ranking $ranking */ $ranking = $this->_em->find(GH7062Ranking::class, self::SEASON_ID); + assert($ranking instanceof GH7062Ranking); foreach ($ranking->positions as $position) { $position->points += 3; @@ -66,10 +69,10 @@ private function modifyRanking() : void $this->_em->clear(); } - private function verifyRanking() : void + private function verifyRanking(): void { - /** @var GH7062Season $season */ $season = $this->_em->find(GH7062Season::class, self::SEASON_ID); + assert($season instanceof GH7062Season); self::assertInstanceOf(GH7062Season::class, $season); $ranking = $season->ranking; @@ -93,14 +96,12 @@ class GH7062Ranking * @Id * @OneToOne(targetEntity=GH7062Season::class, inversedBy="ranking") * @JoinColumn(name="season", referencedColumnName="id") - * * @var GH7062Season */ public $season; /** * @OneToMany(targetEntity=GH7062RankingPosition::class, mappedBy="ranking", cascade={"all"}) - * * @var Collection|GH7062RankingPosition[] * @psalm-var Collection */ @@ -131,14 +132,12 @@ class GH7062Season /** * @Id * @Column(type="string") - * * @var string */ public $id; /** * @OneToOne(targetEntity=GH7062Ranking::class, mappedBy="season", cascade={"all"}) - * * @var GH7062Ranking|null */ public $ranking; @@ -160,7 +159,6 @@ class GH7062Team /** * @Id * @Column(type="string") - * * @var string */ public $id; @@ -183,7 +181,6 @@ class GH7062RankingPosition * @Id * @ManyToOne(targetEntity=GH7062Ranking::class, inversedBy="positions") * @JoinColumn(name="season", referencedColumnName="season") - * * @var GH7062Ranking */ public $ranking; @@ -192,14 +189,12 @@ class GH7062RankingPosition * @Id * @ManyToOne(targetEntity=GH7062Team::class) * @JoinColumn(name="team_id", referencedColumnName="id") - * * @var GH7062Team */ public $team; /** * @Column(type="integer") - * * @var int */ public $points; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7067Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7067Test.php index 972161ec988..c8ee4f28a3e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7067Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7067Test.php @@ -1,11 +1,17 @@ enableSecondLevelCache(); parent::setUp(); @@ -16,21 +22,21 @@ protected function setUp() : void /** * @group GH-7067 */ - public function testSLCWithVersion() : void + public function testSLCWithVersion(): void { $entity = new GH7067Entity(); - $entity->lastUpdate = new \DateTime(); + $entity->lastUpdate = new DateTime(); $this->_em->persist($entity); $this->_em->flush(); $this->_em->clear(); - /** @var GH7067Entity $notCached */ $notCached = $this->_em->find(GH7067Entity::class, $entity->id); + assert($notCached instanceof GH7067Entity); self::assertNotNull($notCached->version, 'Version already cached by persister above, it must be not null'); - $notCached->lastUpdate = new \DateTime('+1 seconds'); + $notCached->lastUpdate = new DateTime('+1 seconds'); $this->_em->flush(); $this->_em->clear(); @@ -47,23 +53,20 @@ class GH7067Entity * @Id * @GeneratedValue * @Column(type="integer") - * * @var int */ public $id; /** * @Column(type="datetime") - * - * @var \DateTime + * @var DateTime */ public $lastUpdate; /** * @Column(type="datetime") * @Version - * - * @var \DateTime + * @var DateTime */ public $version; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7068Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7068Test.php index 234b7fbce62..594571a785e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7068Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7068Test.php @@ -1,5 +1,7 @@ _em->persist($entity); @@ -37,7 +36,8 @@ public function testLockModeIsRespected() } /** @Entity */ -final class SomeEntity { +final class SomeEntity +{ /** @Id @Column(type="integer") @GeneratedValue */ public $id; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7079Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7079Test.php index a59dd67bbf4..77136c9977e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7079Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7079Test.php @@ -21,10 +21,7 @@ final class GH7079Test extends OrmFunctionalTestCase /** @var AbstractPlatform */ private $platform; - /** - * {@inheritDoc} - */ - protected function setUp() : void + protected function setUp(): void { parent::setUp(); @@ -32,7 +29,7 @@ protected function setUp() : void $this->strategy = new DefaultQuoteStrategy(); } - public function testGetTableName() : void + public function testGetTableName(): void { $table = [ 'name' => 'cms_user', @@ -45,7 +42,7 @@ public function testGetTableName() : void self::assertEquals($this->getTableFullName($table), $this->strategy->getTableName($cm, $this->platform)); } - public function testJoinTableName() : void + public function testJoinTableName(): void { $table = [ 'name' => 'cmsaddress_cmsuser', @@ -68,7 +65,7 @@ public function testJoinTableName() : void ); } - private function getTableFullName(array $table) : string + private function getTableFullName(array $table): string { $join = '.'; if (! $this->platform->supportsSchemas() && $this->platform->canEmulateSchemas()) { @@ -78,7 +75,7 @@ private function getTableFullName(array $table) : string return $table['schema'] . $join . $table['name']; } - private function createClassMetadata(string $className) : ClassMetadata + private function createClassMetadata(string $className): ClassMetadata { $cm = new ClassMetadata($className); $cm->initializeReflection(new RuntimeReflectionService()); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7259Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7259Test.php index 3ddbb945254..ad401655322 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7259Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7259Test.php @@ -1,4 +1,5 @@ _em->persist($space); $this->_em->flush(); - $feed = new GH7259Feed(); + $feed = new GH7259Feed(); $feed->space = $space; - $file = new GH7259File(); - $file->space = $space; - $fileVersion = new GH7259FileVersion(); + $file = new GH7259File(); + $file->space = $space; + $fileVersion = new GH7259FileVersion(); $fileVersion->file = $file; $this->_em->persist($file); @@ -44,7 +45,7 @@ public function testPersistFileBeforeVersion() : void /** * @group GH-7259 */ - public function testPersistFileAfterVersion() : void + public function testPersistFileAfterVersion(): void { $space = new GH7259Space(); @@ -54,12 +55,12 @@ public function testPersistFileAfterVersion() : void $space = $this->_em->find(GH7259Space::class, $space->id); - $feed = new GH7259Feed(); + $feed = new GH7259Feed(); $feed->space = $space; - $file = new GH7259File(); - $file->space = $space; - $fileVersion = new GH7259FileVersion(); + $file = new GH7259File(); + $file->space = $space; + $fileVersion = new GH7259FileVersion(); $fileVersion->file = $file; $this->_em->persist($fileVersion); @@ -81,7 +82,6 @@ class GH7259File * @Id * @GeneratedValue * @Column(type="integer") - * * @var int */ public $id; @@ -89,7 +89,6 @@ class GH7259File /** * @ManyToOne(targetEntity=GH7259Space::class) * @JoinColumn(nullable=false) - * * @var GH7259Space|null */ public $space; @@ -104,7 +103,6 @@ class GH7259FileVersion * @Id * @GeneratedValue * @Column(type="integer") - * * @var int */ public $id; @@ -112,7 +110,6 @@ class GH7259FileVersion /** * @ManyToOne(targetEntity=GH7259File::class) * @JoinColumn(nullable=false) - * * @var GH7259File|null */ public $file; @@ -127,7 +124,6 @@ class GH7259Space * @Id * @GeneratedValue * @Column(type="integer") - * * @var int */ public $id; @@ -135,7 +131,6 @@ class GH7259Space /** * @ManyToOne(targetEntity=GH7259File::class) * @JoinColumn(nullable=true) - * * @var GH7259File|null */ public $ruleFile; @@ -150,7 +145,6 @@ class GH7259Feed * @Id * @GeneratedValue * @Column(type="integer") - * * @var int */ public $id; @@ -158,7 +152,6 @@ class GH7259Feed /** * @ManyToOne(targetEntity=GH7259Space::class) * @JoinColumn(nullable=false) - * * @var GH7259Space|null */ public $space; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7286Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7286Test.php index 73d20148d9a..b471f6ea849 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7286Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7286Test.php @@ -1,5 +1,7 @@ _em->clear(); } - public function testAggregateExpressionInFunction() : void + public function testAggregateExpressionInFunction(): void { $query = $this->_em->createQuery( 'SELECT CONCAT(e.type, MIN(e.version)) pair' @@ -54,7 +53,7 @@ public function testAggregateExpressionInFunction() : void /** * @group DDC-1091 */ - public function testAggregateFunctionInCustomFunction() : void + public function testAggregateFunctionInCustomFunction(): void { $this->_em->getConfiguration()->addCustomStringFunction('CC', GH7286CustomConcat::class); @@ -113,7 +112,7 @@ class GH7286CustomConcat extends FunctionNode /** @var Node */ private $second; - public function parse(Parser $parser) : void + public function parse(Parser $parser): void { $parser->match(Lexer::T_IDENTIFIER); $parser->match(Lexer::T_OPEN_PARENTHESIS); @@ -125,7 +124,7 @@ public function parse(Parser $parser) : void $parser->match(Lexer::T_CLOSE_PARENTHESIS); } - public function getSql(SqlWalker $walker) : string + public function getSql(SqlWalker $walker): string { return $walker->getConnection()->getDatabasePlatform()->getConcatExpression( $this->first->dispatch($walker), diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7366Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7366Test.php index 80f5cae723b..1b14467e73d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7366Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7366Test.php @@ -1,5 +1,7 @@ _em->clear(); } - public function testOptimisticLockNoExceptionOnFind() : void + public function testOptimisticLockNoExceptionOnFind(): void { try { $entity = $this->_em->find(GH7366Entity::class, 1, LockMode::OPTIMISTIC); } catch (TransactionRequiredException $e) { self::fail('EntityManager::find() threw TransactionRequiredException with LockMode::OPTIMISTIC'); } + self::assertEquals('baz', $entity->getName()); } } @@ -62,7 +62,6 @@ class GH7366Entity */ protected $name; - public function __construct(string $name) { $this->name = $name; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7496WithToIterableTest.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7496WithToIterableTest.php index 05fb0454e8e..b70aafeea00 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7496WithToIterableTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7496WithToIterableTest.php @@ -10,7 +10,7 @@ final class GH7496WithToIterableTest extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { parent::setUp(); @@ -32,7 +32,7 @@ protected function setUp() : void $this->_em->clear(); } - public function testNonUniqueObjectHydrationDuringIteration() : void + public function testNonUniqueObjectHydrationDuringIteration(): void { $q = $this->_em->createQuery( 'SELECT b FROM ' . GH7496EntityAinB::class . ' aib JOIN ' . GH7496EntityB::class . ' b WITH aib.eB = b' diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7505Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7505Test.php index 2537c461035..973b476fcd8 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7505Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7505Test.php @@ -6,15 +6,14 @@ use Doctrine\Tests\OrmFunctionalTestCase; +use function assert; + /** * @group GH7505 */ final class GH7505Test extends OrmFunctionalTestCase { - /** - * {@inheritDoc} - */ - protected function setUp() : void + protected function setUp(): void { parent::setUp(); @@ -25,7 +24,7 @@ protected function setUp() : void ]); } - public function testSimpleArrayTypeHydratedCorrectly() : void + public function testSimpleArrayTypeHydratedCorrectly(): void { $arrayResponse = new GH7505ArrayResponse(); $this->_em->persist($arrayResponse); @@ -38,12 +37,12 @@ public function testSimpleArrayTypeHydratedCorrectly() : void $repository = $this->_em->getRepository(GH7505AbstractResponse::class); - /** @var GH7505ArrayResponse $arrayResponse */ $arrayResponse = $repository->find($arrayResponse->id); + assert($arrayResponse instanceof GH7505ArrayResponse); self::assertSame([], $arrayResponse->value); - /** @var GH7505TextResponse $textResponse */ $textResponse = $repository->find($textResponse->id); + assert($textResponse instanceof GH7505TextResponse); self::assertNull($textResponse->value); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7629Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7629Test.php index 25dfa946804..3ae31f14f85 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7629Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7629Test.php @@ -1,15 +1,14 @@ _em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { $this->markTestSkipped('Platform does not support foreign keys.'); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7735Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7735Test.php index a9cdc102678..44a5592c9aa 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7735Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7735Test.php @@ -5,11 +5,12 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; use Doctrine\Tests\OrmFunctionalTestCase; + use function assert; final class GH7735Test extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { $this->enableSecondLevelCache(); parent::setUp(); @@ -31,7 +32,7 @@ protected function setUp() : void * @test * @group GH7735 */ - public function findByReturnsCachedEntity() : void + public function findByReturnsCachedEntity(): void { $this->_em->getCache()->evictEntityRegion(GH7735Power::class); @@ -69,12 +70,12 @@ public function __construct(int $id, GH7735Engine $engine) $this->engine = $engine; } - public function getId() : int + public function getId(): int { return $this->id; } - public function getEngine() : GH7735Engine + public function getEngine(): GH7735Engine { return $this->engine; } @@ -115,17 +116,17 @@ public function __construct(int $id, string $model, GH7735Power $power) $power->setEngine($this); } - public function getId() : int + public function getId(): int { return $this->id; } - public function getPower() : GH7735Power + public function getPower(): GH7735Power { return $this->power; } - public function getModel() : string + public function getModel(): string { return $this->model; } @@ -155,17 +156,17 @@ public function __construct(int $id) $this->id = $id; } - public function getId() : int + public function getId(): int { return $this->id; } - public function setEngine(GH7735Engine $engine) : void + public function setEngine(GH7735Engine $engine): void { $this->engine = $engine; } - public function getEngine() : GH7735Engine + public function getEngine(): GH7735Engine { return $this->engine; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7737Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7737Test.php index 8101488a980..16983a976d6 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7737Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7737Test.php @@ -13,7 +13,7 @@ */ class GH7737Test extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { parent::setUp(); @@ -33,7 +33,7 @@ protected function setUp() : void /** * @test */ - public function memberOfCriteriaShouldBeCompatibleWithQueryBuilder() : void + public function memberOfCriteriaShouldBeCompatibleWithQueryBuilder(): void { $query = $this->_em->createQueryBuilder() ->select('person') diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7761Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7761Test.php index fcf3e3be7d2..36b18ec4bc0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7761Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7761Test.php @@ -7,12 +7,11 @@ use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Tests\OrmFunctionalTestCase; +use function assert; + final class GH7761Test extends OrmFunctionalTestCase { - /** - * {@inheritDoc} - */ - protected function setUp() : void + protected function setUp(): void { parent::setUp(); @@ -31,10 +30,10 @@ protected function setUp() : void $this->_em->clear(); } - public function testCollectionClearDoesNotClearIfNotPersisted() : void + public function testCollectionClearDoesNotClearIfNotPersisted(): void { - /** @var GH7761Entity $entity */ $entity = $this->_em->find(GH7761Entity::class, 1); + assert($entity instanceof GH7761Entity); $entity->children->clear(); $this->_em->persist(new GH7761Entity()); $this->_em->flush(); @@ -48,10 +47,10 @@ public function testCollectionClearDoesNotClearIfNotPersisted() : void /** * @group GH-7862 */ - public function testCollectionClearDoesClearIfPersisted() : void + public function testCollectionClearDoesClearIfPersisted(): void { - /** @var GH7761Entity $entity */ $entity = $this->_em->find(GH7761Entity::class, 1); + assert($entity instanceof GH7761Entity); $entity->children->clear(); $this->_em->persist($entity); $this->_em->flush(); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7767Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7767Test.php index 01f12f32159..e760ca7edf9 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7767Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7767Test.php @@ -7,6 +7,7 @@ use Doctrine\Common\Collections\Criteria; use Doctrine\ORM\PersistentCollection; use Doctrine\Tests\OrmFunctionalTestCase; + use function assert; /** @@ -14,7 +15,7 @@ */ class GH7767Test extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { parent::setUp(); @@ -30,7 +31,7 @@ protected function setUp() : void $this->_em->clear(); } - public function testMatchingRespectsCollectionOrdering() : void + public function testMatchingRespectsCollectionOrdering(): void { $parent = $this->_em->find(GH7767ParentEntity::class, 1); assert($parent instanceof GH7767ParentEntity); @@ -42,7 +43,7 @@ public function testMatchingRespectsCollectionOrdering() : void self::assertEquals(300, $children[2]->position); } - public function testMatchingOverrulesCollectionOrdering() : void + public function testMatchingOverrulesCollectionOrdering(): void { $parent = $this->_em->find(GH7767ParentEntity::class, 1); assert($parent instanceof GH7767ParentEntity); @@ -73,12 +74,12 @@ class GH7767ParentEntity */ private $children; - public function addChild(int $position) : void + public function addChild(int $position): void { $this->children[] = new GH7767ChildEntity($this, $position); } - public function getChildren() : PersistentCollection + public function getChildren(): PersistentCollection { return $this->children; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7820Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7820Test.php index 11110e5a73e..3b765321952 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7820Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7820Test.php @@ -11,6 +11,7 @@ use Doctrine\DBAL\Types\Type; use Doctrine\ORM\Tools\Pagination\Paginator; use Doctrine\Tests\OrmFunctionalTestCase; + use function array_map; use function assert; use function is_string; @@ -45,7 +46,7 @@ class GH7820Test extends OrmFunctionalTestCase 'Don\'t know, don\'t know, don\'t know...', ]; - protected function setUp() : void + protected function setUp(): void { parent::setUp(); @@ -65,7 +66,7 @@ protected function setUp() : void $this->_em->flush(); } - public function testWillFindSongsInPaginator() : void + public function testWillFindSongsInPaginator(): void { $query = $this->_em->getRepository(GH7820Line::class) ->createQueryBuilder('l') @@ -73,14 +74,14 @@ public function testWillFindSongsInPaginator() : void self::assertSame( self::SONG, - array_map(static function (GH7820Line $line) : string { + array_map(static function (GH7820Line $line): string { return $line->toString(); }, iterator_to_array(new Paginator($query))) ); } /** @group GH7837 */ - public function testWillFindSongsInPaginatorEvenWithCachedQueryParsing() : void + public function testWillFindSongsInPaginatorEvenWithCachedQueryParsing(): void { $cache = $this->_em->getConfiguration() ->getQueryCacheImpl(); @@ -95,7 +96,7 @@ public function testWillFindSongsInPaginatorEvenWithCachedQueryParsing() : void self::assertSame( self::SONG, - array_map(static function (GH7820Line $line) : string { + array_map(static function (GH7820Line $line): string { return $line->toString(); }, iterator_to_array(new Paginator($query))), 'Expected to return expected data before query cache is populated with DQL -> SQL translation. Were SQL parameters translated?' @@ -107,7 +108,7 @@ public function testWillFindSongsInPaginatorEvenWithCachedQueryParsing() : void self::assertSame( self::SONG, - array_map(static function (GH7820Line $line) : string { + array_map(static function (GH7820Line $line): string { return $line->toString(); }, iterator_to_array(new Paginator($query))), 'Expected to return expected data even when DQL -> SQL translation is present in cache. Were SQL parameters translated again?' @@ -137,7 +138,7 @@ public function __construct(GH7820LineText $text, int $index) $this->lineNumber = $index; } - public function toString() : string + public function toString(): string { return $this->text->getText(); } @@ -153,17 +154,17 @@ private function __construct(string $text) $this->text = $text; } - public static function fromText(string $text) : self + public static function fromText(string $text): self { return new self($text); } - public function getText() : string + public function getText(): string { return $this->text; } - public function __toString() : string + public function __toString(): string { return 'Line: ' . $this->text; } @@ -192,7 +193,7 @@ public function convertToDatabaseValue($value, AbstractPlatform $platform) } /** {@inheritdoc} */ - public function getName() : string + public function getName(): string { return self::class; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7829Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7829Test.php index 88a4b018859..c3f9d7bec90 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7829Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7829Test.php @@ -17,7 +17,7 @@ final class GH7829Test extends OrmFunctionalTestCase /** @var DebugStack */ private $logger; - protected function setUp() : void + protected function setUp(): void { $this->useModelSet('cms'); parent::setUp(); @@ -34,7 +34,7 @@ protected function setUp() : void $this->_em->getConnection()->getConfiguration()->setSQLLogger($this->logger = new DebugStack()); } - public function testPaginatorWithLimitSubquery() : void + public function testPaginatorWithLimitSubquery(): void { $query = $this->_em->createQuery('SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a'); $query->setMaxResults(1); @@ -48,7 +48,7 @@ public function testPaginatorWithLimitSubquery() : void $this->assertCount(3, $this->logger->queries); } - public function testPaginatorWithLimitSubquerySkipped() : void + public function testPaginatorWithLimitSubquerySkipped(): void { $query = $this->_em->createQuery('SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a'); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7836Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7836Test.php index ab1ceeb7297..7c913c3efc4 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7836Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7836Test.php @@ -7,6 +7,7 @@ use Doctrine\Common\Collections\Criteria; use Doctrine\ORM\PersistentCollection; use Doctrine\Tests\OrmFunctionalTestCase; + use function assert; /** @@ -14,7 +15,7 @@ */ class GH7836Test extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { parent::setUp(); @@ -30,7 +31,7 @@ protected function setUp() : void $this->_em->clear(); } - public function testMatchingRespectsCollectionOrdering() : void + public function testMatchingRespectsCollectionOrdering(): void { $parent = $this->_em->find(GH7836ParentEntity::class, 1); assert($parent instanceof GH7836ParentEntity); @@ -45,7 +46,7 @@ public function testMatchingRespectsCollectionOrdering() : void self::assertSame('baz', $children[2]->name); } - public function testMatchingOverrulesCollectionOrdering() : void + public function testMatchingOverrulesCollectionOrdering(): void { $parent = $this->_em->find(GH7836ParentEntity::class, 1); assert($parent instanceof GH7836ParentEntity); @@ -60,7 +61,7 @@ public function testMatchingOverrulesCollectionOrdering() : void self::assertSame('foo', $children[2]->name); } - public function testMatchingKeepsOrderOfCriteriaOrderingKeys() : void + public function testMatchingKeepsOrderOfCriteriaOrderingKeys(): void { $parent = $this->_em->find(GH7836ParentEntity::class, 1); assert($parent instanceof GH7836ParentEntity); @@ -94,12 +95,12 @@ class GH7836ParentEntity */ private $children; - public function addChild(int $position, string $name) : void + public function addChild(int $position, string $name): void { $this->children[] = new GH7836ChildEntity($this, $position, $name); } - public function getChildren() : PersistentCollection + public function getChildren(): PersistentCollection { return $this->children; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7864Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7864Test.php index b4916ffe5bb..b8f9c030d85 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7864Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7864Test.php @@ -6,6 +6,7 @@ use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Tests\OrmFunctionalTestCase; + use function array_values; /** @@ -13,7 +14,7 @@ */ class GH7864Test extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { parent::setUp(); @@ -25,7 +26,7 @@ protected function setUp() : void ); } - public function testExtraLazyRemoveElement() + public function testExtraLazyRemoveElement(): void { $user = new GH7864User(); $user->name = 'test'; @@ -76,7 +77,7 @@ public function __construct() $this->tweets = new ArrayCollection(); } - public function addTweet(GH7864Tweet $tweet) + public function addTweet(GH7864Tweet $tweet): void { $tweet->user = $this; $this->tweets->add($tweet); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7869Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7869Test.php index db16e38967e..58beb5b5b80 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7869Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7869Test.php @@ -17,7 +17,7 @@ */ class GH7869Test extends OrmTestCase { - public function testDQLDeferredEagerLoad() + public function testDQLDeferredEagerLoad(): void { $decoratedEm = EntityManagerMock::create(new ConnectionMock([], new DriverMock())); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7875Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7875Test.php index 41fbaabdd85..e5bfc1a1fd5 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7875Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7875Test.php @@ -8,6 +8,7 @@ use Doctrine\DBAL\Platforms\PostgreSqlPlatform; use Doctrine\ORM\Tools\SchemaTool; use Doctrine\Tests\OrmFunctionalTestCase; + use function array_filter; use function current; use function method_exists; @@ -18,7 +19,7 @@ final class GH7875Test extends OrmFunctionalTestCase { /** @after */ - public function cleanUpSchema() : void + public function cleanUpSchema(): void { $connection = $this->_em->getConnection(); @@ -36,14 +37,14 @@ public function cleanUpSchema() : void * * @return string[] */ - private function filterCreateTable(array $sqls, string $tableName) : array + private function filterCreateTable(array $sqls, string $tableName): array { - return array_filter($sqls, static function (string $sql) use ($tableName) : bool { + return array_filter($sqls, static function (string $sql) use ($tableName): bool { return strpos($sql, sprintf('CREATE TABLE %s (', $tableName)) === 0; }); } - public function testUpdateSchemaSql() : void + public function testUpdateSchemaSql(): void { $classes = [$this->_em->getClassMetadata(GH7875MyEntity::class)]; @@ -54,7 +55,7 @@ public function testUpdateSchemaSql() : void $this->_em->getConnection()->exec(current($sqls)); - $sqls = array_filter($tool->getUpdateSchemaSql($classes), static function (string $sql) : bool { + $sqls = array_filter($tool->getUpdateSchemaSql($classes), static function (string $sql): bool { return strpos($sql, ' gh7875_my_entity ') !== false; }); @@ -71,13 +72,13 @@ public function testUpdateSchemaSql() : void /** * @return array> */ - public function provideUpdateSchemaSqlWithSchemaAssetFilter() : array + public function provideUpdateSchemaSqlWithSchemaAssetFilter(): array { return [ ['/^(?!my_enti)/', null], [ null, - static function ($assetName) : bool { + static function ($assetName): bool { return $assetName !== 'gh7875_my_entity'; }, ], @@ -85,7 +86,7 @@ static function ($assetName) : bool { } /** @dataProvider provideUpdateSchemaSqlWithSchemaAssetFilter */ - public function testUpdateSchemaSqlWithSchemaAssetFilter(?string $filterRegex, ?callable $filterCallback) : void + public function testUpdateSchemaSqlWithSchemaAssetFilter(?string $filterRegex, ?callable $filterCallback): void { if ($filterRegex && ! method_exists(Configuration::class, 'setFilterSchemaAssetsExpression')) { self::markTestSkipped(sprintf('Test require %s::setFilterSchemaAssetsExpression method', Configuration::class)); @@ -106,7 +107,7 @@ public function testUpdateSchemaSqlWithSchemaAssetFilter(?string $filterRegex, ? $previousFilter = $config->getSchemaAssetsFilter(); $sqls = $tool->getUpdateSchemaSql($classes); - $sqls = array_filter($sqls, static function (string $sql) : bool { + $sqls = array_filter($sqls, static function (string $sql): bool { return strpos($sql, ' gh7875_my_entity ') !== false; }); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7941Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7941Test.php index 0e7450701d8..ca6d4f5cbe6 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7941Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7941Test.php @@ -6,6 +6,7 @@ use DateTimeImmutable; use Doctrine\Tests\OrmFunctionalTestCase; + use function ltrim; use function strlen; @@ -21,7 +22,7 @@ final class GH7941Test extends OrmFunctionalTestCase ['name' => 'Test 6', 'price' => '-25', 'square_root' => '/^5(\.0+)?$/'], ]; - protected function setUp() : void + protected function setUp(): void { parent::setUp(); @@ -36,7 +37,7 @@ protected function setUp() : void } /** @test */ - public function typesShouldBeConvertedForDQLFunctions() : void + public function typesShouldBeConvertedForDQLFunctions(): void { $query = $this->_em->createQuery( 'SELECT diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH8055Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH8055Test.php index cb48fac4f88..b8443f30573 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH8055Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH8055Test.php @@ -11,10 +11,7 @@ */ final class GH8055Test extends OrmFunctionalTestCase { - /** - * {@inheritDoc} - */ - protected function setUp() : void + protected function setUp(): void { parent::setUp(); @@ -24,7 +21,7 @@ protected function setUp() : void ]); } - public function testNumericDescriminatorColumn() : void + public function testNumericDescriminatorColumn(): void { $entity = new GH8055SubClass(); $entity->value = 'test'; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH8061Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH8061Test.php index ed4f8f5a7b1..1f66f435ccd 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH8061Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH8061Test.php @@ -7,6 +7,7 @@ use Doctrine\DBAL\Platforms\AbstractPlatform; use Doctrine\DBAL\Types\Type; use Doctrine\Tests\OrmTestCase; + use function sprintf; /** @@ -14,12 +15,12 @@ */ final class GH8061Test extends OrmTestCase { - public static function setUpBeforeClass() : void + public static function setUpBeforeClass(): void { Type::addType('GH8061Type', GH8061Type::class); } - public function testConvertToPHPValueSQLForNewObjectExpression() : void + public function testConvertToPHPValueSQLForNewObjectExpression(): void { $dql = 'SELECT NEW ' . GH8061Class::class . '(e.field) FROM ' . GH8061Entity::class . ' e'; $entityManager = $this->_getTestEntityManager(); @@ -43,22 +44,22 @@ final class GH8061Entity final class GH8061Type extends Type { - public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform) : string + public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform): string { return $platform->getVarcharTypeDeclarationSQL($fieldDeclaration); } - public function getName() : string + public function getName(): string { return 'GH8061'; } - public function canRequireSQLConversion() : bool + public function canRequireSQLConversion(): bool { return true; } - public function convertToPHPValueSQL($sqlExpr, $platform) : string + public function convertToPHPValueSQL($sqlExpr, $platform): string { return sprintf('DatabaseFunction(%s)', $sqlExpr); } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/Issue5989Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/Issue5989Test.php index b9007ce4431..b00cd680f75 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/Issue5989Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/Issue5989Test.php @@ -1,39 +1,42 @@ useModelSet('issue5989'); parent::setUp(); } - public function testSimpleArrayTypeHydratedCorrectlyInJoinedInheritance() + public function testSimpleArrayTypeHydratedCorrectlyInJoinedInheritance(): void { $manager = new Issue5989Manager(); - $managerTags = ['tag1', 'tag2']; + $managerTags = ['tag1', 'tag2']; $manager->tags = $managerTags; $this->_em->persist($manager); $employee = new Issue5989Employee(); - $employeeTags =['tag2', 'tag3']; + $employeeTags = ['tag2', 'tag3']; $employee->tags = $employeeTags; $this->_em->persist($employee); $this->_em->flush(); - $managerId = $manager->id; + $managerId = $manager->id; $employeeId = $employee->id; // clear entity manager so that $repository->find actually fetches them and uses the hydrator @@ -42,7 +45,7 @@ public function testSimpleArrayTypeHydratedCorrectlyInJoinedInheritance() $repository = $this->_em->getRepository(Issue5989Person::class); - $manager = $repository->find($managerId); + $manager = $repository->find($managerId); $employee = $repository->find($employeeId); static::assertEquals($managerTags, $manager->tags); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket2481Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket2481Test.php index ebaa71f840f..301efa0e94e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket2481Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket2481Test.php @@ -1,26 +1,32 @@ _schemaTool->createSchema( [ - $this->_em->getClassMetadata(Ticket2481Product::class) + $this->_em->getClassMetadata(Ticket2481Product::class), ] ); - } catch (\Exception $e) { + } catch (Exception $e) { // Swallow all exceptions. We do not test the schema tool here. } + $this->_conn = $this->_em->getConnection(); } - public function testEmptyInsert() + public function testEmptyInsert(): void { $test = new Ticket2481Product(); $this->_em->persist($test); @@ -40,5 +46,5 @@ class Ticket2481Product * @Id @Column(type="integer") * @GeneratedValue(strategy="AUTO") */ - public $id; + public $id; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfAbstractTest.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfAbstractTest.php index eaee1aae59e..9b53457d34c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfAbstractTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfAbstractTest.php @@ -1,12 +1,14 @@ _em->persist(new EmployeeTicket4646Abstract()); $this->_em->flush(); - $dql = 'SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\PersonTicket4646Abstract p + $dql = 'SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\PersonTicket4646Abstract p WHERE p INSTANCE OF Doctrine\Tests\ORM\Functional\Ticket\PersonTicket4646Abstract'; - $query = $this->_em->createQuery($dql); + $query = $this->_em->createQuery($dql); $result = $query->getResult(); self::assertCount(1, $result); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfMultiLevelTest.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfMultiLevelTest.php index 6f4e591ebae..aea0f5cd13c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfMultiLevelTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfMultiLevelTest.php @@ -1,12 +1,14 @@ _em->persist(new EngineerTicket4646MultiLevel()); $this->_em->flush(); - $dql = 'SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\PersonTicket4646MultiLevel p + $dql = 'SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\PersonTicket4646MultiLevel p WHERE p INSTANCE OF Doctrine\Tests\ORM\Functional\Ticket\PersonTicket4646MultiLevel'; - $query = $this->_em->createQuery($dql); + $query = $this->_em->createQuery($dql); $result = $query->getResult(); self::assertCount(3, $result); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfParametricTest.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfParametricTest.php index 1f92cb02cc0..d592e15aa76 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfParametricTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfParametricTest.php @@ -1,12 +1,14 @@ _schemaTool->createSchema([ @@ -20,7 +22,7 @@ public function testInstanceOf(): void $this->_em->persist(new PersonTicket4646Parametric()); $this->_em->persist(new EmployeeTicket4646Parametric()); $this->_em->flush(); - $dql = 'SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\PersonTicket4646Parametric p + $dql = 'SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\PersonTicket4646Parametric p WHERE p INSTANCE OF :parameter'; $query = $this->_em->createQuery($dql); $query->setParameter( diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfTest.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfTest.php index 7d95270d9ec..cfa02b08c68 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfTest.php @@ -1,12 +1,14 @@ _em->persist(new EmployeeTicket4646()); $this->_em->flush(); - $dql = 'SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\PersonTicket4646 p + $dql = 'SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\PersonTicket4646 p WHERE p INSTANCE OF Doctrine\Tests\ORM\Functional\Ticket\PersonTicket4646'; - $query = $this->_em->createQuery($dql); + $query = $this->_em->createQuery($dql); $result = $query->getResult(); self::assertCount(2, $result); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfWithMultipleParametersTest.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfWithMultipleParametersTest.php index b63b2d9ce3f..d2412af78a6 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfWithMultipleParametersTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfWithMultipleParametersTest.php @@ -1,12 +1,14 @@ _em->persist(new InternTicket4646Multiple()); $this->_em->flush(); - $dql = 'SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\PersonTicket4646Multiple p + $dql = 'SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\PersonTicket4646Multiple p WHERE p INSTANCE OF (Doctrine\Tests\ORM\Functional\Ticket\EmployeeTicket4646Multiple, Doctrine\Tests\ORM\Functional\Ticket\InternTicket4646Multiple)'; - $query = $this->_em->createQuery($dql); + $query = $this->_em->createQuery($dql); $result = $query->getResult(); self::assertCount(2, $result); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket69.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket69.php index 369e326a7f2..057c0afeb51 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket69.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket69.php @@ -1,14 +1,21 @@ _em->getClassMetadata(Lemma::class), $this->_em->getClassMetadata(Relation::class), - $this->_em->getClassMetadata(RelationType::class) + $this->_em->getClassMetadata(RelationType::class), ] ); - } catch (\Exception $e) { + } catch (Exception $e) { // Swallow all exceptions. We do not test the schema tool here. } } - public function testIssue() + public function testIssue(): void { //setup - $lemma1 = new Lemma; + $lemma1 = new Lemma(); $lemma1->setLemma('foo'); - $lemma2 = new Lemma; + $lemma2 = new Lemma(); $lemma2->setLemma('bar'); - $lemma3 = new Lemma; + $lemma3 = new Lemma(); $lemma3->setLemma('batz'); - $lemma4 = new Lemma; + $lemma4 = new Lemma(); $lemma4->setLemma('bla'); - $type1 = new RelationType; + $type1 = new RelationType(); $type1->setType('nonsense'); $type1->setAbbreviation('non'); - $type2 = new RelationType; + $type2 = new RelationType(); $type2->setType('quatsch'); $type2->setAbbreviation('qu'); - $relation1 = new Relation; + $relation1 = new Relation(); $relation1->setParent($lemma1); $relation1->setChild($lemma2); $relation1->setType($type1); - $relation2 = new Relation; + $relation2 = new Relation(); $relation2->setParent($lemma1); $relation2->setChild($lemma3); $relation2->setType($type1); - $relation3 = new Relation; + $relation3 = new Relation(); $relation3->setParent($lemma1); $relation3->setChild($lemma4); $relation3->setType($type2); @@ -79,20 +86,19 @@ public function testIssue() // test One To Many $query = $this->_em->createQuery("SELECT l FROM Doctrine\Tests\ORM\Functional\Ticket\Lemma l Where l.lemma = 'foo'"); - $res = $query->getResult(); + $res = $query->getResult(); $lemma = $res[0]; $this->assertEquals('foo', $lemma->getLemma()); $this->assertInstanceOf(Lemma::class, $lemma); $relations = $lemma->getRelations(); - foreach($relations as $relation) { + foreach ($relations as $relation) { $this->assertInstanceOf(Relation::class, $relation); - $this->assertTrue($relation->getType()->getType() != ''); + $this->assertTrue($relation->getType()->getType() !== ''); } $this->_em->clear(); - } } @@ -100,9 +106,9 @@ public function testIssue() * @Entity * @Table(name="lemma") */ -class Lemma { - - const CLASS_NAME = __CLASS__; +class Lemma +{ + public const CLASS_NAME = self::class; /** * @var int @@ -113,7 +119,6 @@ class Lemma { private $id; /** - * * @var string * @Column(type="string", name="lemma_name", unique=true, length=255) */ @@ -126,79 +131,55 @@ class Lemma { */ private $relations; - public function __construct() { - $this->types = new \Doctrine\Common\Collections\ArrayCollection(); - $this->relations = new \Doctrine\Common\Collections\ArrayCollection(); + public function __construct() + { + $this->types = new ArrayCollection(); + $this->relations = new ArrayCollection(); } - - /** - * - * @return int - */ - public function getId() { + public function getId(): int + { return $this->id; } - /** - * - * @param string $lemma - * @return void - */ - public function setLemma($lemma) { + public function setLemma(string $lemma): void + { $this->lemma = $lemma; } - /** - * - * @return string - */ - public function getLemma() { + public function getLemma(): string + { return $this->lemma; } - - /** - * - * @param Relation $relation - * @return void - */ - public function addRelation(Relation $relation) { + public function addRelation(Relation $relation): void + { $this->relations[] = $relation; $relation->setParent($this); } - /** - * - * @param Relation $relation - * @return void - */ - public function removeRelation(Relation $relation) { - /*@var $removed Relation */ + public function removeRelation(Relation $relation): void + { $removed = $this->relations->removeElement($relation); + assert($removed instanceof Relation); if ($removed !== null) { $removed->removeParent(); } } - /** - * - * @return kateglo\application\utilities\collections\ArrayCollection - */ - public function getRelations() { + public function getRelations(): kateglo\application\utilities\collections\ArrayCollection + { return $this->relations; } - } /** - * * @Entity * @Table(name="relation") */ -class Relation { - - const CLASS_NAME = __CLASS__; +class Relation +{ + public const CLASS_NAME = self::class; /** * @var int @@ -229,78 +210,51 @@ class Relation { */ private $type; - /** - * - * @param Lemma $parent - * @return void - */ - public function setParent(Lemma $parent) { + public function setParent(Lemma $parent): void + { $this->parent = $parent; } - /** - * - * @return Phrase - */ - public function getParent() { + public function getParent(): Phrase + { return $this->parent; } - /** - * - * @return void - */ - public function removeParent() { + public function removeParent(): void + { if ($this->lemma !== null) { - /*@var $phrase Lemma */ - $lemma = $this->parent; + /** @var Lemma $phrase */ + $lemma = $this->parent; $this->parent = null; $lemma->removeRelation($this); } } - /** - * - * @param Lemma $child - * @return void - */ - public function setChild(Lemma $child) { + public function setChild(Lemma $child): void + { $this->child = $child; } - /** - * - * @return Lemma - */ - public function getChild() { + public function getChild(): Lemma + { return $this->child; } - /** - * - * @param RelationType $type - * @return void - */ - public function setType(RelationType $type) { + public function setType(RelationType $type): void + { $this->type = $type; } - /** - * - * @return RelationType - */ - public function getType() { + public function getType(): RelationType + { return $this->type; } - /** - * - * @return void - */ - public function removeType() { + public function removeType(): void + { if ($this->type !== null) { - /*@var $phrase RelationType */ - $type = $this->type; + /** @var RelationType $phrase */ + $type = $this->type; $this->type = null; $type->removeRelation($this); } @@ -308,16 +262,14 @@ public function removeType() { } /** - * * @Entity * @Table(name="relation_type") */ -class RelationType { - - const CLASS_NAME = __CLASS__; +class RelationType +{ + public const CLASS_NAME = self::class; /** - * * @var int * @Id * @Column(type="integer", name="relation_type_id") @@ -326,14 +278,12 @@ class RelationType { private $id; /** - * * @var string * @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) */ @@ -345,81 +295,53 @@ class RelationType { */ private $relations; - public function __construct() { - $relations = new \Doctrine\Common\Collections\ArrayCollection(); + public function __construct() + { + $relations = new ArrayCollection(); } - /** - * - * @return int - */ - public function getId() { + public function getId(): int + { return $this->id; } - /** - * - * @param string $type - * @return void - */ - public function setType($type) { + public function setType(string $type): void + { $this->type = $type; } - /** - * - * @return string - */ - public function getType() { + public function getType(): string + { return $this->type; } - /** - * - * @param string $abbreviation - * @return void - */ - public function setAbbreviation($abbreviation) { + public function setAbbreviation(string $abbreviation): void + { $this->abbreviation = $abbreviation; } - /** - * - * @return string - */ - public function getAbbreviation() { + public function getAbbreviation(): string + { return $this->abbreviation; } - /** - * - * @param Relation $relation - * @return void - */ - public function addRelation(Relation $relation) { + public function addRelation(Relation $relation): void + { $this->relations[] = $relation; $relation->setType($this); } - /** - * - * @param Relation $relation - * @return void - */ - public function removeRelation(Relation $relation) { - /*@var $removed Relation */ + public function removeRelation(Relation $relation): void + { $removed = $this->relations->removeElement($relation); + assert($removed instanceof Relation); if ($removed !== null) { $removed->removeLemma(); } } - /** - * - * @return kateglo\application\utilities\collections\ArrayCollection - */ - public function getRelations() { + public function getRelations(): kateglo\application\utilities\collections\ArrayCollection + { return $this->relations; } } - diff --git a/tests/Doctrine/Tests/ORM/Functional/TypeTest.php b/tests/Doctrine/Tests/ORM/Functional/TypeTest.php index 0771e30da4e..b06675e013e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/TypeTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/TypeTest.php @@ -1,35 +1,39 @@ useModelSet('generic'); parent::setUp(); } - public function testDecimal() + public function testDecimal(): void { - $decimal = new DecimalModel(); - $decimal->decimal = 0.15; + $decimal = new DecimalModel(); + $decimal->decimal = 0.15; $decimal->highScale = 0.1515; $this->_em->persist($decimal); $this->_em->flush(); $this->_em->clear(); - $dql = 'SELECT d FROM ' . DecimalModel::class . ' d'; + $dql = 'SELECT d FROM ' . DecimalModel::class . ' d'; $decimal = $this->_em->createQuery($dql)->getSingleResult(); $this->assertSame('0.15', $decimal->decimal); @@ -38,18 +42,17 @@ public function testDecimal() /** * @group DDC-1394 - * @return void */ - public function testBoolean() + public function testBoolean(): void { - $bool = new BooleanModel(); + $bool = new BooleanModel(); $bool->booleanField = true; $this->_em->persist($bool); $this->_em->flush(); $this->_em->clear(); - $dql = 'SELECT b FROM ' . BooleanModel::class . ' b WHERE b.booleanField = true'; + $dql = 'SELECT b FROM ' . BooleanModel::class . ' b WHERE b.booleanField = true'; $bool = $this->_em->createQuery($dql)->getSingleResult(); $this->assertTrue($bool->booleanField); @@ -59,47 +62,47 @@ public function testBoolean() $this->_em->flush(); $this->_em->clear(); - $dql = 'SELECT b FROM ' . BooleanModel::class . ' b WHERE b.booleanField = false'; + $dql = 'SELECT b FROM ' . BooleanModel::class . ' b WHERE b.booleanField = false'; $bool = $this->_em->createQuery($dql)->getSingleResult(); $this->assertFalse($bool->booleanField); } - public function testArray() + public function testArray(): void { - $serialize = new SerializationModel(); - $serialize->array["foo"] = "bar"; - $serialize->array["bar"] = "baz"; + $serialize = new SerializationModel(); + $serialize->array['foo'] = 'bar'; + $serialize->array['bar'] = 'baz'; $this->_em->persist($serialize); $this->_em->flush(); $this->_em->clear(); - $dql = 'SELECT s FROM ' . SerializationModel::class . ' s'; + $dql = 'SELECT s FROM ' . SerializationModel::class . ' s'; $serialize = $this->_em->createQuery($dql)->getSingleResult(); - $this->assertSame(["foo" => "bar", "bar" => "baz"], $serialize->array); + $this->assertSame(['foo' => 'bar', 'bar' => 'baz'], $serialize->array); } - public function testObject() + public function testObject(): void { - $serialize = new SerializationModel(); - $serialize->object = new \stdClass(); + $serialize = new SerializationModel(); + $serialize->object = new stdClass(); $this->_em->persist($serialize); $this->_em->flush(); $this->_em->clear(); - $dql = 'SELECT s FROM ' . SerializationModel::class . ' s'; + $dql = 'SELECT s FROM ' . SerializationModel::class . ' s'; $serialize = $this->_em->createQuery($dql)->getSingleResult(); $this->assertInstanceOf('stdClass', $serialize->object); } - public function testDate() + public function testDate(): void { - $dateTime = new DateTimeModel(); - $dateTime->date = new \DateTime('2009-10-01', new \DateTimeZone('Europe/Berlin')); + $dateTime = new DateTimeModel(); + $dateTime->date = new DateTime('2009-10-01', new DateTimeZone('Europe/Berlin')); $this->_em->persist($dateTime); $this->_em->flush(); @@ -107,14 +110,14 @@ public function testDate() $dateTimeDb = $this->_em->find(DateTimeModel::class, $dateTime->id); - $this->assertInstanceOf(\DateTime::class, $dateTimeDb->date); + $this->assertInstanceOf(DateTime::class, $dateTimeDb->date); $this->assertSame('2009-10-01', $dateTimeDb->date->format('Y-m-d')); } - public function testDateTime() + public function testDateTime(): void { - $dateTime = new DateTimeModel(); - $dateTime->datetime = new \DateTime('2009-10-02 20:10:52', new \DateTimeZone('Europe/Berlin')); + $dateTime = new DateTimeModel(); + $dateTime->datetime = new DateTime('2009-10-02 20:10:52', new DateTimeZone('Europe/Berlin')); $this->_em->persist($dateTime); $this->_em->flush(); @@ -122,20 +125,20 @@ public function testDateTime() $dateTimeDb = $this->_em->find(DateTimeModel::class, $dateTime->id); - $this->assertInstanceOf(\DateTime::class, $dateTimeDb->datetime); + $this->assertInstanceOf(DateTime::class, $dateTimeDb->datetime); $this->assertSame('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()]); + ->findBy(['datetime' => new DateTime()]); $this->assertEmpty($articles); } - public function testDqlQueryBindDateTimeInstance() + public function testDqlQueryBindDateTimeInstance(): void { - $date = new \DateTime('2009-10-02 20:10:52', new \DateTimeZone('Europe/Berlin')); + $date = new DateTime('2009-10-02 20:10:52', new DateTimeZone('Europe/Berlin')); - $dateTime = new DateTimeModel(); + $dateTime = new DateTimeModel(); $dateTime->datetime = $date; $this->_em->persist($dateTime); @@ -146,15 +149,15 @@ public function testDqlQueryBindDateTimeInstance() ->setParameter(1, $date, DBALType::DATETIME) ->getSingleResult(); - $this->assertInstanceOf(\DateTime::class, $dateTimeDb->datetime); + $this->assertInstanceOf(DateTime::class, $dateTimeDb->datetime); $this->assertSame('2009-10-02 20:10:52', $dateTimeDb->datetime->format('Y-m-d H:i:s')); } - public function testDqlQueryBuilderBindDateTimeInstance() + public function testDqlQueryBuilderBindDateTimeInstance(): void { - $date = new \DateTime('2009-10-02 20:10:52', new \DateTimeZone('Europe/Berlin')); + $date = new DateTime('2009-10-02 20:10:52', new DateTimeZone('Europe/Berlin')); - $dateTime = new DateTimeModel(); + $dateTime = new DateTimeModel(); $dateTime->datetime = $date; $this->_em->persist($dateTime); @@ -168,14 +171,14 @@ public function testDqlQueryBuilderBindDateTimeInstance() ->setParameter(1, $date, DBALType::DATETIME) ->getQuery()->getSingleResult(); - $this->assertInstanceOf(\DateTime::class, $dateTimeDb->datetime); + $this->assertInstanceOf(DateTime::class, $dateTimeDb->datetime); $this->assertSame('2009-10-02 20:10:52', $dateTimeDb->datetime->format('Y-m-d H:i:s')); } - public function testTime() + public function testTime(): void { - $dateTime = new DateTimeModel(); - $dateTime->time = new \DateTime('2010-01-01 19:27:20'); + $dateTime = new DateTimeModel(); + $dateTime->time = new DateTime('2010-01-01 19:27:20'); $this->_em->persist($dateTime); $this->_em->flush(); @@ -183,7 +186,7 @@ public function testTime() $dateTimeDb = $this->_em->find(DateTimeModel::class, $dateTime->id); - $this->assertInstanceOf(\DateTime::class, $dateTimeDb->time); + $this->assertInstanceOf(DateTime::class, $dateTimeDb->time); $this->assertSame('19:27:20', $dateTimeDb->time->format('H:i:s')); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/TypeValueSqlTest.php b/tests/Doctrine/Tests/ORM/Functional/TypeValueSqlTest.php index b51d5a133f1..086cbe79ab2 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); @@ -45,18 +49,17 @@ public function testUpperCaseStringType() $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'); + $this->assertEquals('FOO', $this->_em->getConnection()->fetchColumn('select lowerCaseString from customtype_uppercases where id=' . $entity->id . ''), 'Database holds uppercase string'); } /** * @group DDC-1642 */ - public function testUpperCaseStringTypeWhenColumnNameIsDefined() + public function testUpperCaseStringTypeWhenColumnNameIsDefined(): void { - - $entity = new CustomTypeUpperCase(); - $entity->lowerCaseString = 'Some Value'; - $entity->namedLowerCaseString = 'foo'; + $entity = new CustomTypeUpperCase(); + $entity->lowerCaseString = 'Some Value'; + $entity->namedLowerCaseString = 'foo'; $this->_em->persist($entity); $this->_em->flush(); @@ -67,10 +70,9 @@ public function testUpperCaseStringTypeWhenColumnNameIsDefined() $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'); + $this->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'; + $entity->namedLowerCaseString = 'bar'; $this->_em->persist($entity); $this->_em->flush(); @@ -79,17 +81,16 @@ public function testUpperCaseStringTypeWhenColumnNameIsDefined() $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'); + $this->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() + public function testTypeValueSqlWithAssociations(): void { - $parent = new CustomTypeParent(); + $parent = new CustomTypeParent(); $parent->customInteger = -1; - $parent->child = new CustomTypeChild(); + $parent->child = new CustomTypeChild(); $friend1 = new CustomTypeParent(); $friend2 = new CustomTypeParent(); @@ -109,17 +110,17 @@ public function testTypeValueSqlWithAssociations() $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'); + $this->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'); } - public function testSelectDQL() + public function testSelectDQL(): void { - $parent = new CustomTypeParent(); + $parent = new CustomTypeParent(); $parent->customInteger = -1; - $parent->child = new CustomTypeChild(); + $parent->child = new CustomTypeChild(); $this->_em->persist($parent); $this->_em->flush(); @@ -128,7 +129,7 @@ public function testSelectDQL() $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(); diff --git a/tests/Doctrine/Tests/ORM/Functional/UUIDGeneratorTest.php b/tests/Doctrine/Tests/ORM/Functional/UUIDGeneratorTest.php index 258bd4188b2..76faf772b86 100644 --- a/tests/Doctrine/Tests/ORM/Functional/UUIDGeneratorTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/UUIDGeneratorTest.php @@ -1,28 +1,34 @@ _em->getConnection()->getDatabasePlatform()->getName() != 'mysql') { + if ($this->_em->getConnection()->getDatabasePlatform()->getName() !== 'mysql') { $this->markTestSkipped('Currently restricted to MySQL platform.'); } $this->_schemaTool->createSchema( [ - $this->_em->getClassMetadata(UUIDEntity::class) + $this->_em->getClassMetadata(UUIDEntity::class), ] ); } - public function testGenerateUUID() + public function testGenerateUUID(): void { $entity = new UUIDEntity(); @@ -39,12 +45,13 @@ class UUIDEntity { /** @Id @Column(type="string") @GeneratedValue(strategy="UUID") */ private $id; + /** * Get id. * * @return id. */ - public function getId() + public function getId(): id { return $this->id; } diff --git a/tests/Doctrine/Tests/ORM/Functional/UnitOfWorkLifecycleTest.php b/tests/Doctrine/Tests/ORM/Functional/UnitOfWorkLifecycleTest.php index 2688d178183..d85cf3d2a69 100644 --- a/tests/Doctrine/Tests/ORM/Functional/UnitOfWorkLifecycleTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/UnitOfWorkLifecycleTest.php @@ -1,5 +1,7 @@ useModelSet('cms'); parent::setUp(); } - public function testScheduleInsertManaged() + public function testScheduleInsertManaged(): void { - $user = new CmsUser(); - $user->username = "beberlei"; - $user->name = "Benjamin"; - $user->status = "active"; + $user = new CmsUser(); + $user->username = 'beberlei'; + $user->name = 'Benjamin'; + $user->status = 'active'; $this->_em->persist($user); $this->_em->flush(); @@ -29,12 +31,12 @@ public function testScheduleInsertManaged() $this->_em->getUnitOfWork()->scheduleForInsert($user); } - public function testScheduleInsertDeleted() + public function testScheduleInsertDeleted(): void { - $user = new CmsUser(); - $user->username = "beberlei"; - $user->name = "Benjamin"; - $user->status = "active"; + $user = new CmsUser(); + $user->username = 'beberlei'; + $user->name = 'Benjamin'; + $user->status = 'active'; $this->_em->persist($user); $this->_em->flush(); @@ -46,12 +48,12 @@ public function testScheduleInsertDeleted() $this->_em->getUnitOfWork()->scheduleForInsert($user); } - public function testScheduleInsertTwice() + public function testScheduleInsertTwice(): void { - $user = new CmsUser(); - $user->username = "beberlei"; - $user->name = "Benjamin"; - $user->status = "active"; + $user = new CmsUser(); + $user->username = 'beberlei'; + $user->name = 'Benjamin'; + $user->status = 'active'; $this->_em->getUnitOfWork()->scheduleForInsert($user); @@ -61,7 +63,7 @@ public function testScheduleInsertTwice() $this->_em->getUnitOfWork()->scheduleForInsert($user); } - public function testAddToIdentityMapWithoutIdentity() + public function testAddToIdentityMapWithoutIdentity(): void { $user = new CmsUser(); @@ -71,7 +73,7 @@ public function testAddToIdentityMapWithoutIdentity() $this->_em->getUnitOfWork()->registerManaged($user, [], []); } - public function testMarkReadOnlyNonManaged() + public function testMarkReadOnlyNonManaged(): void { $user = new CmsUser(); diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyCompositeIdForeignKeyTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyCompositeIdForeignKeyTest.php index e314e8172e7..226aa785167 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyCompositeIdForeignKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyCompositeIdForeignKeyTest.php @@ -1,5 +1,7 @@ useModelSet('vct_manytomany_compositeid_foreignkey'); parent::setUp(); - $auxiliary = new Entity\AuxiliaryEntity(); + $auxiliary = new Entity\AuxiliaryEntity(); $auxiliary->id4 = 'abc'; - $inversed = new Entity\InversedManyToManyCompositeIdForeignKeyEntity(); - $inversed->id1 = 'def'; + $inversed = new Entity\InversedManyToManyCompositeIdForeignKeyEntity(); + $inversed->id1 = 'def'; $inversed->foreignEntity = $auxiliary; - $owning = new Entity\OwningManyToManyCompositeIdForeignKeyEntity(); + $owning = new Entity\OwningManyToManyCompositeIdForeignKeyEntity(); $owning->id2 = 'ghi'; $inversed->associatedEntities->add($owning); @@ -44,7 +46,7 @@ protected function setUp() : void $this->_em->clear(); } - public static function tearDownAfterClass() : void + public static function tearDownAfterClass(): void { $conn = static::$_sharedConn; @@ -54,7 +56,7 @@ public static function tearDownAfterClass() : void $conn->executeUpdate('DROP TABLE vct_auxiliary'); } - public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() + public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase(): void { $conn = $this->_em->getConnection(); @@ -73,7 +75,7 @@ public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() /** * @depends testThatTheValueOfIdentifiersAreConvertedInTheDatabase */ - public function testThatEntitiesAreFetchedFromTheDatabase() + public function testThatEntitiesAreFetchedFromTheDatabase(): void { $auxiliary = $this->_em->find( Models\ValueConversionType\AuxiliaryEntity::class, @@ -98,7 +100,7 @@ public function testThatEntitiesAreFetchedFromTheDatabase() /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() + public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase(): void { $auxiliary = $this->_em->find( Models\ValueConversionType\AuxiliaryEntity::class, @@ -124,7 +126,7 @@ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFr /** * @depends testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase */ - public function testThatInversedEntityIsFetchedFromTheDatabaseUsingAuxiliaryEntityAsId() + public function testThatInversedEntityIsFetchedFromTheDatabaseUsingAuxiliaryEntityAsId(): void { $auxiliary = $this->_em->find( Models\ValueConversionType\AuxiliaryEntity::class, @@ -142,7 +144,7 @@ public function testThatInversedEntityIsFetchedFromTheDatabaseUsingAuxiliaryEnti /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheCollectionFromOwningToInversedIsLoaded() + public function testThatTheCollectionFromOwningToInversedIsLoaded(): void { $owning = $this->_em->find( Models\ValueConversionType\OwningManyToManyCompositeIdForeignKeyEntity::class, @@ -155,7 +157,7 @@ public function testThatTheCollectionFromOwningToInversedIsLoaded() /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheCollectionFromInversedToOwningIsLoaded() + public function testThatTheCollectionFromInversedToOwningIsLoaded(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedManyToManyCompositeIdForeignKeyEntity::class, @@ -169,7 +171,7 @@ public function testThatTheCollectionFromInversedToOwningIsLoaded() * @depends testThatTheCollectionFromOwningToInversedIsLoaded * @depends testThatTheCollectionFromInversedToOwningIsLoaded */ - public function testThatTheJoinTableRowsAreRemovedWhenRemovingTheAssociation() + public function testThatTheJoinTableRowsAreRemovedWhenRemovingTheAssociation(): void { $conn = $this->_em->getConnection(); diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyCompositeIdTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyCompositeIdTest.php index 99bec4a4a50..b723772d7d2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyCompositeIdTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyCompositeIdTest.php @@ -1,5 +1,7 @@ useModelSet('vct_manytomany_compositeid'); parent::setUp(); - $inversed = new Entity\InversedManyToManyCompositeIdEntity(); + $inversed = new Entity\InversedManyToManyCompositeIdEntity(); $inversed->id1 = 'abc'; $inversed->id2 = 'def'; - $owning = new Entity\OwningManyToManyCompositeIdEntity(); + $owning = new Entity\OwningManyToManyCompositeIdEntity(); $owning->id3 = 'ghi'; $inversed->associatedEntities->add($owning); @@ -39,7 +41,7 @@ protected function setUp() : void $this->_em->clear(); } - public static function tearDownAfterClass() : void + public static function tearDownAfterClass(): void { $conn = static::$_sharedConn; @@ -48,7 +50,7 @@ public static function tearDownAfterClass() : void $conn->executeUpdate('DROP TABLE vct_inversed_manytomany_compositeid'); } - public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() + public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase(): void { $conn = $this->_em->getConnection(); @@ -65,7 +67,7 @@ public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() /** * @depends testThatTheValueOfIdentifiersAreConvertedInTheDatabase */ - public function testThatEntitiesAreFetchedFromTheDatabase() + public function testThatEntitiesAreFetchedFromTheDatabase(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedManyToManyCompositeIdEntity::class, @@ -84,7 +86,7 @@ public function testThatEntitiesAreFetchedFromTheDatabase() /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() + public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedManyToManyCompositeIdEntity::class, @@ -104,7 +106,7 @@ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFr /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheCollectionFromOwningToInversedIsLoaded() + public function testThatTheCollectionFromOwningToInversedIsLoaded(): void { $owning = $this->_em->find( Models\ValueConversionType\OwningManyToManyCompositeIdEntity::class, @@ -117,7 +119,7 @@ public function testThatTheCollectionFromOwningToInversedIsLoaded() /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheCollectionFromInversedToOwningIsLoaded() + public function testThatTheCollectionFromInversedToOwningIsLoaded(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedManyToManyCompositeIdEntity::class, @@ -131,7 +133,7 @@ public function testThatTheCollectionFromInversedToOwningIsLoaded() * @depends testThatTheCollectionFromOwningToInversedIsLoaded * @depends testThatTheCollectionFromInversedToOwningIsLoaded */ - public function testThatTheJoinTableRowsAreRemovedWhenRemovingTheAssociation() + public function testThatTheJoinTableRowsAreRemovedWhenRemovingTheAssociation(): void { $conn = $this->_em->getConnection(); diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyExtraLazyTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyExtraLazyTest.php index 06f1c091a0c..651a197a006 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(); + $inversed1 = new Entity\InversedManyToManyExtraLazyEntity(); $inversed1->id1 = 'abc'; - $inversed2 = new Entity\InversedManyToManyExtraLazyEntity(); + $inversed2 = new Entity\InversedManyToManyExtraLazyEntity(); $inversed2->id1 = 'def'; - $owning1 = new Entity\OwningManyToManyExtraLazyEntity(); + $owning1 = new Entity\OwningManyToManyExtraLazyEntity(); $owning1->id2 = 'ghi'; - $owning2 = new Entity\OwningManyToManyExtraLazyEntity(); + $owning2 = new Entity\OwningManyToManyExtraLazyEntity(); $owning2->id2 = 'jkl'; $inversed1->associatedEntities->add($owning1); @@ -53,7 +55,7 @@ protected function setUp() : void $this->_em->clear(); } - public static function tearDownAfterClass() : void + public static function tearDownAfterClass(): void { $conn = static::$_sharedConn; @@ -62,7 +64,7 @@ public static function tearDownAfterClass() : void $conn->executeUpdate('DROP TABLE vct_inversed_manytomany_extralazy'); } - public function testThatTheExtraLazyCollectionFromOwningToInversedIsCounted() + public function testThatTheExtraLazyCollectionFromOwningToInversedIsCounted(): void { $owning = $this->_em->find( Models\ValueConversionType\OwningManyToManyExtraLazyEntity::class, @@ -72,7 +74,7 @@ public function testThatTheExtraLazyCollectionFromOwningToInversedIsCounted() $this->assertEquals(2, $owning->associatedEntities->count()); } - public function testThatTheExtraLazyCollectionFromInversedToOwningIsCounted() + public function testThatTheExtraLazyCollectionFromInversedToOwningIsCounted(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedManyToManyExtraLazyEntity::class, @@ -82,7 +84,7 @@ public function testThatTheExtraLazyCollectionFromInversedToOwningIsCounted() $this->assertEquals(2, $inversed->associatedEntities->count()); } - public function testThatTheExtraLazyCollectionFromOwningToInversedContainsAnEntity() + public function testThatTheExtraLazyCollectionFromOwningToInversedContainsAnEntity(): void { $owning = $this->_em->find( Models\ValueConversionType\OwningManyToManyExtraLazyEntity::class, @@ -97,7 +99,7 @@ public function testThatTheExtraLazyCollectionFromOwningToInversedContainsAnEnti $this->assertTrue($owning->associatedEntities->contains($inversed)); } - public function testThatTheExtraLazyCollectionFromInversedToOwningContainsAnEntity() + public function testThatTheExtraLazyCollectionFromInversedToOwningContainsAnEntity(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedManyToManyExtraLazyEntity::class, @@ -112,7 +114,7 @@ public function testThatTheExtraLazyCollectionFromInversedToOwningContainsAnEnti $this->assertTrue($inversed->associatedEntities->contains($owning)); } - public function testThatTheExtraLazyCollectionFromOwningToInversedContainsAnIndexByKey() + public function testThatTheExtraLazyCollectionFromOwningToInversedContainsAnIndexByKey(): void { $owning = $this->_em->find( Models\ValueConversionType\OwningManyToManyExtraLazyEntity::class, @@ -122,7 +124,7 @@ public function testThatTheExtraLazyCollectionFromOwningToInversedContainsAnInde $this->assertTrue($owning->associatedEntities->containsKey('abc')); } - public function testThatTheExtraLazyCollectionFromInversedToOwningContainsAnIndexByKey() + public function testThatTheExtraLazyCollectionFromInversedToOwningContainsAnIndexByKey(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedManyToManyExtraLazyEntity::class, @@ -132,7 +134,7 @@ public function testThatTheExtraLazyCollectionFromInversedToOwningContainsAnInde $this->assertTrue($inversed->associatedEntities->containsKey('ghi')); } - public function testThatASliceOfTheExtraLazyCollectionFromOwningToInversedIsLoaded() + public function testThatASliceOfTheExtraLazyCollectionFromOwningToInversedIsLoaded(): void { $owning = $this->_em->find( Models\ValueConversionType\OwningManyToManyExtraLazyEntity::class, @@ -142,7 +144,7 @@ public function testThatASliceOfTheExtraLazyCollectionFromOwningToInversedIsLoad $this->assertCount(1, $owning->associatedEntities->slice(0, 1)); } - public function testThatASliceOfTheExtraLazyCollectionFromInversedToOwningIsLoaded() + public function testThatASliceOfTheExtraLazyCollectionFromInversedToOwningIsLoaded(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedManyToManyExtraLazyEntity::class, diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyTest.php index 4ebec8d071f..6784dc8b286 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyTest.php @@ -1,5 +1,7 @@ useModelSet('vct_manytomany'); parent::setUp(); - $inversed = new Entity\InversedManyToManyEntity(); + $inversed = new Entity\InversedManyToManyEntity(); $inversed->id1 = 'abc'; - $owning = new Entity\OwningManyToManyEntity(); + $owning = new Entity\OwningManyToManyEntity(); $owning->id2 = 'def'; $inversed->associatedEntities->add($owning); @@ -38,7 +40,7 @@ protected function setUp() : void $this->_em->clear(); } - public static function tearDownAfterClass() : void + public static function tearDownAfterClass(): void { $conn = static::$_sharedConn; @@ -47,7 +49,7 @@ public static function tearDownAfterClass() : void $conn->executeUpdate('DROP TABLE vct_inversed_manytomany'); } - public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() + public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase(): void { $conn = $this->_em->getConnection(); @@ -62,7 +64,7 @@ public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() /** * @depends testThatTheValueOfIdentifiersAreConvertedInTheDatabase */ - public function testThatEntitiesAreFetchedFromTheDatabase() + public function testThatEntitiesAreFetchedFromTheDatabase(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedManyToManyEntity::class, @@ -81,7 +83,7 @@ public function testThatEntitiesAreFetchedFromTheDatabase() /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() + public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedManyToManyEntity::class, @@ -100,7 +102,7 @@ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFr /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheCollectionFromOwningToInversedIsLoaded() + public function testThatTheCollectionFromOwningToInversedIsLoaded(): void { $owning = $this->_em->find( Models\ValueConversionType\OwningManyToManyEntity::class, @@ -113,7 +115,7 @@ public function testThatTheCollectionFromOwningToInversedIsLoaded() /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheCollectionFromInversedToOwningIsLoaded() + public function testThatTheCollectionFromInversedToOwningIsLoaded(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedManyToManyEntity::class, @@ -127,7 +129,7 @@ public function testThatTheCollectionFromInversedToOwningIsLoaded() * @depends testThatTheCollectionFromOwningToInversedIsLoaded * @depends testThatTheCollectionFromInversedToOwningIsLoaded */ - public function testThatTheJoinTableRowsAreRemovedWhenRemovingTheAssociation() + public function testThatTheJoinTableRowsAreRemovedWhenRemovingTheAssociation(): void { $conn = $this->_em->getConnection(); diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyCompositeIdForeignKeyTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyCompositeIdForeignKeyTest.php index a8e017b0c96..0ac068e8cac 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyCompositeIdForeignKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyCompositeIdForeignKeyTest.php @@ -1,5 +1,7 @@ useModelSet('vct_onetomany_compositeid_foreignkey'); parent::setUp(); - $auxiliary = new Entity\AuxiliaryEntity(); + $auxiliary = new Entity\AuxiliaryEntity(); $auxiliary->id4 = 'abc'; - $inversed = new Entity\InversedOneToManyCompositeIdForeignKeyEntity(); - $inversed->id1 = 'def'; + $inversed = new Entity\InversedOneToManyCompositeIdForeignKeyEntity(); + $inversed->id1 = 'def'; $inversed->foreignEntity = $auxiliary; - $inversed->someProperty = 'some value to be loaded'; + $inversed->someProperty = 'some value to be loaded'; - $owning = new Entity\OwningManyToOneCompositeIdForeignKeyEntity(); + $owning = new Entity\OwningManyToOneCompositeIdForeignKeyEntity(); $owning->id2 = 'ghi'; $inversed->associatedEntities->add($owning); @@ -45,7 +47,7 @@ protected function setUp() : void $this->_em->clear(); } - public static function tearDownAfterClass() : void + public static function tearDownAfterClass(): void { $conn = static::$_sharedConn; @@ -54,7 +56,7 @@ public static function tearDownAfterClass() : void $conn->executeUpdate('DROP TABLE vct_auxiliary'); } - public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() + public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase(): void { $conn = $this->_em->getConnection(); @@ -71,7 +73,7 @@ public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() /** * @depends testThatTheValueOfIdentifiersAreConvertedInTheDatabase */ - public function testThatEntitiesAreFetchedFromTheDatabase() + public function testThatEntitiesAreFetchedFromTheDatabase(): void { $auxiliary = $this->_em->find( Models\ValueConversionType\AuxiliaryEntity::class, @@ -96,7 +98,7 @@ public function testThatEntitiesAreFetchedFromTheDatabase() /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() + public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase(): void { $auxiliary = $this->_em->find( Models\ValueConversionType\AuxiliaryEntity::class, @@ -122,7 +124,7 @@ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFr /** * @depends testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase */ - public function testThatInversedEntityIsFetchedFromTheDatabaseUsingAuxiliaryEntityAsId() + public function testThatInversedEntityIsFetchedFromTheDatabaseUsingAuxiliaryEntityAsId(): void { $auxiliary = $this->_em->find( Models\ValueConversionType\AuxiliaryEntity::class, @@ -140,7 +142,7 @@ public function testThatInversedEntityIsFetchedFromTheDatabaseUsingAuxiliaryEnti /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheProxyFromOwningToInversedIsLoaded() + public function testThatTheProxyFromOwningToInversedIsLoaded(): void { $owning = $this->_em->find( Models\ValueConversionType\OwningManyToOneCompositeIdForeignKeyEntity::class, @@ -157,7 +159,7 @@ public function testThatTheProxyFromOwningToInversedIsLoaded() /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheCollectionFromInversedToOwningIsLoaded() + public function testThatTheCollectionFromInversedToOwningIsLoaded(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedOneToManyCompositeIdForeignKeyEntity::class, diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyCompositeIdTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyCompositeIdTest.php index 359def14337..e0f5e3f0e7e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyCompositeIdTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyCompositeIdTest.php @@ -1,5 +1,7 @@ useModelSet('vct_onetomany_compositeid'); parent::setUp(); - $inversed = new Entity\InversedOneToManyCompositeIdEntity(); - $inversed->id1 = 'abc'; - $inversed->id2 = 'def'; + $inversed = new Entity\InversedOneToManyCompositeIdEntity(); + $inversed->id1 = 'abc'; + $inversed->id2 = 'def'; $inversed->someProperty = 'some value to be loaded'; - $owning = new Entity\OwningManyToOneCompositeIdEntity(); + $owning = new Entity\OwningManyToOneCompositeIdEntity(); $owning->id3 = 'ghi'; $inversed->associatedEntities->add($owning); @@ -40,7 +42,7 @@ protected function setUp() : void $this->_em->clear(); } - public static function tearDownAfterClass() : void + public static function tearDownAfterClass(): void { $conn = static::$_sharedConn; @@ -48,7 +50,7 @@ public static function tearDownAfterClass() : void $conn->executeUpdate('DROP TABLE vct_inversed_onetomany_compositeid'); } - public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() + public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase(): void { $conn = $this->_em->getConnection(); @@ -63,7 +65,7 @@ public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() /** * @depends testThatTheValueOfIdentifiersAreConvertedInTheDatabase */ - public function testThatEntitiesAreFetchedFromTheDatabase() + public function testThatEntitiesAreFetchedFromTheDatabase(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedOneToManyCompositeIdEntity::class, @@ -82,7 +84,7 @@ public function testThatEntitiesAreFetchedFromTheDatabase() /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() + public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedOneToManyCompositeIdEntity::class, @@ -102,7 +104,7 @@ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFr /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheProxyFromOwningToInversedIsLoaded() + public function testThatTheProxyFromOwningToInversedIsLoaded(): void { $owning = $this->_em->find( Models\ValueConversionType\OwningManyToOneCompositeIdEntity::class, @@ -117,7 +119,7 @@ public function testThatTheProxyFromOwningToInversedIsLoaded() /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheCollectionFromInversedToOwningIsLoaded() + public function testThatTheCollectionFromInversedToOwningIsLoaded(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedOneToManyCompositeIdEntity::class, diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyExtraLazyTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyExtraLazyTest.php index 244c5fe1b99..45ab51f09a1 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyExtraLazyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyExtraLazyTest.php @@ -1,5 +1,7 @@ useModelSet('vct_onetomany_extralazy'); parent::setUp(); - $inversed = new Entity\InversedOneToManyExtraLazyEntity(); + $inversed = new Entity\InversedOneToManyExtraLazyEntity(); $inversed->id1 = 'abc'; - $owning1 = new Entity\OwningManyToOneExtraLazyEntity(); + $owning1 = new Entity\OwningManyToOneExtraLazyEntity(); $owning1->id2 = 'def'; - $owning2 = new Entity\OwningManyToOneExtraLazyEntity(); + $owning2 = new Entity\OwningManyToOneExtraLazyEntity(); $owning2->id2 = 'ghi'; - $owning3 = new Entity\OwningManyToOneExtraLazyEntity(); + $owning3 = new Entity\OwningManyToOneExtraLazyEntity(); $owning3->id2 = 'jkl'; $inversed->associatedEntities->add($owning1); @@ -51,7 +53,7 @@ protected function setUp() : void $this->_em->clear(); } - public static function tearDownAfterClass() : void + public static function tearDownAfterClass(): void { $conn = static::$_sharedConn; @@ -59,7 +61,7 @@ public static function tearDownAfterClass() : void $conn->executeUpdate('DROP TABLE vct_inversed_onetomany_extralazy'); } - public function testThatExtraLazyCollectionIsCounted() + public function testThatExtraLazyCollectionIsCounted(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedOneToManyExtraLazyEntity::class, @@ -69,7 +71,7 @@ public function testThatExtraLazyCollectionIsCounted() $this->assertEquals(3, $inversed->associatedEntities->count()); } - public function testThatExtraLazyCollectionContainsAnEntity() + public function testThatExtraLazyCollectionContainsAnEntity(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedOneToManyExtraLazyEntity::class, @@ -84,7 +86,7 @@ public function testThatExtraLazyCollectionContainsAnEntity() $this->assertTrue($inversed->associatedEntities->contains($owning)); } - public function testThatExtraLazyCollectionContainsAnIndexbyKey() + public function testThatExtraLazyCollectionContainsAnIndexbyKey(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedOneToManyExtraLazyEntity::class, @@ -94,7 +96,7 @@ public function testThatExtraLazyCollectionContainsAnIndexbyKey() $this->assertTrue($inversed->associatedEntities->containsKey('def')); } - public function testThatASliceOfTheExtraLazyCollectionIsLoaded() + public function testThatASliceOfTheExtraLazyCollectionIsLoaded(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedOneToManyExtraLazyEntity::class, diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyTest.php index f210e2ec84f..a300c5ebd8f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyTest.php @@ -1,5 +1,7 @@ useModelSet('vct_onetomany'); parent::setUp(); - $inversed = new Entity\InversedOneToManyEntity(); - $inversed->id1 = 'abc'; + $inversed = new Entity\InversedOneToManyEntity(); + $inversed->id1 = 'abc'; $inversed->someProperty = 'some value to be loaded'; - $owning = new Entity\OwningManyToOneEntity(); + $owning = new Entity\OwningManyToOneEntity(); $owning->id2 = 'def'; $inversed->associatedEntities->add($owning); @@ -39,7 +41,7 @@ protected function setUp() : void $this->_em->clear(); } - public static function tearDownAfterClass() : void + public static function tearDownAfterClass(): void { $conn = static::$_sharedConn; @@ -47,7 +49,7 @@ public static function tearDownAfterClass() : void $conn->executeUpdate('DROP TABLE vct_inversed_onetomany'); } - public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() + public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase(): void { $conn = $this->_em->getConnection(); @@ -60,7 +62,7 @@ public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() /** * @depends testThatTheValueOfIdentifiersAreConvertedInTheDatabase */ - public function testThatEntitiesAreFetchedFromTheDatabase() + public function testThatEntitiesAreFetchedFromTheDatabase(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedOneToManyEntity::class, @@ -79,7 +81,7 @@ public function testThatEntitiesAreFetchedFromTheDatabase() /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() + public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedOneToManyEntity::class, @@ -98,7 +100,7 @@ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFr /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheProxyFromOwningToInversedIsLoaded() + public function testThatTheProxyFromOwningToInversedIsLoaded(): void { $owning = $this->_em->find( Models\ValueConversionType\OwningManyToOneEntity::class, @@ -113,7 +115,7 @@ public function testThatTheProxyFromOwningToInversedIsLoaded() /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheCollectionFromInversedToOwningIsLoaded() + public function testThatTheCollectionFromInversedToOwningIsLoaded(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedOneToManyEntity::class, diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneCompositeIdForeignKeyTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneCompositeIdForeignKeyTest.php index f5bd984c043..ce0724833e8 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(); + $auxiliary = new Entity\AuxiliaryEntity(); $auxiliary->id4 = 'abc'; - $inversed = new Entity\InversedOneToOneCompositeIdForeignKeyEntity(); - $inversed->id1 = 'def'; + $inversed = new Entity\InversedOneToOneCompositeIdForeignKeyEntity(); + $inversed->id1 = 'def'; $inversed->foreignEntity = $auxiliary; - $inversed->someProperty = 'some value to be loaded'; + $inversed->someProperty = 'some value to be loaded'; - $owning = new Entity\OwningOneToOneCompositeIdForeignKeyEntity(); + $owning = new Entity\OwningOneToOneCompositeIdForeignKeyEntity(); $owning->id2 = 'ghi'; $inversed->associatedEntity = $owning; - $owning->associatedEntity = $inversed; + $owning->associatedEntity = $inversed; $this->_em->persist($auxiliary); $this->_em->persist($inversed); @@ -44,7 +46,7 @@ protected function setUp() : void $this->_em->clear(); } - public static function tearDownAfterClass() : void + public static function tearDownAfterClass(): void { $conn = static::$_sharedConn; @@ -53,7 +55,7 @@ public static function tearDownAfterClass() : void $conn->executeUpdate('DROP TABLE vct_auxiliary'); } - public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() + public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase(): void { $conn = $this->_em->getConnection(); @@ -70,7 +72,7 @@ public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() /** * @depends testThatTheValueOfIdentifiersAreConvertedInTheDatabase */ - public function testThatEntitiesAreFetchedFromTheDatabase() + public function testThatEntitiesAreFetchedFromTheDatabase(): void { $auxiliary = $this->_em->find( Models\ValueConversionType\AuxiliaryEntity::class, @@ -95,7 +97,7 @@ public function testThatEntitiesAreFetchedFromTheDatabase() /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() + public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase(): void { $auxiliary = $this->_em->find( Models\ValueConversionType\AuxiliaryEntity::class, @@ -121,7 +123,7 @@ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFr /** * @depends testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase */ - public function testThatInversedEntityIsFetchedFromTheDatabaseUsingAuxiliaryEntityAsId() + public function testThatInversedEntityIsFetchedFromTheDatabaseUsingAuxiliaryEntityAsId(): void { $auxiliary = $this->_em->find( Models\ValueConversionType\AuxiliaryEntity::class, @@ -139,7 +141,7 @@ public function testThatInversedEntityIsFetchedFromTheDatabaseUsingAuxiliaryEnti /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheProxyFromOwningToInversedIsLoaded() + public function testThatTheProxyFromOwningToInversedIsLoaded(): void { $owning = $this->_em->find( Models\ValueConversionType\OwningOneToOneCompositeIdForeignKeyEntity::class, @@ -154,7 +156,7 @@ public function testThatTheProxyFromOwningToInversedIsLoaded() /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheEntityFromInversedToOwningIsEagerLoaded() + public function testThatTheEntityFromInversedToOwningIsEagerLoaded(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedOneToOneCompositeIdForeignKeyEntity::class, diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneCompositeIdTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneCompositeIdTest.php index df63a3906ec..08db762bfcc 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(); - $inversed->id1 = 'abc'; - $inversed->id2 = 'def'; + $inversed = new Entity\InversedOneToOneCompositeIdEntity(); + $inversed->id1 = 'abc'; + $inversed->id2 = 'def'; $inversed->someProperty = 'some value to be loaded'; - $owning = new Entity\OwningOneToOneCompositeIdEntity(); + $owning = new Entity\OwningOneToOneCompositeIdEntity(); $owning->id3 = 'ghi'; $inversed->associatedEntity = $owning; - $owning->associatedEntity = $inversed; + $owning->associatedEntity = $inversed; $this->_em->persist($inversed); $this->_em->persist($owning); @@ -39,7 +41,7 @@ protected function setUp() : void $this->_em->clear(); } - public static function tearDownAfterClass() : void + public static function tearDownAfterClass(): void { $conn = static::$_sharedConn; @@ -47,7 +49,7 @@ public static function tearDownAfterClass() : void $conn->executeUpdate('DROP TABLE vct_inversed_onetoone_compositeid'); } - public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() + public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase(): void { $conn = $this->_em->getConnection(); @@ -62,7 +64,7 @@ public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() /** * @depends testThatTheValueOfIdentifiersAreConvertedInTheDatabase */ - public function testThatEntitiesAreFetchedFromTheDatabase() + public function testThatEntitiesAreFetchedFromTheDatabase(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedOneToOneCompositeIdEntity::class, @@ -81,7 +83,7 @@ public function testThatEntitiesAreFetchedFromTheDatabase() /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() + public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedOneToOneCompositeIdEntity::class, @@ -101,7 +103,7 @@ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFr /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheProxyFromOwningToInversedIsLoaded() + public function testThatTheProxyFromOwningToInversedIsLoaded(): void { $owning = $this->_em->find( Models\ValueConversionType\OwningOneToOneCompositeIdEntity::class, @@ -116,7 +118,7 @@ public function testThatTheProxyFromOwningToInversedIsLoaded() /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheEntityFromInversedToOwningIsEagerLoaded() + public function testThatTheEntityFromInversedToOwningIsEagerLoaded(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedOneToOneCompositeIdEntity::class, diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneTest.php index 9bba31c7529..450bc147b3a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneTest.php @@ -1,5 +1,7 @@ useModelSet('vct_onetoone'); parent::setUp(); - $inversed = new Entity\InversedOneToOneEntity(); - $inversed->id1 = 'abc'; + $inversed = new Entity\InversedOneToOneEntity(); + $inversed->id1 = 'abc'; $inversed->someProperty = 'some value to be loaded'; - $owning = new Entity\OwningOneToOneEntity(); + $owning = new Entity\OwningOneToOneEntity(); $owning->id2 = 'def'; $inversed->associatedEntity = $owning; - $owning->associatedEntity = $inversed; + $owning->associatedEntity = $inversed; $this->_em->persist($inversed); $this->_em->persist($owning); @@ -39,7 +41,7 @@ protected function setUp() : void $this->_em->clear(); } - public static function tearDownAfterClass() : void + public static function tearDownAfterClass(): void { $conn = static::$_sharedConn; @@ -47,7 +49,7 @@ public static function tearDownAfterClass() : void $conn->executeUpdate('DROP TABLE vct_inversed_onetoone'); } - public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() + public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase(): void { $conn = $this->_em->getConnection(); @@ -60,7 +62,7 @@ public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() /** * @depends testThatTheValueOfIdentifiersAreConvertedInTheDatabase */ - public function testThatEntitiesAreFetchedFromTheDatabase() + public function testThatEntitiesAreFetchedFromTheDatabase(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedOneToOneEntity::class, @@ -79,7 +81,7 @@ public function testThatEntitiesAreFetchedFromTheDatabase() /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() + public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedOneToOneEntity::class, @@ -98,7 +100,7 @@ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFr /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheProxyFromOwningToInversedIsLoaded() + public function testThatTheProxyFromOwningToInversedIsLoaded(): void { $owning = $this->_em->find( Models\ValueConversionType\OwningOneToOneEntity::class, @@ -113,7 +115,7 @@ public function testThatTheProxyFromOwningToInversedIsLoaded() /** * @depends testThatEntitiesAreFetchedFromTheDatabase */ - public function testThatTheEntityFromInversedToOwningIsEagerLoaded() + public function testThatTheEntityFromInversedToOwningIsEagerLoaded(): void { $inversed = $this->_em->find( Models\ValueConversionType\InversedOneToOneEntity::class, diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueObjectsTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueObjectsTest.php index b1e6fdd93d1..12ed8c0c2bd 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueObjectsTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueObjectsTest.php @@ -21,7 +21,7 @@ */ class ValueObjectsTest extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { parent::setUp(); @@ -40,7 +40,7 @@ protected function setUp() : void } } - public function testMetadataHasReflectionEmbeddablesAccessible() + public function testMetadataHasReflectionEmbeddablesAccessible(): void { $classMetadata = $this->_em->getClassMetadata(DDC93Person::class); @@ -55,10 +55,11 @@ public function testMetadataHasReflectionEmbeddablesAccessible() $classMetadata->getReflectionProperty('address') ); } + $this->assertInstanceOf(ReflectionEmbeddedProperty::class, $classMetadata->getReflectionProperty('address.street')); } - public function testCRUD() + public function testCRUD(): void { $person = new DDC93Person(); $person->name = 'Tara'; @@ -109,7 +110,7 @@ public function testCRUD() $this->assertNull($this->_em->find(DDC93Person::class, $personId)); } - public function testLoadDql() + public function testLoadDql(): void { for ($i = 0; $i < 3; $i++) { $person = new DDC93Person(); @@ -153,7 +154,7 @@ public function testLoadDql() /** * @group dql */ - public function testDqlOnEmbeddedObjectsField() + public function testDqlOnEmbeddedObjectsField(): void { if ($this->isSecondLevelCacheEnabled) { $this->markTestSkipped('SLC does not work with UPDATE/DELETE queries through EM.'); @@ -200,7 +201,7 @@ public function testDqlOnEmbeddedObjectsField() $this->assertNull($this->_em->find(DDC93Person::class, $person->id)); } - public function testPartialDqlOnEmbeddedObjectsField() + public function testPartialDqlOnEmbeddedObjectsField(): void { $person = new DDC93Person('Karl', new DDC93Address('Foo', '12345', 'Gosport', new DDC93Country('England'))); $this->_em->persist($person); @@ -252,7 +253,7 @@ public function testPartialDqlOnEmbeddedObjectsField() $this->assertNull($person->name); } - public function testDqlWithNonExistentEmbeddableField() + public function testDqlWithNonExistentEmbeddableField(): void { $this->expectException(QueryException::class); $this->expectExceptionMessage('no field or association named address.asdfasdf'); @@ -261,7 +262,7 @@ public function testDqlWithNonExistentEmbeddableField() ->execute(); } - public function testPartialDqlWithNonExistentEmbeddableField() + public function testPartialDqlWithNonExistentEmbeddableField(): void { $this->expectException(QueryException::class); $this->expectExceptionMessage("no mapped field named 'address.asdfasdf'"); @@ -270,7 +271,7 @@ public function testPartialDqlWithNonExistentEmbeddableField() ->execute(); } - public function testEmbeddableWithInheritance() + public function testEmbeddableWithInheritance(): void { $car = new DDC93Car(new DDC93Address('Foo', '12345', 'Asdf')); $this->_em->persist($car); @@ -280,7 +281,7 @@ public function testEmbeddableWithInheritance() $this->assertEquals($car, $reloadedCar); } - public function testInlineEmbeddableWithPrefix() + public function testInlineEmbeddableWithPrefix(): void { $metadata = $this->_em->getClassMetadata(DDC3028PersonWithPrefix::class); @@ -290,7 +291,7 @@ public function testInlineEmbeddableWithPrefix() $this->assertEquals('bloo_id', $metadata->getColumnName('nested.nestedWithPrefixFalse.id')); } - public function testInlineEmbeddableEmptyPrefix() + public function testInlineEmbeddableEmptyPrefix(): void { $metadata = $this->_em->getClassMetadata(DDC3028PersonEmptyPrefix::class); @@ -300,7 +301,7 @@ public function testInlineEmbeddableEmptyPrefix() $this->assertEquals('nested_id', $metadata->getColumnName('nested.nestedWithPrefixFalse.id')); } - public function testInlineEmbeddablePrefixFalse() + public function testInlineEmbeddablePrefixFalse(): void { $expectedColumnName = 'id'; @@ -311,7 +312,7 @@ public function testInlineEmbeddablePrefixFalse() $this->assertEquals($expectedColumnName, $actualColumnName); } - public function testInlineEmbeddableInMappedSuperClass() + public function testInlineEmbeddableInMappedSuperClass(): void { $isFieldMapped = $this->_em ->getClassMetadata(DDC3027Dog::class) @@ -323,7 +324,7 @@ public function testInlineEmbeddableInMappedSuperClass() /** * @dataProvider getInfiniteEmbeddableNestingData */ - public function testThrowsExceptionOnInfiniteEmbeddableNesting($embeddableClassName, $declaredEmbeddableClassName) + public function testThrowsExceptionOnInfiniteEmbeddableNesting($embeddableClassName, $declaredEmbeddableClassName): void { $this->expectException(MappingException::class); $this->expectExceptionMessage( diff --git a/tests/Doctrine/Tests/ORM/Functional/VersionedOneToOneTest.php b/tests/Doctrine/Tests/ORM/Functional/VersionedOneToOneTest.php index 8548b1834a2..fa599e144d0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/VersionedOneToOneTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/VersionedOneToOneTest.php @@ -1,22 +1,22 @@ - * * @group VersionedOneToOne */ class VersionedOneToOneTest extends OrmFunctionalTestCase { - protected function setUp() : void + protected function setUp(): void { parent::setUp(); @@ -24,7 +24,7 @@ protected function setUp() : void $this->_schemaTool->createSchema( [ $this->_em->getClassMetadata(FirstRelatedEntity::class), - $this->_em->getClassMetadata(SecondRelatedEntity::class) + $this->_em->getClassMetadata(SecondRelatedEntity::class), ] ); } catch (ORMException $e) { @@ -35,16 +35,16 @@ protected function setUp() : void * This test case tests that a versionable entity, that has a oneToOne relationship as it's id can be created * without this bug fix (DDC-3318), you could not do this */ - public function testSetVersionOnCreate() + public function testSetVersionOnCreate(): void { - $secondRelatedEntity = new SecondRelatedEntity(); + $secondRelatedEntity = new SecondRelatedEntity(); $secondRelatedEntity->name = 'Bob'; $this->_em->persist($secondRelatedEntity); $this->_em->flush(); - $firstRelatedEntity = new FirstRelatedEntity(); - $firstRelatedEntity->name = 'Fred'; + $firstRelatedEntity = new FirstRelatedEntity(); + $firstRelatedEntity->name = 'Fred'; $firstRelatedEntity->secondEntity = $secondRelatedEntity; $this->_em->persist($firstRelatedEntity); diff --git a/tests/Doctrine/Tests/ORM/Hydration/AbstractHydratorTest.php b/tests/Doctrine/Tests/ORM/Hydration/AbstractHydratorTest.php index 40a3d03233e..00aefa398d9 100644 --- a/tests/Doctrine/Tests/ORM/Hydration/AbstractHydratorTest.php +++ b/tests/Doctrine/Tests/ORM/Hydration/AbstractHydratorTest.php @@ -1,5 +1,7 @@ mockEventManager @@ -93,7 +90,7 @@ public function testOnClearEventListenerIsDetachedOnCleanup() : void /** * @group #6623 */ - public function testHydrateAllRegistersAndClearsAllAttachedListeners() : void + public function testHydrateAllRegistersAndClearsAllAttachedListeners(): void { $this ->mockEventManager diff --git a/tests/Doctrine/Tests/ORM/Hydration/ArrayHydratorTest.php b/tests/Doctrine/Tests/ORM/Hydration/ArrayHydratorTest.php index 6c0b30ef655..21e262a9213 100644 --- a/tests/Doctrine/Tests/ORM/Hydration/ArrayHydratorTest.php +++ b/tests/Doctrine/Tests/ORM/Hydration/ArrayHydratorTest.php @@ -1,7 +1,10 @@ addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', 'u__id', 'id'); @@ -39,16 +45,16 @@ public function testSimpleEntityQuery() $resultSet = [ [ 'u__id' => '1', - 'u__name' => 'romanb' + 'u__name' => 'romanb', ], [ 'u__id' => '2', - 'u__name' => 'jwage' - ] + 'u__name' => 'jwage', + ], ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new ArrayHydrator($this->_em); $result = $hydrator->hydrateAll($stmt, $rsm); $this->assertEquals(2, count($result)); @@ -67,10 +73,10 @@ public function testSimpleEntityQuery() * * @dataProvider provideDataForUserEntityResult */ - public function testSimpleEntityWithScalarQuery($userEntityKey) + public function testSimpleEntityWithScalarQuery($userEntityKey): void { $alias = $userEntityKey ?: 'u'; - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, $alias); $rsm->addFieldResult($alias, 's__id', 'id'); @@ -88,11 +94,11 @@ public function testSimpleEntityWithScalarQuery($userEntityKey) 's__id' => '2', 's__name' => 'jwage', 'sclr0' => 'JWAGE', - ] + ], ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new ArrayHydrator($this->_em); $result = $hydrator->hydrateAll($stmt, $rsm); $this->assertEquals(2, count($result)); @@ -119,9 +125,9 @@ public function testSimpleEntityWithScalarQuery($userEntityKey) * SELECT PARTIAL u.{id, name} AS user * FROM Doctrine\Tests\Models\CMS\CmsUser u */ - public function testSimpleEntityQueryWithAliasedUserEntity() + public function testSimpleEntityQueryWithAliasedUserEntity(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', 'user'); $rsm->addFieldResult('u', 'u__id', 'id'); @@ -131,16 +137,16 @@ public function testSimpleEntityQueryWithAliasedUserEntity() $resultSet = [ [ 'u__id' => '1', - 'u__name' => 'romanb' + 'u__name' => 'romanb', ], [ 'u__id' => '2', - 'u__name' => 'jwage' - ] + 'u__name' => 'jwage', + ], ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new ArrayHydrator($this->_em); $result = $hydrator->hydrateAll($stmt, $rsm); $this->assertEquals(2, count($result)); @@ -159,9 +165,9 @@ public function testSimpleEntityQueryWithAliasedUserEntity() * SELECT PARTIAL u.{id, name}, PARTIAL a.{id, topic} * FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsArticle a */ - public function testSimpleMultipleRootEntityQuery() + public function testSimpleMultipleRootEntityQuery(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addEntityResult(CmsArticle::class, 'a'); @@ -176,18 +182,18 @@ public function testSimpleMultipleRootEntityQuery() 'u__id' => '1', 'u__name' => 'romanb', 'a__id' => '1', - 'a__topic' => 'Cool things.' + 'a__topic' => 'Cool things.', ], [ 'u__id' => '2', 'u__name' => 'jwage', 'a__id' => '2', - 'a__topic' => 'Cool things II.' - ] + 'a__topic' => 'Cool things II.', + ], ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new ArrayHydrator($this->_em); $result = $hydrator->hydrateAll($stmt, $rsm); $this->assertEquals(4, count($result)); @@ -209,9 +215,9 @@ public function testSimpleMultipleRootEntityQuery() * SELECT PARTIAL u.{id, name} AS user, PARTIAL a.{id, topic} * FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsArticle a */ - public function testSimpleMultipleRootEntityQueryWithAliasedUserEntity() + public function testSimpleMultipleRootEntityQueryWithAliasedUserEntity(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', 'user'); $rsm->addEntityResult(CmsArticle::class, 'a'); @@ -226,18 +232,18 @@ public function testSimpleMultipleRootEntityQueryWithAliasedUserEntity() 'u__id' => '1', 'u__name' => 'romanb', 'a__id' => '1', - 'a__topic' => 'Cool things.' + 'a__topic' => 'Cool things.', ], [ 'u__id' => '2', 'u__name' => 'jwage', 'a__id' => '2', - 'a__topic' => 'Cool things II.' - ] + 'a__topic' => 'Cool things II.', + ], ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new ArrayHydrator($this->_em); $result = $hydrator->hydrateAll($stmt, $rsm); $this->assertEquals(4, count($result)); @@ -263,9 +269,9 @@ public function testSimpleMultipleRootEntityQueryWithAliasedUserEntity() * SELECT PARTIAL u.{id, name}, PARTIAL a.{id, topic} AS article * FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsArticle a */ - public function testSimpleMultipleRootEntityQueryWithAliasedArticleEntity() + public function testSimpleMultipleRootEntityQueryWithAliasedArticleEntity(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addEntityResult(CmsArticle::class, 'a', 'article'); @@ -280,18 +286,18 @@ public function testSimpleMultipleRootEntityQueryWithAliasedArticleEntity() 'u__id' => '1', 'u__name' => 'romanb', 'a__id' => '1', - 'a__topic' => 'Cool things.' + 'a__topic' => 'Cool things.', ], [ 'u__id' => '2', 'u__name' => 'jwage', 'a__id' => '2', - 'a__topic' => 'Cool things II.' - ] + 'a__topic' => 'Cool things II.', + ], ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new ArrayHydrator($this->_em); $result = $hydrator->hydrateAll($stmt, $rsm); $this->assertEquals(4, count($result)); @@ -317,9 +323,9 @@ public function testSimpleMultipleRootEntityQueryWithAliasedArticleEntity() * SELECT PARTIAL u.{id, name} AS user, PARTIAL a.{id, topic} AS article * FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsArticle a */ - public function testSimpleMultipleRootEntityQueryWithAliasedEntities() + public function testSimpleMultipleRootEntityQueryWithAliasedEntities(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', 'user'); $rsm->addEntityResult(CmsArticle::class, 'a', 'article'); @@ -334,18 +340,18 @@ public function testSimpleMultipleRootEntityQueryWithAliasedEntities() 'u__id' => '1', 'u__name' => 'romanb', 'a__id' => '1', - 'a__topic' => 'Cool things.' + 'a__topic' => 'Cool things.', ], [ 'u__id' => '2', 'u__name' => 'jwage', 'a__id' => '2', - 'a__topic' => 'Cool things II.' - ] + 'a__topic' => 'Cool things II.', + ], ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new ArrayHydrator($this->_em); $result = $hydrator->hydrateAll($stmt, $rsm); $this->assertEquals(4, count($result)); @@ -375,9 +381,9 @@ public function testSimpleMultipleRootEntityQueryWithAliasedEntities() * * @dataProvider provideDataForUserEntityResult */ - public function testMixedQueryNormalJoin($userEntityKey) + public function testMixedQueryNormalJoin($userEntityKey): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addFieldResult('u', 'u__id', 'id'); @@ -396,11 +402,11 @@ public function testMixedQueryNormalJoin($userEntityKey) 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => '1', - ] + ], ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new ArrayHydrator($this->_em); $result = $hydrator->hydrateAll($stmt, $rsm); $this->assertEquals(2, count($result)); @@ -424,9 +430,9 @@ public function testMixedQueryNormalJoin($userEntityKey) * * @dataProvider provideDataForUserEntityResult */ - public function testMixedQueryFetchJoin($userEntityKey) + public function testMixedQueryFetchJoin($userEntityKey): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addJoinedEntityResult( @@ -459,12 +465,12 @@ public function testMixedQueryFetchJoin($userEntityKey) 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => 'JWAGE', - 'p__phonenumber' => '91' - ] + 'p__phonenumber' => '91', + ], ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new ArrayHydrator($this->_em); $result = $hydrator->hydrateAll($stmt, $rsm); $this->assertEquals(2, count($result)); @@ -495,9 +501,9 @@ public function testMixedQueryFetchJoin($userEntityKey) * * @dataProvider provideDataForUserEntityResult */ - public function testMixedQueryFetchJoinCustomIndex($userEntityKey) + public function testMixedQueryFetchJoinCustomIndex($userEntityKey): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addJoinedEntityResult( @@ -532,13 +538,12 @@ public function testMixedQueryFetchJoinCustomIndex($userEntityKey) 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => 'JWAGE', - 'p__phonenumber' => '91' - ] + 'p__phonenumber' => '91', + ], ]; - $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new ArrayHydrator($this->_em); $result = $hydrator->hydrateAll($stmt, $rsm); $this->assertEquals(2, count($result)); @@ -574,9 +579,9 @@ public function testMixedQueryFetchJoinCustomIndex($userEntityKey) * inner join PHONENUMBERS p ON u.id = p.user_id * inner join ARTICLES a ON u.id = a.user_id */ - public function testMixedQueryMultipleFetchJoin() + public function testMixedQueryMultipleFetchJoin(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addJoinedEntityResult( @@ -607,7 +612,7 @@ public function testMixedQueryMultipleFetchJoin() 'sclr0' => 'ROMANB', 'p__phonenumber' => '42', 'a__id' => '1', - 'a__topic' => 'Getting things done!' + 'a__topic' => 'Getting things done!', ], [ 'u__id' => '1', @@ -615,7 +620,7 @@ public function testMixedQueryMultipleFetchJoin() 'sclr0' => 'ROMANB', 'p__phonenumber' => '43', 'a__id' => '1', - 'a__topic' => 'Getting things done!' + 'a__topic' => 'Getting things done!', ], [ 'u__id' => '1', @@ -623,7 +628,7 @@ public function testMixedQueryMultipleFetchJoin() 'sclr0' => 'ROMANB', 'p__phonenumber' => '42', 'a__id' => '2', - 'a__topic' => 'ZendCon' + 'a__topic' => 'ZendCon', ], [ 'u__id' => '1', @@ -631,7 +636,7 @@ public function testMixedQueryMultipleFetchJoin() 'sclr0' => 'ROMANB', 'p__phonenumber' => '43', 'a__id' => '2', - 'a__topic' => 'ZendCon' + 'a__topic' => 'ZendCon', ], [ 'u__id' => '2', @@ -639,7 +644,7 @@ public function testMixedQueryMultipleFetchJoin() 'sclr0' => 'JWAGE', 'p__phonenumber' => '91', 'a__id' => '3', - 'a__topic' => 'LINQ' + 'a__topic' => 'LINQ', ], [ 'u__id' => '2', @@ -647,12 +652,12 @@ public function testMixedQueryMultipleFetchJoin() 'sclr0' => 'JWAGE', 'p__phonenumber' => '91', 'a__id' => '4', - 'a__topic' => 'PHP7' + 'a__topic' => 'PHP7', ], ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new ArrayHydrator($this->_em); $result = $hydrator->hydrateAll($stmt, $rsm); $this->assertEquals(2, count($result)); @@ -693,9 +698,9 @@ public function testMixedQueryMultipleFetchJoin() * inner join ARTICLES a ON u.id = a.user_id * left outer join COMMENTS c ON a.id = c.article_id */ - public function testMixedQueryMultipleDeepMixedFetchJoin() + public function testMixedQueryMultipleDeepMixedFetchJoin(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addJoinedEntityResult( @@ -736,7 +741,7 @@ public function testMixedQueryMultipleDeepMixedFetchJoin() 'a__id' => '1', 'a__topic' => 'Getting things done!', 'c__id' => '1', - 'c__topic' => 'First!' + 'c__topic' => 'First!', ], [ 'u__id' => '1', @@ -746,7 +751,7 @@ public function testMixedQueryMultipleDeepMixedFetchJoin() 'a__id' => '1', 'a__topic' => 'Getting things done!', 'c__id' => '1', - 'c__topic' => 'First!' + 'c__topic' => 'First!', ], [ 'u__id' => '1', @@ -756,7 +761,7 @@ public function testMixedQueryMultipleDeepMixedFetchJoin() 'a__id' => '2', 'a__topic' => 'ZendCon', 'c__id' => null, - 'c__topic' => null + 'c__topic' => null, ], [ 'u__id' => '1', @@ -766,7 +771,7 @@ public function testMixedQueryMultipleDeepMixedFetchJoin() 'a__id' => '2', 'a__topic' => 'ZendCon', 'c__id' => null, - 'c__topic' => null + 'c__topic' => null, ], [ 'u__id' => '2', @@ -776,7 +781,7 @@ public function testMixedQueryMultipleDeepMixedFetchJoin() 'a__id' => '3', 'a__topic' => 'LINQ', 'c__id' => null, - 'c__topic' => null + 'c__topic' => null, ], [ 'u__id' => '2', @@ -786,12 +791,12 @@ public function testMixedQueryMultipleDeepMixedFetchJoin() 'a__id' => '4', 'a__topic' => 'PHP7', 'c__id' => null, - 'c__topic' => null + 'c__topic' => null, ], ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new ArrayHydrator($this->_em); $result = $hydrator->hydrateAll($stmt, $rsm); $this->assertEquals(2, count($result)); @@ -850,9 +855,9 @@ public function testMixedQueryMultipleDeepMixedFetchJoin() * 1 | 0 | First | 1 | 3 | 1 * 1 | 0 | First | 2 | 4 | 1 */ - public function testEntityQueryCustomResultSetOrder() + public function testEntityQueryCustomResultSetOrder(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(ForumCategory::class, 'c'); $rsm->addJoinedEntityResult( @@ -901,11 +906,11 @@ public function testEntityQueryCustomResultSetOrder() 'b__id' => '4', 'b__position' => '2', //'b__category_id' => '1' - ] + ], ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new ArrayHydrator($this->_em); $result = $hydrator->hydrateAll($stmt, $rsm); $this->assertEquals(2, count($result)); @@ -926,9 +931,9 @@ public function testEntityQueryCustomResultSetOrder() * * @dataProvider provideDataForUserEntityResult */ - public function testChainedJoinWithScalars($entityKey) + public function testChainedJoinWithScalars($entityKey): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', $entityKey ?: null); $rsm->addFieldResult('u', 'u__id', 'id'); @@ -947,7 +952,7 @@ public function testChainedJoinWithScalars($entityKey) 'a__id' => '1', 'a__topic' => 'The First', 'c__id' => '1', - 'c__topic' => 'First Comment' + 'c__topic' => 'First Comment', ], [ 'u__id' => '1', @@ -955,7 +960,7 @@ public function testChainedJoinWithScalars($entityKey) 'a__id' => '1', 'a__topic' => 'The First', 'c__id' => '2', - 'c__topic' => 'Second Comment' + 'c__topic' => 'Second Comment', ], [ 'u__id' => '1', @@ -963,12 +968,12 @@ public function testChainedJoinWithScalars($entityKey) 'a__id' => '42', 'a__topic' => 'The Answer', 'c__id' => null, - 'c__topic' => null + 'c__topic' => null, ], ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new ArrayHydrator($this->_em); $result = $hydrator->hydrateAll($stmt, $rsm); $this->assertEquals(3, count($result)); @@ -996,9 +1001,9 @@ public function testChainedJoinWithScalars($entityKey) * SELECT PARTIAL u.{id, status} * FROM Doctrine\Tests\Models\CMS\CmsUser u */ - public function testResultIteration() + public function testResultIteration(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', 'u__id', 'id'); @@ -1008,16 +1013,16 @@ public function testResultIteration() $resultSet = [ [ 'u__id' => '1', - 'u__name' => 'romanb' + 'u__name' => 'romanb', ], [ 'u__id' => '2', - 'u__name' => 'jwage' - ] + 'u__name' => 'jwage', + ], ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new ArrayHydrator($this->_em); $iterator = $hydrator->iterate($stmt, $rsm); $rowNum = 0; @@ -1025,10 +1030,10 @@ public function testResultIteration() $this->assertEquals(1, count($row)); $this->assertTrue(is_array($row[0])); - if ($rowNum == 0) { + if ($rowNum === 0) { $this->assertEquals(1, $row[0]['id']); $this->assertEquals('romanb', $row[0]['name']); - } else if ($rowNum == 1) { + } elseif ($rowNum === 1) { $this->assertEquals(2, $row[0]['id']); $this->assertEquals('jwage', $row[0]['name']); } @@ -1041,9 +1046,9 @@ public function testResultIteration() * SELECT PARTIAL u.{id, status} * FROM Doctrine\Tests\Models\CMS\CmsUser u */ - public function testResultIterationWithAliasedUserEntity() + public function testResultIterationWithAliasedUserEntity(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', 'user'); $rsm->addFieldResult('u', 'u__id', 'id'); @@ -1053,16 +1058,16 @@ public function testResultIterationWithAliasedUserEntity() $resultSet = [ [ 'u__id' => '1', - 'u__name' => 'romanb' + 'u__name' => 'romanb', ], [ 'u__id' => '2', - 'u__name' => 'jwage' - ] + 'u__name' => 'jwage', + ], ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new ArrayHydrator($this->_em); $iterator = $hydrator->iterate($stmt, $rsm); $rowNum = 0; @@ -1071,10 +1076,10 @@ public function testResultIterationWithAliasedUserEntity() $this->assertArrayHasKey(0, $row); $this->assertArrayHasKey('user', $row[0]); - if ($rowNum == 0) { + if ($rowNum === 0) { $this->assertEquals(1, $row[0]['user']['id']); $this->assertEquals('romanb', $row[0]['user']['name']); - } else if ($rowNum == 1) { + } elseif ($rowNum === 1) { $this->assertEquals(2, $row[0]['user']['id']); $this->assertEquals('jwage', $row[0]['user']['name']); } @@ -1089,9 +1094,9 @@ public function testResultIterationWithAliasedUserEntity() * * @group DDC-644 */ - public function testSkipUnknownColumns() + public function testSkipUnknownColumns(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', 'u__id', 'id'); @@ -1107,7 +1112,7 @@ public function testSkipUnknownColumns() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new ArrayHydrator($this->_em); $result = $hydrator->hydrateAll($stmt, $rsm); $this->assertEquals(1, count($result)); @@ -1123,9 +1128,9 @@ public function testSkipUnknownColumns() * @group DDC-1358 * @dataProvider provideDataForUserEntityResult */ - public function testMissingIdForRootEntity($userEntityKey) + public function testMissingIdForRootEntity($userEntityKey): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addFieldResult('u', 'u__id', 'id'); @@ -1158,10 +1163,10 @@ public function testMissingIdForRootEntity($userEntityKey) ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new ArrayHydrator($this->_em); $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertEquals(4, count($result), "Should hydrate four results."); + $this->assertEquals(4, count($result), 'Should hydrate four results.'); $this->assertEquals('ROMANB', $result[0]['nameUpper']); $this->assertEquals('ROMANB', $result[1]['nameUpper']); @@ -1182,9 +1187,9 @@ public function testMissingIdForRootEntity($userEntityKey) * @group DDC-1385 * @dataProvider provideDataForUserEntityResult */ - public function testIndexByAndMixedResult($userEntityKey) + public function testIndexByAndMixedResult($userEntityKey): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addFieldResult('u', 'u__id', 'id'); @@ -1208,7 +1213,7 @@ public function testIndexByAndMixedResult($userEntityKey) ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new ArrayHydrator($this->_em); $result = $hydrator->hydrateAll($stmt, $rsm); $this->assertEquals(2, count($result)); diff --git a/tests/Doctrine/Tests/ORM/Hydration/CustomHydratorTest.php b/tests/Doctrine/Tests/ORM/Hydration/CustomHydratorTest.php index 7342b942f4f..a318bb4d4f2 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); diff --git a/tests/Doctrine/Tests/ORM/Hydration/HydrationTestCase.php b/tests/Doctrine/Tests/ORM/Hydration/HydrationTestCase.php index 3284e026fb6..f49046700a3 100644 --- a/tests/Doctrine/Tests/ORM/Hydration/HydrationTestCase.php +++ b/tests/Doctrine/Tests/ORM/Hydration/HydrationTestCase.php @@ -1,14 +1,17 @@ _em = $this->_getTestEntityManager(); @@ -17,11 +20,12 @@ protected function setUp() : void /** Helper method */ protected function _createParserResult($resultSetMapping, $isMixedQuery = false) { - $parserResult = new ParserResult; + $parserResult = new ParserResult(); $parserResult->setResultSetMapping($resultSetMapping); //$parserResult->setDefaultQueryComponentAlias(key($queryComponents)); //$parserResult->setTableAliasMap($tableToClassAliasMap); $parserResult->setMixedQuery($isMixedQuery); + return $parserResult; } } diff --git a/tests/Doctrine/Tests/ORM/Hydration/ObjectHydratorTest.php b/tests/Doctrine/Tests/ORM/Hydration/ObjectHydratorTest.php index 70524e9a7ff..e11d5cc1323 100644 --- a/tests/Doctrine/Tests/ORM/Hydration/ObjectHydratorTest.php +++ b/tests/Doctrine/Tests/ORM/Hydration/ObjectHydratorTest.php @@ -1,5 +1,7 @@ addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); @@ -68,12 +73,12 @@ public function testSimpleEntityQuery() $resultSet = [ [ 'u__id' => '1', - 'u__name' => 'romanb' + 'u__name' => 'romanb', ], [ 'u__id' => '2', - 'u__name' => 'jwage' - ] + 'u__name' => 'jwage', + ], ]; $stmt = new HydratorMockStatement($resultSet); @@ -96,9 +101,9 @@ public function testSimpleEntityQuery() * SELECT PARTIAL u.{id,name} AS user * FROM Doctrine\Tests\Models\CMS\CmsUser u */ - public function testSimpleEntityQueryWithAliasedUserEntity() + public function testSimpleEntityQueryWithAliasedUserEntity(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', 'user'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); @@ -107,12 +112,12 @@ public function testSimpleEntityQueryWithAliasedUserEntity() $resultSet = [ [ 'u__id' => '1', - 'u__name' => 'romanb' + 'u__name' => 'romanb', ], [ 'u__id' => '2', - 'u__name' => 'jwage' - ] + 'u__name' => 'jwage', + ], ]; $stmt = new HydratorMockStatement($resultSet); @@ -138,9 +143,9 @@ public function testSimpleEntityQueryWithAliasedUserEntity() * SELECT PARTIAL u.{id, name}, PARTIAL a.{id, topic} * FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsArticle a */ - public function testSimpleMultipleRootEntityQuery() + public function testSimpleMultipleRootEntityQuery(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addEntityResult(CmsArticle::class, 'a'); $rsm->addFieldResult('u', 'u__id', 'id'); @@ -154,14 +159,14 @@ public function testSimpleMultipleRootEntityQuery() 'u__id' => '1', 'u__name' => 'romanb', 'a__id' => '1', - 'a__topic' => 'Cool things.' + 'a__topic' => 'Cool things.', ], [ 'u__id' => '2', 'u__name' => 'jwage', 'a__id' => '2', - 'a__topic' => 'Cool things II.' - ] + 'a__topic' => 'Cool things II.', + ], ]; $stmt = new HydratorMockStatement($resultSet); @@ -192,9 +197,9 @@ public function testSimpleMultipleRootEntityQuery() * SELECT PARTIAL u.{id, name} AS user, PARTIAL a.{id, topic} * FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsArticle a */ - public function testSimpleMultipleRootEntityQueryWithAliasedUserEntity() + public function testSimpleMultipleRootEntityQueryWithAliasedUserEntity(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', 'user'); $rsm->addEntityResult(CmsArticle::class, 'a'); $rsm->addFieldResult('u', 'u__id', 'id'); @@ -208,14 +213,14 @@ public function testSimpleMultipleRootEntityQueryWithAliasedUserEntity() 'u__id' => '1', 'u__name' => 'romanb', 'a__id' => '1', - 'a__topic' => 'Cool things.' + 'a__topic' => 'Cool things.', ], [ 'u__id' => '2', 'u__name' => 'jwage', 'a__id' => '2', - 'a__topic' => 'Cool things II.' - ] + 'a__topic' => 'Cool things II.', + ], ]; $stmt = new HydratorMockStatement($resultSet); @@ -253,9 +258,9 @@ public function testSimpleMultipleRootEntityQueryWithAliasedUserEntity() * SELECT PARTIAL u.{id, name}, PARTIAL a.{id, topic} AS article * FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsArticle a */ - public function testSimpleMultipleRootEntityQueryWithAliasedArticleEntity() + public function testSimpleMultipleRootEntityQueryWithAliasedArticleEntity(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addEntityResult(CmsArticle::class, 'a', 'article'); $rsm->addFieldResult('u', 'u__id', 'id'); @@ -269,14 +274,14 @@ public function testSimpleMultipleRootEntityQueryWithAliasedArticleEntity() 'u__id' => '1', 'u__name' => 'romanb', 'a__id' => '1', - 'a__topic' => 'Cool things.' + 'a__topic' => 'Cool things.', ], [ 'u__id' => '2', 'u__name' => 'jwage', 'a__id' => '2', - 'a__topic' => 'Cool things II.' - ] + 'a__topic' => 'Cool things II.', + ], ]; $stmt = new HydratorMockStatement($resultSet); @@ -314,9 +319,9 @@ public function testSimpleMultipleRootEntityQueryWithAliasedArticleEntity() * SELECT PARTIAL u.{id, name} AS user, PARTIAL a.{id, topic} AS article * FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsArticle a */ - public function testSimpleMultipleRootEntityQueryWithAliasedEntities() + public function testSimpleMultipleRootEntityQueryWithAliasedEntities(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', 'user'); $rsm->addEntityResult(CmsArticle::class, 'a', 'article'); $rsm->addFieldResult('u', 'u__id', 'id'); @@ -330,14 +335,14 @@ public function testSimpleMultipleRootEntityQueryWithAliasedEntities() 'u__id' => '1', 'u__name' => 'romanb', 'a__id' => '1', - 'a__topic' => 'Cool things.' + 'a__topic' => 'Cool things.', ], [ 'u__id' => '2', 'u__name' => 'jwage', 'a__id' => '2', - 'a__topic' => 'Cool things II.' - ] + 'a__topic' => 'Cool things II.', + ], ]; $stmt = new HydratorMockStatement($resultSet); @@ -379,9 +384,9 @@ public function testSimpleMultipleRootEntityQueryWithAliasedEntities() * * @dataProvider provideDataForUserEntityResult */ - public function testMixedQueryNormalJoin($userEntityKey) + public function testMixedQueryNormalJoin($userEntityKey): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); @@ -399,7 +404,7 @@ public function testMixedQueryNormalJoin($userEntityKey) 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => '1', - ] + ], ]; $stmt = new HydratorMockStatement($resultSet); @@ -428,9 +433,9 @@ public function testMixedQueryNormalJoin($userEntityKey) * * @dataProvider provideDataForUserEntityResult */ - public function testMixedQueryFetchJoin($userEntityKey) + public function testMixedQueryFetchJoin($userEntityKey): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addJoinedEntityResult( CmsPhonenumber::class, @@ -463,7 +468,7 @@ public function testMixedQueryFetchJoin($userEntityKey) 'u__status' => 'developer', 'p__phonenumber' => '91', 'sclr0' => 'JWAGE', - ] + ], ]; $stmt = new HydratorMockStatement($resultSet); @@ -506,9 +511,9 @@ public function testMixedQueryFetchJoin($userEntityKey) * * @dataProvider provideDataForUserEntityResult */ - public function testMixedQueryFetchJoinCustomIndex($userEntityKey) + public function testMixedQueryFetchJoinCustomIndex($userEntityKey): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addJoinedEntityResult( CmsPhonenumber::class, @@ -542,11 +547,10 @@ public function testMixedQueryFetchJoinCustomIndex($userEntityKey) 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => 'JWAGE', - 'p__phonenumber' => '91' - ] + 'p__phonenumber' => '91', + ], ]; - $stmt = new HydratorMockStatement($resultSet); $hydrator = new ObjectHydrator($this->_em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); @@ -585,9 +589,9 @@ public function testMixedQueryFetchJoinCustomIndex($userEntityKey) * * @dataProvider provideDataForUserEntityResult */ - public function testMixedQueryMultipleFetchJoin($userEntityKey) + public function testMixedQueryMultipleFetchJoin($userEntityKey): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addJoinedEntityResult( CmsPhonenumber::class, @@ -617,7 +621,7 @@ public function testMixedQueryMultipleFetchJoin($userEntityKey) 'sclr0' => 'ROMANB', 'p__phonenumber' => '42', 'a__id' => '1', - 'a__topic' => 'Getting things done!' + 'a__topic' => 'Getting things done!', ], [ 'u__id' => '1', @@ -625,7 +629,7 @@ public function testMixedQueryMultipleFetchJoin($userEntityKey) 'sclr0' => 'ROMANB', 'p__phonenumber' => '43', 'a__id' => '1', - 'a__topic' => 'Getting things done!' + 'a__topic' => 'Getting things done!', ], [ 'u__id' => '1', @@ -633,7 +637,7 @@ public function testMixedQueryMultipleFetchJoin($userEntityKey) 'sclr0' => 'ROMANB', 'p__phonenumber' => '42', 'a__id' => '2', - 'a__topic' => 'ZendCon' + 'a__topic' => 'ZendCon', ], [ 'u__id' => '1', @@ -641,7 +645,7 @@ public function testMixedQueryMultipleFetchJoin($userEntityKey) 'sclr0' => 'ROMANB', 'p__phonenumber' => '43', 'a__id' => '2', - 'a__topic' => 'ZendCon' + 'a__topic' => 'ZendCon', ], [ 'u__id' => '2', @@ -649,7 +653,7 @@ public function testMixedQueryMultipleFetchJoin($userEntityKey) 'sclr0' => 'JWAGE', 'p__phonenumber' => '91', 'a__id' => '3', - 'a__topic' => 'LINQ' + 'a__topic' => 'LINQ', ], [ 'u__id' => '2', @@ -657,7 +661,7 @@ public function testMixedQueryMultipleFetchJoin($userEntityKey) 'sclr0' => 'JWAGE', 'p__phonenumber' => '91', 'a__id' => '4', - 'a__topic' => 'PHP7' + 'a__topic' => 'PHP7', ], ]; @@ -695,9 +699,9 @@ public function testMixedQueryMultipleFetchJoin($userEntityKey) * * @dataProvider provideDataForUserEntityResult */ - public function testMixedQueryMultipleDeepMixedFetchJoin($userEntityKey) + public function testMixedQueryMultipleDeepMixedFetchJoin($userEntityKey): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addJoinedEntityResult( CmsPhonenumber::class, @@ -737,7 +741,7 @@ public function testMixedQueryMultipleDeepMixedFetchJoin($userEntityKey) 'a__id' => '1', 'a__topic' => 'Getting things done!', 'c__id' => '1', - 'c__topic' => 'First!' + 'c__topic' => 'First!', ], [ 'u__id' => '1', @@ -747,7 +751,7 @@ public function testMixedQueryMultipleDeepMixedFetchJoin($userEntityKey) 'a__id' => '1', 'a__topic' => 'Getting things done!', 'c__id' => '1', - 'c__topic' => 'First!' + 'c__topic' => 'First!', ], [ 'u__id' => '1', @@ -757,7 +761,7 @@ public function testMixedQueryMultipleDeepMixedFetchJoin($userEntityKey) 'a__id' => '2', 'a__topic' => 'ZendCon', 'c__id' => null, - 'c__topic' => null + 'c__topic' => null, ], [ 'u__id' => '1', @@ -767,7 +771,7 @@ public function testMixedQueryMultipleDeepMixedFetchJoin($userEntityKey) 'a__id' => '2', 'a__topic' => 'ZendCon', 'c__id' => null, - 'c__topic' => null + 'c__topic' => null, ], [ 'u__id' => '2', @@ -777,7 +781,7 @@ public function testMixedQueryMultipleDeepMixedFetchJoin($userEntityKey) 'a__id' => '3', 'a__topic' => 'LINQ', 'c__id' => null, - 'c__topic' => null + 'c__topic' => null, ], [ 'u__id' => '2', @@ -787,7 +791,7 @@ public function testMixedQueryMultipleDeepMixedFetchJoin($userEntityKey) 'a__id' => '4', 'a__topic' => 'PHP7', 'c__id' => null, - 'c__topic' => null + 'c__topic' => null, ], ]; @@ -852,9 +856,9 @@ public function testMixedQueryMultipleDeepMixedFetchJoin($userEntityKey) * 1 | 0 | First | 1 | 3 | 1 * 1 | 0 | First | 2 | 4 | 1 */ - public function testEntityQueryCustomResultSetOrder() + public function testEntityQueryCustomResultSetOrder(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(ForumCategory::class, 'c'); $rsm->addJoinedEntityResult( ForumBoard::class, @@ -901,7 +905,7 @@ public function testEntityQueryCustomResultSetOrder() 'b__id' => '4', 'b__position' => '2', //'b__category_id' => '1' - ] + ], ]; $stmt = new HydratorMockStatement($resultSet); @@ -931,9 +935,9 @@ public function testEntityQueryCustomResultSetOrder() * * @group DDC-644 */ - public function testSkipUnknownColumns() + public function testSkipUnknownColumns(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); @@ -961,9 +965,9 @@ public function testSkipUnknownColumns() * * @dataProvider provideDataForUserEntityResult */ - public function testScalarQueryWithoutResultVariables($userEntityKey) + public function testScalarQueryWithoutResultVariables($userEntityKey): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addScalarResult('sclr0', 'id', 'integer'); $rsm->addScalarResult('sclr1', 'name', 'string'); @@ -972,12 +976,12 @@ public function testScalarQueryWithoutResultVariables($userEntityKey) $resultSet = [ [ 'sclr0' => '1', - 'sclr1' => 'romanb' + 'sclr1' => 'romanb', ], [ 'sclr0' => '2', - 'sclr1' => 'jwage' - ] + 'sclr1' => 'jwage', + ], ]; $stmt = new HydratorMockStatement($resultSet); @@ -1000,9 +1004,9 @@ public function testScalarQueryWithoutResultVariables($userEntityKey) * SELECT p * FROM Doctrine\Tests\Models\ECommerce\ECommerceProduct p */ - public function testCreatesProxyForLazyLoadingWithForeignKeys() + public function testCreatesProxyForLazyLoadingWithForeignKeys(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(ECommerceProduct::class, 'p'); $rsm->addFieldResult('p', 'p__id', 'id'); $rsm->addFieldResult('p', 'p__name', 'name'); @@ -1013,11 +1017,11 @@ public function testCreatesProxyForLazyLoadingWithForeignKeys() [ 'p__id' => '1', 'p__name' => 'Doctrine Book', - 'p__shipping_id' => 42 - ] + 'p__shipping_id' => 42, + ], ]; - $proxyInstance = new \Doctrine\Tests\Models\ECommerce\ECommerceShipping(); + $proxyInstance = new ECommerceShipping(); // mocking the proxy factory $proxyFactory = $this->getMockBuilder(ProxyFactory::class) @@ -1033,7 +1037,7 @@ public function testCreatesProxyForLazyLoadingWithForeignKeys() $this->_em->setProxyFactory($proxyFactory); // configuring lazy loading - $metadata = $this->_em->getClassMetadata(ECommerceProduct::class); + $metadata = $this->_em->getClassMetadata(ECommerceProduct::class); $metadata->associationMappings['shipping']['fetch'] = ClassMetadata::FETCH_LAZY; $stmt = new HydratorMockStatement($resultSet); @@ -1049,9 +1053,9 @@ public function testCreatesProxyForLazyLoadingWithForeignKeys() * SELECT p AS product * FROM Doctrine\Tests\Models\ECommerce\ECommerceProduct p */ - public function testCreatesProxyForLazyLoadingWithForeignKeysWithAliasedProductEntity() + public function testCreatesProxyForLazyLoadingWithForeignKeysWithAliasedProductEntity(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(ECommerceProduct::class, 'p', 'product'); $rsm->addFieldResult('p', 'p__id', 'id'); $rsm->addFieldResult('p', 'p__name', 'name'); @@ -1062,11 +1066,11 @@ public function testCreatesProxyForLazyLoadingWithForeignKeysWithAliasedProductE [ 'p__id' => '1', 'p__name' => 'Doctrine Book', - 'p__shipping_id' => 42 - ] + 'p__shipping_id' => 42, + ], ]; - $proxyInstance = new \Doctrine\Tests\Models\ECommerce\ECommerceShipping(); + $proxyInstance = new ECommerceShipping(); // mocking the proxy factory $proxyFactory = $this->getMockBuilder(ProxyFactory::class) @@ -1082,7 +1086,7 @@ public function testCreatesProxyForLazyLoadingWithForeignKeysWithAliasedProductE $this->_em->setProxyFactory($proxyFactory); // configuring lazy loading - $metadata = $this->_em->getClassMetadata(ECommerceProduct::class); + $metadata = $this->_em->getClassMetadata(ECommerceProduct::class); $metadata->associationMappings['shipping']['fetch'] = ClassMetadata::FETCH_LAZY; $stmt = new HydratorMockStatement($resultSet); @@ -1101,9 +1105,9 @@ public function testCreatesProxyForLazyLoadingWithForeignKeysWithAliasedProductE * LEFT JOIN u.articles a * LEFT JOIN a.comments c */ - public function testChainedJoinWithEmptyCollections() + public function testChainedJoinWithEmptyCollections(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addJoinedEntityResult( CmsArticle::class, @@ -1133,7 +1137,7 @@ public function testChainedJoinWithEmptyCollections() 'a__id' => null, 'a__topic' => null, 'c__id' => null, - 'c__topic' => null + 'c__topic' => null, ], [ 'u__id' => '2', @@ -1141,7 +1145,7 @@ public function testChainedJoinWithEmptyCollections() 'a__id' => null, 'a__topic' => null, 'c__id' => null, - 'c__topic' => null + 'c__topic' => null, ], ]; @@ -1164,9 +1168,9 @@ public function testChainedJoinWithEmptyCollections() * LEFT JOIN u.articles a * LEFT JOIN a.comments c */ - public function testChainedJoinWithEmptyCollectionsWithAliasedUserEntity() + public function testChainedJoinWithEmptyCollectionsWithAliasedUserEntity(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', 'user'); $rsm->addJoinedEntityResult( CmsArticle::class, @@ -1196,7 +1200,7 @@ public function testChainedJoinWithEmptyCollectionsWithAliasedUserEntity() 'a__id' => null, 'a__topic' => null, 'c__id' => null, - 'c__topic' => null + 'c__topic' => null, ], [ 'u__id' => '2', @@ -1204,7 +1208,7 @@ public function testChainedJoinWithEmptyCollectionsWithAliasedUserEntity() 'a__id' => null, 'a__topic' => null, 'c__id' => null, - 'c__topic' => null + 'c__topic' => null, ], ]; @@ -1228,9 +1232,9 @@ public function testChainedJoinWithEmptyCollectionsWithAliasedUserEntity() * SELECT PARTIAL u.{id, name} * FROM Doctrine\Tests\Models\CMS\CmsUser u */ - public function testResultIteration() + public function testResultIteration(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); @@ -1239,12 +1243,12 @@ public function testResultIteration() $resultSet = [ [ 'u__id' => '1', - 'u__name' => 'romanb' + 'u__name' => 'romanb', ], [ 'u__id' => '2', - 'u__name' => 'jwage' - ] + 'u__name' => 'jwage', + ], ]; $hydrator = new ObjectHydrator($this->_em); @@ -1260,10 +1264,10 @@ public function testResultIteration() $this->assertEquals(1, count($row)); $this->assertInstanceOf(CmsUser::class, $row[0]); - if ($rowNum == 0) { + if ($rowNum === 0) { $this->assertEquals(1, $row[0]->id); $this->assertEquals('romanb', $row[0]->name); - } else if ($rowNum == 1) { + } elseif ($rowNum === 1) { $this->assertEquals(2, $row[0]->id); $this->assertEquals('jwage', $row[0]->name); } @@ -1303,9 +1307,9 @@ public function testResultIteration() * SELECT PARTIAL u.{id, name} * FROM Doctrine\Tests\Models\CMS\CmsUser u */ - public function testResultIterationWithAliasedUserEntity() + public function testResultIterationWithAliasedUserEntity(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', 'user'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); @@ -1314,12 +1318,12 @@ public function testResultIterationWithAliasedUserEntity() $resultSet = [ [ 'u__id' => '1', - 'u__name' => 'romanb' + 'u__name' => 'romanb', ], [ 'u__id' => '2', - 'u__name' => 'jwage' - ] + 'u__name' => 'jwage', + ], ]; $hydrator = new ObjectHydrator($this->_em); @@ -1336,10 +1340,10 @@ public function testResultIterationWithAliasedUserEntity() $this->assertArrayHasKey('user', $row[0]); $this->assertInstanceOf(CmsUser::class, $row[0]['user']); - if ($rowNum == 0) { + if ($rowNum === 0) { $this->assertEquals(1, $row[0]['user']->id); $this->assertEquals('romanb', $row[0]['user']->name); - } else if ($rowNum == 1) { + } elseif ($rowNum === 1) { $this->assertEquals(2, $row[0]['user']->id); $this->assertEquals('jwage', $row[0]['user']->name); } @@ -1385,9 +1389,9 @@ public function testResultIterationWithAliasedUserEntity() * * @group DDC-809 */ - public function testManyToManyHydration() + public function testManyToManyHydration(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); @@ -1508,9 +1512,9 @@ public function testManyToManyHydration() * * @group DDC-809 */ - public function testManyToManyHydrationWithAliasedUserEntity() + public function testManyToManyHydrationWithAliasedUserEntity(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', 'user'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); @@ -1633,9 +1637,9 @@ public function testManyToManyHydrationWithAliasedUserEntity() * @group DDC-1358 * @dataProvider provideDataForUserEntityResult */ - public function testMissingIdForRootEntity($userEntityKey) + public function testMissingIdForRootEntity($userEntityKey): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); @@ -1670,7 +1674,7 @@ public function testMissingIdForRootEntity($userEntityKey) $hydrator = new ObjectHydrator($this->_em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); - $this->assertEquals(4, count($result), "Should hydrate four results."); + $this->assertEquals(4, count($result), 'Should hydrate four results.'); $this->assertEquals('ROMANB', $result[0]['nameUpper']); $this->assertEquals('ROMANB', $result[1]['nameUpper']); @@ -1692,9 +1696,9 @@ public function testMissingIdForRootEntity($userEntityKey) * @group DDC-1358 * @dataProvider provideDataForUserEntityResult */ - public function testMissingIdForCollectionValuedChildEntity($userEntityKey) + public function testMissingIdForCollectionValuedChildEntity($userEntityKey): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addJoinedEntityResult( CmsPhonenumber::class, @@ -1720,20 +1724,20 @@ public function testMissingIdForCollectionValuedChildEntity($userEntityKey) 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', - 'p__phonenumber' => null + 'p__phonenumber' => null, ], [ 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => 'JWAGE', - 'p__phonenumber' => '91' + 'p__phonenumber' => '91', ], [ 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => 'JWAGE', - 'p__phonenumber' => null - ] + 'p__phonenumber' => null, + ], ]; $stmt = new HydratorMockStatement($resultSet); @@ -1754,9 +1758,9 @@ public function testMissingIdForCollectionValuedChildEntity($userEntityKey) * @group DDC-1358 * @dataProvider provideDataForUserEntityResult */ - public function testMissingIdForSingleValuedChildEntity($userEntityKey) + public function testMissingIdForSingleValuedChildEntity($userEntityKey): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addJoinedEntityResult( CmsAddress::class, @@ -1808,9 +1812,9 @@ public function testMissingIdForSingleValuedChildEntity($userEntityKey) * @group DDC-1385 * @dataProvider provideDataForUserEntityResult */ - public function testIndexByAndMixedResult($userEntityKey) + public function testIndexByAndMixedResult($userEntityKey): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); @@ -1852,9 +1856,9 @@ public function testIndexByAndMixedResult($userEntityKey) * @group DDC-1385 * @dataProvider provideDataForUserEntityResult */ - public function testIndexByScalarsOnly($userEntityKey) + public function testIndexByScalarsOnly($userEntityKey): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addScalarResult('sclr0', 'nameUpper', 'string'); $rsm->addIndexByScalar('sclr0'); @@ -1862,12 +1866,8 @@ public function testIndexByScalarsOnly($userEntityKey) // Faked result set $resultSet = [ //row1 - [ - 'sclr0' => 'ROMANB', - ], - [ - 'sclr0' => 'JWAGE', - ], + ['sclr0' => 'ROMANB'], + ['sclr0' => 'JWAGE'], ]; $stmt = new HydratorMockStatement($resultSet); @@ -1877,21 +1877,20 @@ public function testIndexByScalarsOnly($userEntityKey) $this->assertEquals( [ 'ROMANB' => ['nameUpper' => 'ROMANB'], - 'JWAGE' => ['nameUpper' => 'JWAGE'] + 'JWAGE' => ['nameUpper' => 'JWAGE'], ], $result ); } - /** * @group DDC-1470 */ - public function testMissingMetaMappingException() + public function testMissingMetaMappingException(): void { $this->expectException('Doctrine\ORM\Internal\Hydration\HydrationException'); $this->expectExceptionMessage('The meta mapping for the discriminator column "c_discr" is missing for "Doctrine\Tests\Models\Company\CompanyFixContract" using the DQL alias "c".'); - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CompanyFixContract::class, 'c'); $rsm->addJoinedEntityResult(CompanyEmployee::class, 'e', 'c', 'salesPerson'); @@ -1899,10 +1898,10 @@ public function testMissingMetaMappingException() $rsm->setDiscriminatorColumn('c', 'c_discr'); $resultSet = [ - [ - 'c__id' => '1', - 'c_discr' => 'fix', - ], + [ + 'c__id' => '1', + 'c_discr' => 'fix', + ], ]; $stmt = new HydratorMockStatement($resultSet); @@ -1913,11 +1912,11 @@ public function testMissingMetaMappingException() /** * @group DDC-1470 */ - public function testMissingDiscriminatorColumnException() + public function testMissingDiscriminatorColumnException(): void { $this->expectException('Doctrine\ORM\Internal\Hydration\HydrationException'); $this->expectExceptionMessage('The discriminator column "discr" is missing for "Doctrine\Tests\Models\Company\CompanyEmployee" using the DQL alias "e".'); - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CompanyFixContract::class, 'c'); $rsm->addJoinedEntityResult(CompanyEmployee::class, 'e', 'c', 'salesPerson'); @@ -1930,12 +1929,12 @@ public function testMissingDiscriminatorColumnException() $rsm->setDiscriminatorColumn('e', 'e_discr'); $resultSet = [ - [ - 'c__id' => '1', - 'c_discr' => 'fix', - 'e__id' => '1', - 'e__name' => 'Fabio B. Silva' - ], + [ + 'c__id' => '1', + 'c_discr' => 'fix', + 'e__id' => '1', + 'e__name' => 'Fabio B. Silva', + ], ]; $stmt = new HydratorMockStatement($resultSet); @@ -1946,11 +1945,11 @@ public function testMissingDiscriminatorColumnException() /** * @group DDC-3076 */ - public function testInvalidDiscriminatorValueException() + public function testInvalidDiscriminatorValueException(): void { $this->expectException('Doctrine\ORM\Internal\Hydration\HydrationException'); $this->expectExceptionMessage('The discriminator value "subworker" is invalid. It must be one of "person", "manager", "employee".'); - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CompanyPerson::class, 'p'); $rsm->addFieldResult('p', 'p__id', 'id'); @@ -1959,11 +1958,11 @@ public function testInvalidDiscriminatorValueException() $rsm->setDiscriminatorColumn('p', 'discr'); $resultSet = [ - [ - 'p__id' => '1', - 'p__name' => 'Fabio B. Silva', - 'discr' => 'subworker' - ], + [ + 'p__id' => '1', + 'p__name' => 'Fabio B. Silva', + 'discr' => 'subworker', + ], ]; $stmt = new HydratorMockStatement($resultSet); @@ -1971,9 +1970,9 @@ public function testInvalidDiscriminatorValueException() $hydrator->hydrateAll($stmt, $rsm); } - public function testFetchJoinCollectionValuedAssociationWithDefaultArrayValue() + public function testFetchJoinCollectionValuedAssociationWithDefaultArrayValue(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(EntityWithArrayDefaultArrayValueM2M::class, 'e1', null); $rsm->addJoinedEntityResult(SimpleEntity::class, 'e2', 'e1', 'collection'); @@ -1984,7 +1983,7 @@ public function testFetchJoinCollectionValuedAssociationWithDefaultArrayValue() [ 'a1__id' => '1', 'e2__id' => '1', - ] + ], ]; $stmt = new HydratorMockStatement($resultSet); diff --git a/tests/Doctrine/Tests/ORM/Hydration/ResultSetMappingTest.php b/tests/Doctrine/Tests/ORM/Hydration/ResultSetMappingTest.php index 6eb33126c0b..05ac6b73f10 100644 --- a/tests/Doctrine/Tests/ORM/Hydration/ResultSetMappingTest.php +++ b/tests/Doctrine/Tests/ORM/Hydration/ResultSetMappingTest.php @@ -1,44 +1,43 @@ _rsm = new ResultSetMapping; - $this->_em = $this->_getTestEntityManager(); + $this->_rsm = new ResultSetMapping(); + $this->_em = $this->_getTestEntityManager(); } /** * For SQL: SELECT id, status, username, name FROM cms_users */ - public function testBasicResultSetMapping() + public function testBasicResultSetMapping(): void { $this->_rsm->addEntityResult( CmsUser::class, @@ -54,9 +53,9 @@ public function testBasicResultSetMapping() $this->assertFalse($this->_rsm->isScalarResult('username')); $this->assertFalse($this->_rsm->isScalarResult('name')); - $this->assertTrue($this->_rsm->getClassName('u') == CmsUser::class); + $this->assertTrue($this->_rsm->getClassName('u') === CmsUser::class); $class = $this->_rsm->getDeclaringClass('id'); - $this->assertTrue($class == CmsUser::class); + $this->assertTrue($class === CmsUser::class); $this->assertEquals('u', $this->_rsm->getEntityAlias('id')); $this->assertEquals('u', $this->_rsm->getEntityAlias('status')); @@ -74,12 +73,12 @@ public function testBasicResultSetMapping() * * Fluent interface test, not a real result set mapping */ - public function testFluentInterface() + public function testFluentInterface(): void { $rms = $this->_rsm; - $this->_rsm->addEntityResult(CmsUser::class,'u'); - $this->_rsm->addJoinedEntityResult(CmsPhonenumber::class,'p','u','phonenumbers'); + $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'); @@ -101,77 +100,75 @@ public function testFluentInterface() /** * @group DDC-1663 */ - public function testAddNamedNativeQueryResultSetMapping() + public function testAddNamedNativeQueryResultSetMapping(): void { $cm = new ClassMetadata(CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $cm->mapOneToOne( [ - 'fieldName' => 'email', - 'targetEntity' => CmsEmail::class, - 'cascade' => ['persist'], - 'inversedBy' => 'user', - 'orphanRemoval' => false, - 'joinColumns' => [ - [ - 'nullable' => true, - 'referencedColumnName' => 'id', - ] - ] + 'fieldName' => 'email', + 'targetEntity' => CmsEmail::class, + 'cascade' => ['persist'], + 'inversedBy' => 'user', + 'orphanRemoval' => false, + 'joinColumns' => [ + [ + 'nullable' => true, + 'referencedColumnName' => 'id', + ], + ], ] ); $cm->addNamedNativeQuery( [ - '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', + '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', ] ); $cm->addSqlResultSetMapping( [ - 'name' => 'find-all', - 'entities' => [ - [ - 'entityClass' => '__CLASS__', - 'fields' => [ - [ - 'name' => 'id', - 'column'=> 'user_id' + 'name' => 'find-all', + 'entities' => [ + [ + 'entityClass' => '__CLASS__', + 'fields' => [ + [ + 'name' => 'id', + 'column' => 'user_id', + ], + [ + 'name' => 'name', + 'column' => 'name', + ], ], - [ - 'name' => 'name', - 'column'=> 'name' - ] - ] - ], - [ - 'entityClass' => 'CmsEmail', - 'fields' => [ - [ - 'name' => 'id', - 'column'=> 'email_id' + ], + [ + 'entityClass' => 'CmsEmail', + 'fields' => [ + [ + 'name' => 'id', + 'column' => 'email_id', + ], + [ + 'name' => 'email', + 'column' => 'email', + ], ], - [ - '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 ResultSetMappingBuilder($this->_em); $rsm->addNamedNativeQueryMapping($cm, $queryMapping); $this->assertEquals('scalarColumn', $rsm->getScalarAlias('scalarColumn')); @@ -182,7 +179,6 @@ public function testAddNamedNativeQueryResultSetMapping() $this->assertEquals(CmsUser::class, $rsm->getDeclaringClass('name')); $this->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')); @@ -191,39 +187,35 @@ public function testAddNamedNativeQueryResultSetMapping() } /** - * @group DDC-1663 - */ - public function testAddNamedNativeQueryResultSetMappingWithoutFields() + * @group DDC-1663 + */ + public function testAddNamedNativeQueryResultSetMappingWithoutFields(): void { $cm = new ClassMetadata(CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $cm->addNamedNativeQuery( [ - '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', + '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', ] ); $cm->addSqlResultSetMapping( [ - 'name' => 'find-all', - 'entities' => [ - [ - 'entityClass' => '__CLASS__', - ] - ], - 'columns' => [ - [ - 'name' => 'scalarColumn' - ] - ] + 'name' => 'find-all', + 'entities' => [ + ['entityClass' => '__CLASS__'], + ], + 'columns' => [ + ['name' => 'scalarColumn'], + ], ] ); $queryMapping = $cm->getNamedNativeQuery('find-all'); - $rsm = new \Doctrine\ORM\Query\ResultSetMappingBuilder($this->_em); + $rsm = new ResultSetMappingBuilder($this->_em); $rsm->addNamedNativeQueryMapping($cm, $queryMapping); @@ -242,7 +234,7 @@ public function testAddNamedNativeQueryResultSetMappingWithoutFields() /** * @group DDC-1663 */ - public function testAddNamedNativeQueryResultClass() + public function testAddNamedNativeQueryResultClass(): void { $cm = new ClassMetadata(CmsUser::class); @@ -250,14 +242,14 @@ public function testAddNamedNativeQueryResultClass() $cm->addNamedNativeQuery( [ - 'name' => 'find-all', - 'resultClass' => '__CLASS__', - 'query' => 'SELECT * FROM cms_users', + 'name' => 'find-all', + 'resultClass' => '__CLASS__', + 'query' => 'SELECT * FROM cms_users', ] ); $queryMapping = $cm->getNamedNativeQuery('find-all'); - $rsm = new \Doctrine\ORM\Query\ResultSetMappingBuilder($this->_em); + $rsm = new ResultSetMappingBuilder($this->_em); $rsm->addNamedNativeQueryMapping($cm, $queryMapping); @@ -275,15 +267,14 @@ public function testAddNamedNativeQueryResultClass() /** * @group DDC-117 */ - public function testIndexByMetadataColumn() + public function testIndexByMetadataColumn(): void { $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->addMetaResult('lu', '_source', '_source', true, 'integer'); + $this->_rsm->addMetaResult('lu', '_target', '_target', true, 'integer'); $this->_rsm->addIndexBy('lu', '_source'); $this->assertTrue($this->_rsm->hasIndexBy('lu')); } } - diff --git a/tests/Doctrine/Tests/ORM/Hydration/ScalarHydratorTest.php b/tests/Doctrine/Tests/ORM/Hydration/ScalarHydratorTest.php index dd2aab48f5a..c4b8f11fd58 100644 --- a/tests/Doctrine/Tests/ORM/Hydration/ScalarHydratorTest.php +++ b/tests/Doctrine/Tests/ORM/Hydration/ScalarHydratorTest.php @@ -1,10 +1,12 @@ addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); @@ -23,16 +25,15 @@ public function testNewHydrationSimpleEntityQuery() $resultSet = [ [ 'u__id' => '1', - 'u__name' => 'romanb' + 'u__name' => 'romanb', ], [ 'u__id' => '2', - 'u__name' => 'jwage' - ] + 'u__name' => 'jwage', + ], ]; - - $stmt = new HydratorMockStatement($resultSet); + $stmt = new HydratorMockStatement($resultSet); $hydrator = new ScalarHydrator($this->_em); $result = $hydrator->hydrateAll($stmt, $rsm); @@ -48,7 +49,7 @@ public function testNewHydrationSimpleEntityQuery() /** * @group DDC-407 */ - public function testHydrateScalarResults() + public function testHydrateScalarResults(): void { $rsm = new ResultSetMapping(); $rsm->addScalarResult('foo1', 'foo', 'string'); @@ -63,7 +64,7 @@ public function testHydrateScalarResults() ], ]; - $stmt = new HydratorMockStatement($resultSet); + $stmt = new HydratorMockStatement($resultSet); $hydrator = new ScalarHydrator($this->_em); self::assertCount(1, $hydrator->hydrateAll($stmt, $rsm)); @@ -72,9 +73,9 @@ public function testHydrateScalarResults() /** * @group DDC-644 */ - public function testSkipUnknownColumns() + public function testSkipUnknownColumns(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); @@ -93,7 +94,7 @@ public function testSkipUnknownColumns() ], ]; - $stmt = new HydratorMockStatement($resultSet); + $stmt = new HydratorMockStatement($resultSet); $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 76c286ab545..023d3e8518f 100644 --- a/tests/Doctrine/Tests/ORM/Hydration/SimpleObjectHydratorTest.php +++ b/tests/Doctrine/Tests/ORM/Hydration/SimpleObjectHydratorTest.php @@ -1,7 +1,10 @@ expectException('Doctrine\ORM\Internal\Hydration\HydrationException'); $this->expectExceptionMessage('The discriminator column "discr" is missing for "Doctrine\Tests\Models\Company\CompanyPerson" using the DQL alias "p".'); - $rsm = new ResultSetMapping; + $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->setDiscriminatorColumn('p', 'discr'); $resultSet = [ - [ - 'u__id' => '1', - 'u__name' => 'Fabio B. Silva' - ], + [ + 'u__id' => '1', + 'u__name' => 'Fabio B. Silva', + ], ]; - $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() + public function testExtraFieldInResultSetShouldBeIgnore(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsAddress::class, 'a'); $rsm->addFieldResult('a', 'a__id', 'id'); $rsm->addFieldResult('a', 'a__city', 'city'); @@ -47,28 +50,28 @@ public function testExtraFieldInResultSetShouldBeIgnore() [ 'a__id' => '1', 'a__city' => 'Cracow', - 'doctrine_rownum' => '1' + 'doctrine_rownum' => '1', ], ]; - $expectedEntity = new \Doctrine\Tests\Models\CMS\CmsAddress(); - $expectedEntity->id = 1; + $expectedEntity = new 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); + $stmt = new HydratorMockStatement($resultSet); + $hydrator = new SimpleObjectHydrator($this->_em); + $result = $hydrator->hydrateAll($stmt, $rsm); $this->assertEquals($result[0], $expectedEntity); } /** * @group DDC-3076 */ - public function testInvalidDiscriminatorValueException() + public function testInvalidDiscriminatorValueException(): void { $this->expectException('Doctrine\ORM\Internal\Hydration\HydrationException'); $this->expectExceptionMessage('The discriminator value "subworker" is invalid. It must be one of "person", "manager", "employee".'); - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CompanyPerson::class, 'p'); @@ -78,24 +81,24 @@ public function testInvalidDiscriminatorValueException() $rsm->setDiscriminatorColumn('p', 'discr'); $resultSet = [ - [ - 'p__id' => '1', - 'p__name' => 'Fabio B. Silva', - 'discr' => 'subworker' - ], + [ + 'p__id' => '1', + 'p__name' => 'Fabio B. Silva', + 'discr' => 'subworker', + ], ]; - $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); } /** * @group issue-5989 */ - public function testNullValueShouldNotOverwriteFieldWithSameNameInJoinedInheritance() + public function testNullValueShouldNotOverwriteFieldWithSameNameInJoinedInheritance(): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(Issue5989Person::class, 'p'); $rsm->addFieldResult('p', 'p__id', 'id'); $rsm->addFieldResult('p', 'm__tags', 'tags', Issue5989Manager::class); @@ -106,17 +109,17 @@ public function testNullValueShouldNotOverwriteFieldWithSameNameInJoinedInherita 'p__id' => '1', 'm__tags' => 'tag1,tag2', 'e__tags' => null, - 'discr' => 'manager' + 'discr' => 'manager', ], ]; - $expectedEntity = new Issue5989Manager(); - $expectedEntity->id = 1; + $expectedEntity = new Issue5989Manager(); + $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); + $stmt = new HydratorMockStatement($resultSet); + $hydrator = new SimpleObjectHydrator($this->_em); + $result = $hydrator->hydrateAll($stmt, $rsm); $this->assertEquals($result[0], $expectedEntity); } } diff --git a/tests/Doctrine/Tests/ORM/Hydration/SingleScalarHydratorTest.php b/tests/Doctrine/Tests/ORM/Hydration/SingleScalarHydratorTest.php index f9d91be638d..0d7dc1b380d 100644 --- a/tests/Doctrine/Tests/ORM/Hydration/SingleScalarHydratorTest.php +++ b/tests/Doctrine/Tests/ORM/Hydration/SingleScalarHydratorTest.php @@ -1,13 +1,17 @@ [ 'name' => 'result1', 'resultSet' => [ - [ - 'u__name' => 'romanb', - ], + ['u__name' => 'romanb'], ], ], // valid [ 'name' => 'result2', 'resultSet' => [ - [ - 'u__id' => '1', - ], + ['u__id' => '1'], ], ], // invalid @@ -46,12 +46,8 @@ public static function singleScalarResultSetProvider(): array [ 'name' => 'result4', 'resultSet' => [ - [ - 'u__id' => '1', - ], - [ - 'u__id' => '2', - ], + ['u__id' => '1'], + ['u__id' => '2'], ], ], ]; @@ -62,19 +58,20 @@ public static function singleScalarResultSetProvider(): array * * @dataProvider singleScalarResultSetProvider */ - public function testHydrateSingleScalar($name, $resultSet) + public function testHydrateSingleScalar($name, $resultSet): void { - $rsm = new ResultSetMapping; + $rsm = new ResultSetMapping(); $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); - $stmt = new HydratorMockStatement($resultSet); + $stmt = new HydratorMockStatement($resultSet); $hydrator = new SingleScalarHydrator($this->_em); if ($name === 'result1') { $result = $hydrator->hydrateAll($stmt, $rsm); $this->assertEquals('romanb', $result); + return; } diff --git a/tests/Doctrine/Tests/ORM/Id/AssignedGeneratorTest.php b/tests/Doctrine/Tests/ORM/Id/AssignedGeneratorTest.php index 86f8b5a0922..0f6cf64ab16 100644 --- a/tests/Doctrine/Tests/ORM/Id/AssignedGeneratorTest.php +++ b/tests/Doctrine/Tests/ORM/Id/AssignedGeneratorTest.php @@ -1,5 +1,7 @@ _em = $this->_getTestEntityManager(); - $this->_assignedGen = new AssignedGenerator; + $this->_em = $this->_getTestEntityManager(); + $this->_assignedGen = new AssignedGenerator(); } /** * @dataProvider entitiesWithoutId */ - public function testThrowsExceptionIfIdNotAssigned($entity) + public function testThrowsExceptionIfIdNotAssigned($entity): void { $this->expectException(ORMException::class); @@ -40,29 +40,31 @@ public function entitiesWithoutId(): array ]; } - public function testCorrectIdGeneration() + public function testCorrectIdGeneration(): void { - $entity = new AssignedSingleIdEntity; + $entity = new AssignedSingleIdEntity(); $entity->myId = 1; - $id = $this->_assignedGen->generate($this->_em, $entity); + $id = $this->_assignedGen->generate($this->_em, $entity); $this->assertEquals(['myId' => 1], $id); - $entity = new AssignedCompositeIdEntity; + $entity = new AssignedCompositeIdEntity(); $entity->myId2 = 2; $entity->myId1 = 4; - $id = $this->_assignedGen->generate($this->_em, $entity); + $id = $this->_assignedGen->generate($this->_em, $entity); $this->assertEquals(['myId1' => 4, 'myId2' => 2], $id); } } /** @Entity */ -class AssignedSingleIdEntity { +class AssignedSingleIdEntity +{ /** @Id @Column(type="integer") */ public $myId; } /** @Entity */ -class AssignedCompositeIdEntity { +class AssignedCompositeIdEntity +{ /** @Id @Column(type="integer") */ public $myId1; /** @Id @Column(type="integer") */ diff --git a/tests/Doctrine/Tests/ORM/Id/SequenceGeneratorTest.php b/tests/Doctrine/Tests/ORM/Id/SequenceGeneratorTest.php index 5e4247715b0..06db2634f1e 100644 --- a/tests/Doctrine/Tests/ORM/Id/SequenceGeneratorTest.php +++ b/tests/Doctrine/Tests/ORM/Id/SequenceGeneratorTest.php @@ -1,7 +1,10 @@ connection); } - public function testGeneration() : void + public function testGeneration(): void { - $this->connection->setFetchOneException(new \BadMethodCallException( + $this->connection->setFetchOneException(new BadMethodCallException( 'Fetch* method used. Query method should be used instead, ' . 'as NEXTVAL should be run on a master server in master-slave setup.' )); for ($i = 0; $i < 42; ++$i) { - if ($i % 10 == 0) { - $this->connection->setQueryResult(new StatementArrayMock([[(int)($i / 10) * 10]])); + if ($i % 10 === 0) { + $this->connection->setQueryResult(new StatementArrayMock([[(int) ($i / 10) * 10]])); } $id = $this->sequenceGenerator->generate($this->entityManager, null); self::assertSame($i, $id); - self::assertSame((int)($i / 10) * 10 + 10, $this->sequenceGenerator->getCurrentMaxValue()); + self::assertSame((int) ($i / 10) * 10 + 10, $this->sequenceGenerator->getCurrentMaxValue()); self::assertSame($i + 1, $this->sequenceGenerator->getNextValue()); } } } - diff --git a/tests/Doctrine/Tests/ORM/Internal/HydrationCompleteHandlerTest.php b/tests/Doctrine/Tests/ORM/Internal/HydrationCompleteHandlerTest.php index c3cfe4052ec..28b1a280557 100644 --- a/tests/Doctrine/Tests/ORM/Internal/HydrationCompleteHandlerTest.php +++ b/tests/Doctrine/Tests/ORM/Internal/HydrationCompleteHandlerTest.php @@ -1,4 +1,7 @@ listenersInvoker = $this->createMock(ListenersInvoker::class); $this->entityManager = $this->createMock(EntityManagerInterface::class); @@ -62,13 +60,11 @@ protected function setUp() : void /** * @dataProvider invocationFlagProvider - * - * @param int $listenersFlag */ - public function testDefersPostLoadOfEntity($listenersFlag) + public function testDefersPostLoadOfEntity(int $listenersFlag): void { - /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */ - $metadata = $this->createMock(ClassMetadata::class); + $metadata = $this->createMock(ClassMetadata::class); + assert($metadata instanceof ClassMetadata); $entity = new stdClass(); $entityManager = $this->entityManager; @@ -89,7 +85,7 @@ public function testDefersPostLoadOfEntity($listenersFlag) $metadata, Events::postLoad, $entity, - $this->callback(function (LifecycleEventArgs $args) use ($entityManager, $entity) { + $this->callback(static function (LifecycleEventArgs $args) use ($entityManager, $entity) { return $entity === $args->getEntity() && $entityManager === $args->getObjectManager(); }), $listenersFlag @@ -100,14 +96,12 @@ public function testDefersPostLoadOfEntity($listenersFlag) /** * @dataProvider invocationFlagProvider - * - * @param int $listenersFlag */ - public function testDefersPostLoadOfEntityOnlyOnce($listenersFlag) + public function testDefersPostLoadOfEntityOnlyOnce(int $listenersFlag): void { - /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */ $metadata = $this->createMock(ClassMetadata::class); - $entity = new stdClass(); + assert($metadata instanceof ClassMetadata); + $entity = new stdClass(); $this ->listenersInvoker @@ -126,18 +120,16 @@ public function testDefersPostLoadOfEntityOnlyOnce($listenersFlag) /** * @dataProvider invocationFlagProvider - * - * @param int $listenersFlag */ - public function testDefersMultiplePostLoadOfEntity($listenersFlag) + public function testDefersMultiplePostLoadOfEntity(int $listenersFlag): void { - /* @var $metadata1 \Doctrine\ORM\Mapping\ClassMetadata */ - /* @var $metadata2 \Doctrine\ORM\Mapping\ClassMetadata */ - $metadata1 = $this->createMock(ClassMetadata::class); - $metadata2 = $this->createMock(ClassMetadata::class); - $entity1 = new stdClass(); - $entity2 = new stdClass(); - $entityManager = $this->entityManager; + /** @var ClassMetadata $metadata1 */ + /** @var ClassMetadata $metadata2 */ + $metadata1 = $this->createMock(ClassMetadata::class); + $metadata2 = $this->createMock(ClassMetadata::class); + $entity1 = new stdClass(); + $entity2 = new stdClass(); + $entityManager = $this->entityManager; $this ->listenersInvoker @@ -157,7 +149,7 @@ public function testDefersMultiplePostLoadOfEntity($listenersFlag) $this->logicalOr($metadata1, $metadata2), Events::postLoad, $this->logicalOr($entity1, $entity2), - $this->callback(function (LifecycleEventArgs $args) use ($entityManager, $entity1, $entity2) { + $this->callback(static function (LifecycleEventArgs $args) use ($entityManager, $entity1, $entity2) { return in_array($args->getEntity(), [$entity1, $entity2], true) && $entityManager === $args->getObjectManager(); }), @@ -167,11 +159,11 @@ public function testDefersMultiplePostLoadOfEntity($listenersFlag) $this->handler->hydrationComplete(); } - public function testSkipsDeferredPostLoadOfMetadataWithNoInvokedListeners() + public function testSkipsDeferredPostLoadOfMetadataWithNoInvokedListeners(): void { - /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */ $metadata = $this->createMock(ClassMetadata::class); - $entity = new stdClass(); + assert($metadata instanceof ClassMetadata); + $entity = new stdClass(); $this ->listenersInvoker diff --git a/tests/Doctrine/Tests/ORM/LazyCriteriaCollectionTest.php b/tests/Doctrine/Tests/ORM/LazyCriteriaCollectionTest.php index 9cde0e758a9..ee2b4b3212f 100644 --- a/tests/Doctrine/Tests/ORM/LazyCriteriaCollectionTest.php +++ b/tests/Doctrine/Tests/ORM/LazyCriteriaCollectionTest.php @@ -1,5 +1,7 @@ - * * @covers \Doctrine\ORM\LazyCriteriaCollection */ class LazyCriteriaCollectionTest extends TestCase { - /** - * @var \Doctrine\ORM\Persisters\Entity\EntityPersister|\PHPUnit_Framework_MockObject_MockObject - */ + /** @var EntityPersister|PHPUnit_Framework_MockObject_MockObject */ private $persister; - /** - * @var Criteria - */ + /** @var Criteria */ private $criteria; - /** - * @var LazyCriteriaCollection - */ + /** @var LazyCriteriaCollection */ private $lazyCriteriaCollection; - /** - * {@inheritDoc} - */ - protected function setUp() : void + protected function setUp(): void { $this->persister = $this->createMock(EntityPersister::class); $this->criteria = new Criteria(); $this->lazyCriteriaCollection = new LazyCriteriaCollection($this->persister, $this->criteria); } - public function testCountIsCached() + public function testCountIsCached(): void { $this->persister->expects($this->once())->method('count')->with($this->criteria)->will($this->returnValue(10)); @@ -50,7 +42,7 @@ public function testCountIsCached() $this->assertSame(10, $this->lazyCriteriaCollection->count()); } - public function testCountIsCachedEvenWithZeroResult() + public function testCountIsCachedEvenWithZeroResult(): void { $this->persister->expects($this->once())->method('count')->with($this->criteria)->will($this->returnValue(0)); @@ -59,7 +51,7 @@ public function testCountIsCachedEvenWithZeroResult() $this->assertSame(0, $this->lazyCriteriaCollection->count()); } - public function testCountUsesWrappedCollectionWhenInitialized() + public function testCountUsesWrappedCollectionWhenInitialized(): void { $this ->persister @@ -76,7 +68,7 @@ public function testCountUsesWrappedCollectionWhenInitialized() $this->assertSame(3, $this->lazyCriteriaCollection->count()); } - public function testMatchingUsesThePersisterOnlyOnce() + public function testMatchingUsesThePersisterOnlyOnce(): void { $foo = new stdClass(); $bar = new stdClass(); @@ -105,21 +97,21 @@ public function testMatchingUsesThePersisterOnlyOnce() $this->assertEquals([$foo], $this->lazyCriteriaCollection->matching($criteria)->toArray()); } - public function testIsEmptyUsesCountWhenNotInitialized() + public function testIsEmptyUsesCountWhenNotInitialized(): void { $this->persister->expects($this->once())->method('count')->with($this->criteria)->will($this->returnValue(0)); $this->assertTrue($this->lazyCriteriaCollection->isEmpty()); } - public function testIsEmptyIsFalseIfCountIsNotZero() + public function testIsEmptyIsFalseIfCountIsNotZero(): void { $this->persister->expects($this->once())->method('count')->with($this->criteria)->will($this->returnValue(1)); $this->assertFalse($this->lazyCriteriaCollection->isEmpty()); } - public function testIsEmptyUsesWrappedCollectionWhenInitialized() + public function testIsEmptyUsesWrappedCollectionWhenInitialized(): void { $this ->persister diff --git a/tests/Doctrine/Tests/ORM/Mapping/AbstractMappingDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/AbstractMappingDriverTest.php index 3eab2d6ae5c..84be3344b2b 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/AbstractMappingDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/AbstractMappingDriverTest.php @@ -1,5 +1,7 @@ _loadDriver(); - $em = $em ?: $this->_getTestEntityManager(); - $factory = new ClassMetadataFactory(); + $driver = $this->_loadDriver(); + $em = $em ?: $this->_getTestEntityManager(); + $factory = new ClassMetadataFactory(); $em->getConfiguration()->setMetadataDriverImpl($driver); $factory->setEntityManager($em); @@ -80,72 +89,80 @@ public function testEntityTableNameAndInheritance() /** * @depends testEntityTableNameAndInheritance - * @param ClassMetadata $class */ - public function testEntityIndexes($class) + public function testEntityIndexes(ClassMetadata $class) { $this->assertArrayHasKey('indexes', $class->table, 'ClassMetadata should have indexes key in table property.'); $this->assertEquals( [ - 'name_idx' => ['columns' => ['name']], - 0 => ['columns' => ['user_email']] - ], $class->table['indexes']); + 'name_idx' => ['columns' => ['name']], + 0 => ['columns' => ['user_email']], + ], + $class->table['indexes'] + ); return $class; } - public function testEntityIndexFlagsAndPartialIndexes() + public function testEntityIndexFlagsAndPartialIndexes(): void { $class = $this->createClassMetadata(Comment::class); $this->assertEquals( [ - 0 => [ - 'columns' => ['content'], - 'flags' => ['fulltext'], - 'options' => ['where' => 'content IS NOT NULL'], - ] - ], $class->table['indexes']); + 0 => [ + 'columns' => ['content'], + 'flags' => ['fulltext'], + 'options' => ['where' => 'content IS NOT NULL'], + ], + ], + $class->table['indexes'] + ); } /** * @depends testEntityTableNameAndInheritance - * @param ClassMetadata $class */ - public function testEntityUniqueConstraints($class) + public function testEntityUniqueConstraints(ClassMetadata $class) { - $this->assertArrayHasKey('uniqueConstraints', $class->table, - 'ClassMetadata should have uniqueConstraints key in table property when Unique Constraints are set.'); + $this->assertArrayHasKey( + 'uniqueConstraints', + $class->table, + 'ClassMetadata should have uniqueConstraints key in table property when Unique Constraints are set.' + ); $this->assertEquals( [ - "search_idx" => ["columns" => ["name", "user_email"], 'options' => ['where' => 'name IS NOT NULL']] - ], $class->table['uniqueConstraints']); + 'search_idx' => ['columns' => ['name', 'user_email'], 'options' => ['where' => 'name IS NOT NULL']], + ], + $class->table['uniqueConstraints'] + ); return $class; } /** * @depends testEntityTableNameAndInheritance - * @param ClassMetadata $class */ - public function testEntityOptions($class) + public function testEntityOptions(ClassMetadata $class) { $this->assertArrayHasKey('options', $class->table, 'ClassMetadata should have options key in table property.'); $this->assertEquals( [ - 'foo' => 'bar', 'baz' => ['key' => 'val'] - ], $class->table['options']); + 'foo' => 'bar', + 'baz' => ['key' => 'val'], + ], + $class->table['options'] + ); return $class; } /** * @depends testEntityOptions - * @param ClassMetadata $class */ - public function testEntitySequence($class) + public function testEntitySequence(ClassMetadata $class): void { $this->assertIsArray($class->sequenceGeneratorDefinition, 'No Sequence Definition set on this driver.'); $this->assertEquals( @@ -158,24 +175,26 @@ public function testEntitySequence($class) ); } - public function testEntityCustomGenerator() + public function testEntityCustomGenerator(): void { $class = $this->createClassMetadata(Animal::class); - $this->assertEquals(ClassMetadata::GENERATOR_TYPE_CUSTOM, - $class->generatorType, "Generator Type"); $this->assertEquals( - ["class" => "stdClass"], + ClassMetadata::GENERATOR_TYPE_CUSTOM, + $class->generatorType, + 'Generator Type' + ); + $this->assertEquals( + ['class' => 'stdClass'], $class->customGeneratorDefinition, - "Custom Generator Definition"); + 'Custom Generator Definition' + ); } - /** * @depends testEntityTableNameAndInheritance - * @param ClassMetadata $class */ - public function testFieldMappings($class) + public function testFieldMappings(ClassMetadata $class) { $this->assertEquals(4, count($class->fieldMappings)); $this->assertTrue(isset($class->fieldMappings['id'])); @@ -188,34 +207,31 @@ public function testFieldMappings($class) /** * @depends testFieldMappings - * @param ClassMetadata $class */ - public function testVersionedField($class) + public function testVersionedField(ClassMetadata $class): void { $this->assertTrue($class->isVersioned); - $this->assertEquals("version", $class->versionField); + $this->assertEquals('version', $class->versionField); $this->assertFalse(isset($class->fieldMappings['version']['version'])); } /** * @depends testEntityTableNameAndInheritance - * @param ClassMetadata $class */ - public function testFieldMappingsColumnNames($class) + public function testFieldMappingsColumnNames(ClassMetadata $class) { - $this->assertEquals("id", $class->fieldMappings['id']['columnName']); - $this->assertEquals("name", $class->fieldMappings['name']['columnName']); - $this->assertEquals("user_email", $class->fieldMappings['email']['columnName']); + $this->assertEquals('id', $class->fieldMappings['id']['columnName']); + $this->assertEquals('name', $class->fieldMappings['name']['columnName']); + $this->assertEquals('user_email', $class->fieldMappings['email']['columnName']); return $class; } /** * @depends testEntityTableNameAndInheritance - * @param ClassMetadata $class */ - public function testStringFieldMappings($class) + public function testStringFieldMappings(ClassMetadata $class) { $this->assertEquals('string', $class->fieldMappings['name']['type']); $this->assertEquals(50, $class->fieldMappings['name']['length']); @@ -227,12 +243,8 @@ public function testStringFieldMappings($class) /** * @depends testEntityTableNameAndInheritance - * - * @param ClassMetadata $class - * - * @return ClassMetadata */ - public function testFieldOptions(ClassMetadata $class) + public function testFieldOptions(ClassMetadata $class): ClassMetadata { $expected = ['foo' => 'bar', 'baz' => ['key' => 'val'], 'fixed' => false]; $this->assertEquals($expected, $class->fieldMappings['name']['options']); @@ -242,9 +254,8 @@ public function testFieldOptions(ClassMetadata $class) /** * @depends testEntityTableNameAndInheritance - * @param ClassMetadata $class */ - public function testIdFieldOptions($class) + public function testIdFieldOptions(ClassMetadata $class) { $this->assertEquals(['foo' => 'bar', 'unsigned' => false], $class->fieldMappings['id']['options']); @@ -253,23 +264,20 @@ public function testIdFieldOptions($class) /** * @depends testFieldMappings - * @param ClassMetadata $class */ - public function testIdentifier($class) + public function testIdentifier(ClassMetadata $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"); + $this->assertEquals(ClassMetadata::GENERATOR_TYPE_AUTO, $class->generatorType, 'ID-Generator is not ClassMetadata::GENERATOR_TYPE_AUTO'); return $class; } /** * @group #6129 - * - * @return ClassMetadata */ - public function testBooleanValuesForOptionIsSetCorrectly() + public function testBooleanValuesForOptionIsSetCorrectly(): ClassMetadata { $class = $this->createClassMetadata(User::class); @@ -284,9 +292,8 @@ public function testBooleanValuesForOptionIsSetCorrectly() /** * @depends testIdentifier - * @param ClassMetadata $class */ - public function testAssociations($class) + public function testAssociations(ClassMetadata $class) { $this->assertEquals(3, count($class->associationMappings)); @@ -295,9 +302,8 @@ public function testAssociations($class) /** * @depends testAssociations - * @param ClassMetadata $class */ - public function testOwningOneToOneAssociation($class) + public function testOwningOneToOneAssociation(ClassMetadata $class) { $this->assertTrue(isset($class->associationMappings['address'])); $this->assertTrue($class->associationMappings['address']['isOwningSide']); @@ -314,9 +320,8 @@ public function testOwningOneToOneAssociation($class) /** * @depends testOwningOneToOneAssociation - * @param ClassMetadata $class */ - public function testInverseOneToManyAssociation($class) + public function testInverseOneToManyAssociation(ClassMetadata $class) { $this->assertTrue(isset($class->associationMappings['phonenumbers'])); $this->assertFalse($class->associationMappings['phonenumbers']['isOwningSide']); @@ -335,9 +340,8 @@ public function testInverseOneToManyAssociation($class) /** * @depends testInverseOneToManyAssociation - * @param ClassMetadata $class */ - public function testManyToManyAssociationWithCascadeAll($class) + public function testManyToManyAssociationWithCascadeAll(ClassMetadata $class) { $this->assertTrue(isset($class->associationMappings['groups'])); $this->assertTrue($class->associationMappings['groups']['isOwningSide']); @@ -355,9 +359,8 @@ public function testManyToManyAssociationWithCascadeAll($class) /** * @depends testManyToManyAssociationWithCascadeAll - * @param ClassMetadata $class */ - public function testLifecycleCallbacks($class) + public function testLifecycleCallbacks(ClassMetadata $class) { $this->assertEquals(count($class->lifecycleCallbacks), 2); $this->assertEquals($class->lifecycleCallbacks['prePersist'][0], 'doStuffOnPrePersist'); @@ -368,9 +371,8 @@ public function testLifecycleCallbacks($class) /** * @depends testManyToManyAssociationWithCascadeAll - * @param ClassMetadata $class */ - public function testLifecycleCallbacksSupportMultipleMethodNames($class) + public function testLifecycleCallbacksSupportMultipleMethodNames(ClassMetadata $class) { $this->assertEquals(count($class->lifecycleCallbacks['prePersist']), 2); $this->assertEquals($class->lifecycleCallbacks['prePersist'][1], 'doOtherStuffOnPrePersistToo'); @@ -380,9 +382,8 @@ public function testLifecycleCallbacksSupportMultipleMethodNames($class) /** * @depends testLifecycleCallbacksSupportMultipleMethodNames - * @param ClassMetadata $class */ - public function testJoinColumnUniqueAndNullable($class) + public function testJoinColumnUniqueAndNullable(ClassMetadata $class) { // Non-Nullability of Join Column $this->assertFalse($class->associationMappings['groups']['joinTable']['joinColumns'][0]['nullable']); @@ -393,21 +394,19 @@ public function testJoinColumnUniqueAndNullable($class) /** * @depends testJoinColumnUniqueAndNullable - * @param ClassMetadata $class */ - public function testColumnDefinition($class) + public function testColumnDefinition(ClassMetadata $class) { - $this->assertEquals("CHAR(32) NOT NULL", $class->fieldMappings['email']['columnDefinition']); - $this->assertEquals("INT NULL", $class->associationMappings['groups']['joinTable']['inverseJoinColumns'][0]['columnDefinition']); + $this->assertEquals('CHAR(32) NOT NULL', $class->fieldMappings['email']['columnDefinition']); + $this->assertEquals('INT NULL', $class->associationMappings['groups']['joinTable']['inverseJoinColumns'][0]['columnDefinition']); return $class; } /** * @depends testColumnDefinition - * @param ClassMetadata $class */ - public function testJoinColumnOnDelete($class) + public function testJoinColumnOnDelete(ClassMetadata $class) { $this->assertEquals('CASCADE', $class->associationMappings['address']['joinColumns'][0]['onDelete']); @@ -417,9 +416,9 @@ public function testJoinColumnOnDelete($class) /** * @group DDC-514 */ - public function testDiscriminatorColumnDefaults() + public function testDiscriminatorColumnDefaults(): void { - if (strpos(get_class($this), 'PHPMappingDriver') !== false) { + if (strpos(static::class, 'PHPMappingDriver') !== false) { $this->markTestSkipped('PHP Mapping Drivers have no defaults.'); } @@ -434,11 +433,10 @@ public function testDiscriminatorColumnDefaults() /** * @group DDC-869 */ - public function testMappedSuperclassWithRepository() + public function testMappedSuperclassWithRepository(): void { - $em = $this->_getTestEntityManager(); - $factory = $this->createClassMetadataFactory($em); - + $em = $this->_getTestEntityManager(); + $factory = $this->createClassMetadataFactory($em); $class = $factory->getMetadataFor(DDC869CreditCardPayment::class); @@ -449,8 +447,6 @@ public function testMappedSuperclassWithRepository() $this->assertInstanceOf(DDC869PaymentRepository::class, $em->getRepository(DDC869CreditCardPayment::class)); $this->assertTrue($em->getRepository(DDC869ChequePayment::class)->isTrue()); - - $class = $factory->getMetadataFor(DDC869ChequePayment::class); $this->assertTrue(isset($class->fieldMappings['id'])); @@ -464,32 +460,26 @@ public function testMappedSuperclassWithRepository() /** * @group DDC-1476 */ - public function testDefaultFieldType() + public function testDefaultFieldType(): void { - $factory = $this->createClassMetadataFactory(); - $class = $factory->getMetadataFor(DDC1476EntityWithDefaultFieldType::class); - + $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']); - - $this->assertArrayHasKey('fieldName', $class->fieldMappings['id']); $this->assertArrayHasKey('fieldName', $class->fieldMappings['name']); $this->assertEquals('id', $class->fieldMappings['id']['fieldName']); $this->assertEquals('name', $class->fieldMappings['name']['fieldName']); - - $this->assertArrayHasKey('columnName', $class->fieldMappings['id']); $this->assertArrayHasKey('columnName', $class->fieldMappings['name']); @@ -502,29 +492,27 @@ public function testDefaultFieldType() /** * @group DDC-1170 */ - public function testIdentifierColumnDefinition() + public function testIdentifierColumnDefinition(): void { $class = $this->createClassMetadata(DDC1170Entity::class); - $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']); + $this->assertEquals('INT unsigned NOT NULL', $class->fieldMappings['id']['columnDefinition']); + $this->assertEquals('VARCHAR(255) NOT NULL', $class->fieldMappings['value']['columnDefinition']); } /** * @group DDC-559 */ - public function testNamingStrategy() + public function testNamingStrategy(): void { - $em = $this->_getTestEntityManager(); - $factory = $this->createClassMetadataFactory($em); - + $em = $this->_getTestEntityManager(); + $factory = $this->createClassMetadataFactory($em); $this->assertInstanceOf(DefaultNamingStrategy::class, $em->getConfiguration()->getNamingStrategy()); $em->getConfiguration()->setNamingStrategy(new UnderscoreNamingStrategy(CASE_UPPER)); @@ -541,7 +529,7 @@ public function testNamingStrategy() * @group DDC-807 * @group DDC-553 */ - public function testDiscriminatorColumnDefinition() + public function testDiscriminatorColumnDefinition(): void { $class = $this->createClassMetadata(DDC807Entity::class); @@ -549,13 +537,13 @@ public function testDiscriminatorColumnDefinition() $this->assertArrayHasKey('name', $class->discriminatorColumn); $this->assertEquals("ENUM('ONE','TWO')", $class->discriminatorColumn['columnDefinition']); - $this->assertEquals("dtype", $class->discriminatorColumn['name']); + $this->assertEquals('dtype', $class->discriminatorColumn['name']); } /** * @group DDC-889 */ - public function testInvalidEntityOrMappedSuperClassShouldMentionParentClasses() + public function testInvalidEntityOrMappedSuperClassShouldMentionParentClasses(): void { $this->expectException(MappingException::class); $this->expectExceptionMessage('Class "Doctrine\Tests\Models\DDC889\DDC889Class" sub class of "Doctrine\Tests\Models\DDC889\DDC889SuperClass" is not a valid entity or mapped super class.'); @@ -566,7 +554,7 @@ public function testInvalidEntityOrMappedSuperClassShouldMentionParentClasses() /** * @group DDC-889 */ - public function testIdentifierRequiredShouldMentionParentClasses() + public function testIdentifierRequiredShouldMentionParentClasses(): void { $factory = $this->createClassMetadataFactory(); @@ -576,20 +564,19 @@ public function testIdentifierRequiredShouldMentionParentClasses() $factory->getMetadataFor(DDC889Entity::class); } - public function testNamedQuery() + public function testNamedQuery(): void { $driver = $this->_loadDriver(); - $class = $this->createClassMetadata(User::class); + $class = $this->createClassMetadata(User::class); - $this->assertCount(1, $class->getNamedQueries(), sprintf("Named queries not processed correctly by driver %s", get_class($driver))); + $this->assertCount(1, $class->getNamedQueries(), sprintf('Named queries not processed correctly by driver %s', get_class($driver))); } /** * @group DDC-1663 */ - public function testNamedNativeQuery() + public function testNamedNativeQuery(): void { - $class = $this->createClassMetadata(CmsAddress::class); //named native query @@ -597,7 +584,6 @@ public function testNamedNativeQuery() $this->assertArrayHasKey('find-all', $class->namedNativeQueries); $this->assertArrayHasKey('find-by-id', $class->namedNativeQueries); - $findAllQuery = $class->getNamedNativeQuery('find-all'); $this->assertEquals('find-all', $findAllQuery['name']); $this->assertEquals('mapping-find-all', $findAllQuery['resultSetMapping']); @@ -605,13 +591,13 @@ public function testNamedNativeQuery() $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']); + $this->assertEquals(CmsAddress::class, $findByIdQuery['resultClass']); + $this->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']); + $this->assertEquals('SELECT COUNT(*) AS count FROM cms_addresses', $countQuery['query']); // result set mapping $this->assertCount(3, $class->sqlResultSetMappings); @@ -622,9 +608,9 @@ public function testNamedNativeQuery() $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]); + $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]); $withoutFieldsMapping = $class->getSqlResultSetMapping('mapping-without-fields'); $this->assertEquals('mapping-without-fields', $withoutFieldsMapping['name']); @@ -633,16 +619,14 @@ public function testNamedNativeQuery() $countMapping = $class->getSqlResultSetMapping('mapping-count'); $this->assertEquals('mapping-count', $countMapping['name']); - $this->assertEquals(['name'=>'count'], $countMapping['columns'][0]); - + $this->assertEquals(['name' => 'count'], $countMapping['columns'][0]); } /** * @group DDC-1663 */ - public function testSqlResultSetMapping() + public function testSqlResultSetMapping(): void { - $userMetadata = $this->createClassMetadata(CmsUser::class); $personMetadata = $this->createClassMetadata(CompanyPerson::class); @@ -650,74 +634,71 @@ public function testSqlResultSetMapping() $this->assertCount(4, $userMetadata->getSqlResultSetMappings()); $mapping = $userMetadata->getSqlResultSetMapping('mappingJoinedAddress'); - $this->assertEquals([],$mapping['columns']); + $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']); - + $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']); $mapping = $userMetadata->getSqlResultSetMapping('mappingJoinedPhonenumber'); - $this->assertEquals([],$mapping['columns']); + $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']); + $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']); $mapping = $userMetadata->getSqlResultSetMapping('mappingUserPhonenumberCount'); - $this->assertEquals(['name'=>'numphones'],$mapping['columns'][0]); + $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']); + $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']); $mapping = $userMetadata->getSqlResultSetMapping('mappingMultipleJoinsEntityResults'); - $this->assertEquals(['name'=>'numphones'],$mapping['columns'][0]); + $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->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']); + $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']); //person asserts $this->assertCount(1, $personMetadata->getSqlResultSetMappings()); $mapping = $personMetadata->getSqlResultSetMapping('mappingFetchAll'); - $this->assertEquals([],$mapping['columns']); + $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']); + $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']); } /* * @group DDC-964 */ - public function testAssociationOverridesMapping() + public function testAssociationOverridesMapping(): void { - - $factory = $this->createClassMetadataFactory(); - $adminMetadata = $factory->getMetadataFor(DDC964Admin::class); - $guestMetadata = $factory->getMetadataFor(DDC964Guest::class); - + $factory = $this->createClassMetadataFactory(); + $adminMetadata = $factory->getMetadataFor(DDC964Admin::class); + $guestMetadata = $factory->getMetadataFor(DDC964Guest::class); // assert groups association mappings $this->assertArrayHasKey('groups', $guestMetadata->associationMappings); @@ -744,19 +725,17 @@ public function testAssociationOverridesMapping() $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(['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']); - + $this->assertEquals(['adminuser_id' => 'id'], $adminGroups['relationToSourceKeyColumns']); + $this->assertEquals(['admingroup_id' => 'id'], $adminGroups['relationToTargetKeyColumns']); + $this->assertEquals(['adminuser_id', 'admingroup_id'], $adminGroups['joinTableColumns']); // assert address association mappings $this->assertArrayHasKey('address', $guestMetadata->associationMappings); @@ -780,25 +759,23 @@ public function testAssociationOverridesMapping() // 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']); - + $this->assertEquals(['address_id' => 'id'], $guestAddress['sourceToTargetKeyColumns']); + $this->assertEquals(['address_id' => 'address_id'], $guestAddress['joinColumnFieldNames']); + $this->assertEquals(['id' => 'address_id'], $guestAddress['targetToSourceKeyColumns']); $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']); + $this->assertEquals(['adminaddress_id' => 'id'], $adminAddress['sourceToTargetKeyColumns']); + $this->assertEquals(['adminaddress_id' => 'adminaddress_id'], $adminAddress['joinColumnFieldNames']); + $this->assertEquals(['id' => 'adminaddress_id'], $adminAddress['targetToSourceKeyColumns']); } /* * @group DDC-3579 */ - public function testInversedByOverrideMapping() + public function testInversedByOverrideMapping(): void { - - $factory = $this->createClassMetadataFactory(); - $adminMetadata = $factory->getMetadataFor(DDC3579Admin::class); + $factory = $this->createClassMetadataFactory(); + $adminMetadata = $factory->getMetadataFor(DDC3579Admin::class); // assert groups association mappings $this->assertArrayHasKey('groups', $adminMetadata->associationMappings); @@ -811,7 +788,7 @@ public function testInversedByOverrideMapping() /** * @group DDC-5934 */ - public function testFetchOverrideMapping() + public function testFetchOverrideMapping(): void { // check override metadata $contractMetadata = $this->createClassMetadataFactory()->getMetadataFor(DDC5934Contract::class); @@ -823,9 +800,8 @@ public function testFetchOverrideMapping() /** * @group DDC-964 */ - public function testAttributeOverridesMapping() + public function testAttributeOverridesMapping(): void { - $factory = $this->createClassMetadataFactory(); $guestMetadata = $factory->getMetadataFor(DDC964Guest::class); $adminMetadata = $factory->getMetadataFor(DDC964Admin::class); @@ -833,23 +809,21 @@ public function testAttributeOverridesMapping() $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(['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(['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']); @@ -862,7 +836,7 @@ public function testAttributeOverridesMapping() /** * @group DDC-1955 */ - public function testEntityListeners() + public function testEntityListeners(): void { $em = $this->_getTestEntityManager(); $factory = $this->createClassMetadataFactory($em); @@ -893,7 +867,7 @@ public function testEntityListeners() /** * @group DDC-1955 */ - public function testEntityListenersOverride() + public function testEntityListenersOverride(): void { $em = $this->_getTestEntityManager(); $factory = $this->createClassMetadataFactory($em); @@ -923,15 +897,14 @@ public function testEntityListenersOverride() $this->assertEquals('prePersistHandler2', $prePersist['method']); } - /** * @group DDC-1955 */ - public function testEntityListenersNamingConvention() + public function testEntityListenersNamingConvention(): void { - $em = $this->_getTestEntityManager(); - $factory = $this->createClassMetadataFactory($em); - $metadata = $factory->getMetadataFor(CmsAddress::class); + $em = $this->_getTestEntityManager(); + $factory = $this->createClassMetadataFactory($em); + $metadata = $factory->getMetadataFor(CmsAddress::class); $this->assertArrayHasKey(Events::postPersist, $metadata->entityListeners); $this->assertArrayHasKey(Events::prePersist, $metadata->entityListeners); @@ -960,7 +933,6 @@ 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']); @@ -983,7 +955,7 @@ public function testEntityListenersNamingConvention() /** * @group DDC-2183 */ - public function testSecondLevelCacheMapping() + public function testSecondLevelCacheMapping(): void { $em = $this->_getTestEntityManager(); $factory = $this->createClassMetadataFactory($em); @@ -1012,10 +984,10 @@ public function testSecondLevelCacheMapping() * @group DDC-2825 * @group 881 */ - public function testSchemaDefinitionViaExplicitTableSchemaAnnotationProperty() + public function testSchemaDefinitionViaExplicitTableSchemaAnnotationProperty(): void { - /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */ $metadata = $this->createClassMetadataFactory()->getMetadataFor(ExplicitSchemaAndTable::class); + assert($metadata instanceof ClassMetadata); $this->assertSame('explicit_schema', $metadata->getSchemaName()); $this->assertSame('explicit_table', $metadata->getTableName()); @@ -1025,10 +997,10 @@ public function testSchemaDefinitionViaExplicitTableSchemaAnnotationProperty() * @group DDC-2825 * @group 881 */ - public function testSchemaDefinitionViaSchemaDefinedInTableNameInTableAnnotationProperty() + public function testSchemaDefinitionViaSchemaDefinedInTableNameInTableAnnotationProperty(): void { - /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */ $metadata = $this->createClassMetadataFactory()->getMetadataFor(SchemaAndTableInTableName::class); + assert($metadata instanceof ClassMetadata); $this->assertSame('implicit_schema', $metadata->getSchemaName()); $this->assertSame('implicit_table', $metadata->getTableName()); @@ -1038,11 +1010,12 @@ public function testSchemaDefinitionViaSchemaDefinedInTableNameInTableAnnotation * @group DDC-514 * @group DDC-1015 */ - public function testDiscriminatorColumnDefaultLength() + public function testDiscriminatorColumnDefaultLength(): void { - if (strpos(get_class($this), 'PHPMappingDriver') !== false) { + if (strpos(static::class, 'PHPMappingDriver') !== false) { $this->markTestSkipped('PHP Mapping Drivers have no defaults.'); } + $class = $this->createClassMetadata(SingleTableEntityNoDiscriminatorColumnMapping::class); $this->assertEquals(255, $class->discriminatorColumn['length']); $class = $this->createClassMetadata(SingleTableEntityIncompleteDiscriminatorColumnMapping::class); @@ -1053,11 +1026,12 @@ public function testDiscriminatorColumnDefaultLength() * @group DDC-514 * @group DDC-1015 */ - public function testDiscriminatorColumnDefaultType() + public function testDiscriminatorColumnDefaultType(): void { - if (strpos(get_class($this), 'PHPMappingDriver') !== false) { + if (strpos(static::class, 'PHPMappingDriver') !== false) { $this->markTestSkipped('PHP Mapping Drivers have no defaults.'); } + $class = $this->createClassMetadata(SingleTableEntityNoDiscriminatorColumnMapping::class); $this->assertEquals('string', $class->discriminatorColumn['type']); $class = $this->createClassMetadata(SingleTableEntityIncompleteDiscriminatorColumnMapping::class); @@ -1068,11 +1042,12 @@ public function testDiscriminatorColumnDefaultType() * @group DDC-514 * @group DDC-1015 */ - public function testDiscriminatorColumnDefaultName() + public function testDiscriminatorColumnDefaultName(): void { - if (strpos(get_class($this), 'PHPMappingDriver') !== false) { + if (strpos(static::class, 'PHPMappingDriver') !== false) { $this->markTestSkipped('PHP Mapping Drivers have no defaults.'); } + $class = $this->createClassMetadata(SingleTableEntityNoDiscriminatorColumnMapping::class); $this->assertEquals('dtype', $class->discriminatorColumn['name']); $class = $this->createClassMetadata(SingleTableEntityIncompleteDiscriminatorColumnMapping::class); @@ -1101,14 +1076,10 @@ class User **/ public $id; - /** - * @Column(length=50, nullable=true, unique=true, options={"foo": "bar", "baz": {"key": "val"}, "fixed": false}) - */ + /** @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") - */ + /** @Column(name="user_email", columnDefinition="CHAR(32) NOT NULL") */ public $email; /** @@ -1138,35 +1109,34 @@ class User */ public $version; - /** * @PrePersist */ - public function doStuffOnPrePersist() + public function doStuffOnPrePersist(): void { } /** * @PrePersist */ - public function doOtherStuffOnPrePersistToo() { + public function doOtherStuffOnPrePersistToo(): void + { } /** * @PostPersist */ - public function doStuffOnPostPersist() + public function doStuffOnPostPersist(): void { - } - public static function loadMetadata(ClassMetadataInfo $metadata) + public static function loadMetadata(ClassMetadataInfo $metadata): void { $metadata->setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_NONE); $metadata->setPrimaryTable( [ - 'name' => 'cms_users', - 'options' => ['foo' => 'bar', 'baz' => ['key' => 'val']], + 'name' => 'cms_users', + 'options' => ['foo' => 'bar', 'baz' => ['key' => 'val']], ] ); $metadata->setChangeTrackingPolicy(ClassMetadataInfo::CHANGETRACKING_DEFERRED_IMPLICIT); @@ -1175,30 +1145,30 @@ public static function loadMetadata(ClassMetadataInfo $metadata) $metadata->addLifecycleCallback('doStuffOnPostPersist', 'postPersist'); $metadata->mapField( [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - 'columnName' => 'id', - 'options' => ['foo' => 'bar', 'unsigned' => false], + '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], + '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', + 'fieldName' => 'email', + 'type' => 'string', + 'columnName' => 'user_email', + 'columnDefinition' => 'CHAR(32) NOT NULL', ] ); $mapping = ['fieldName' => 'version', 'type' => 'integer']; @@ -1207,86 +1177,81 @@ public static function loadMetadata(ClassMetadataInfo $metadata) $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, + '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', - ], + '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, + '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['uniqueConstraints'] = [ - 'search_idx' => ['columns' => ['name', 'user_email'], 'options'=> ['where' => 'name IS NOT NULL']], + 'search_idx' => ['columns' => ['name', 'user_email'], 'options' => ['where' => 'name IS NOT NULL']], ]; - $metadata->table['indexes'] = [ - 'name_idx' => ['columns' => ['name']], 0 => ['columns' => ['user_email']] + $metadata->table['indexes'] = [ + 'name_idx' => ['columns' => ['name']], + 0 => ['columns' => ['user_email']], ]; $metadata->setSequenceGeneratorDefinition( [ @@ -1298,7 +1263,7 @@ public static function loadMetadata(ClassMetadataInfo $metadata) $metadata->addNamedQuery( [ 'name' => 'all', - 'query' => 'SELECT u FROM __CLASS__ u' + 'query' => 'SELECT u FROM __CLASS__ u', ] ); } @@ -1318,28 +1283,26 @@ abstract class Animal */ public $id; - public static function loadMetadata(ClassMetadataInfo $metadata) + public static function loadMetadata(ClassMetadataInfo $metadata): void { $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_CUSTOM); - $metadata->setCustomGeneratorDefinition(["class" => "stdClass"]); + $metadata->setCustomGeneratorDefinition(['class' => 'stdClass']); } } /** @Entity */ class Cat extends Animal { - public static function loadMetadata(ClassMetadataInfo $metadata) + public static function loadMetadata(ClassMetadataInfo $metadata): void { - } } /** @Entity */ class Dog extends Animal { - public static function loadMetadata(ClassMetadataInfo $metadata) + public static function loadMetadata(ClassMetadataInfo $metadata): void { - } } @@ -1348,11 +1311,7 @@ public static function loadMetadata(ClassMetadataInfo $metadata) */ class DDC1170Entity { - - /** - * @param string $value - */ - function __construct($value = null) + function __construct(?string $value = null) { $this->value = $value; } @@ -1364,47 +1323,38 @@ function __construct($value = null) **/ private $id; - /** - * @Column(columnDefinition = "VARCHAR(255) NOT NULL") - */ + /** @Column(columnDefinition = "VARCHAR(255) NOT NULL") */ private $value; - /** - * @return int - */ - public function getId() + public function getId(): int { return $this->id; } - /** - * @return string - */ - public function getValue() + public function getValue(): string { return $this->value; } - public static function loadMetadata(ClassMetadataInfo $metadata) + public static function loadMetadata(ClassMetadataInfo $metadata): void { $metadata->mapField( [ - 'id' => true, - 'fieldName' => 'id', - 'columnDefinition' => 'INT unsigned NOT NULL', + 'id' => true, + 'fieldName' => 'id', + 'columnDefinition' => 'INT unsigned NOT NULL', ] ); $metadata->mapField( [ - 'fieldName' => 'value', - 'columnDefinition' => 'VARCHAR(255) NOT NULL' + 'fieldName' => 'value', + 'columnDefinition' => 'VARCHAR(255) NOT NULL', ] ); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE); } - } /** @@ -1420,22 +1370,22 @@ class DDC807Entity * @Column(type="integer") * @GeneratedValue(strategy="NONE") **/ - public $id; + public $id; - public static function loadMetadata(ClassMetadataInfo $metadata) + public static function loadMetadata(ClassMetadataInfo $metadata): void { $metadata->mapField( [ - 'id' => true, - 'fieldName' => 'id', + 'id' => true, + 'fieldName' => 'id', ] ); $metadata->setDiscriminatorColumn( [ - 'name' => "dtype", - 'type' => "string", - 'columnDefinition' => "ENUM('ONE','TWO')" + 'name' => 'dtype', + 'type' => 'string', + 'columnDefinition' => "ENUM('ONE','TWO')", ] ); @@ -1443,12 +1393,22 @@ public static function loadMetadata(ClassMetadataInfo $metadata) } } -class DDC807SubClasse1 {} -class DDC807SubClasse2 {} +class DDC807SubClasse1 +{ +} +class DDC807SubClasse2 +{ +} -class Address {} -class Phonenumber {} -class Group {} +class Address +{ +} +class Phonenumber +{ +} +class Group +{ +} /** * @Entity @@ -1456,32 +1416,30 @@ class Group {} */ class Comment { - /** - * @Column(type="text") - */ + /** @Column(type="text") */ private $content; - public static function loadMetadata(ClassMetadataInfo $metadata) + public static function loadMetadata(ClassMetadataInfo $metadata): void { $metadata->setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_NONE); $metadata->setPrimaryTable( [ - 'indexes' => [ - ['columns' => ['content'], 'flags' => ['fulltext'], 'options' => ['where' => 'content IS NOT NULL']] - ] + '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', + 'fieldName' => 'content', + 'type' => 'text', + 'scale' => 0, + 'length' => null, + 'unique' => false, + 'nullable' => false, + 'precision' => 0, + 'columnName' => 'content', ] ); } @@ -1504,12 +1462,12 @@ class SingleTableEntityNoDiscriminatorColumnMapping */ public $id; - public static function loadMetadata(ClassMetadataInfo $metadata) + public static function loadMetadata(ClassMetadataInfo $metadata): void { $metadata->mapField( [ - 'id' => true, - 'fieldName' => 'id', + 'id' => true, + 'fieldName' => 'id', ] ); @@ -1517,8 +1475,12 @@ public static function loadMetadata(ClassMetadataInfo $metadata) } } -class SingleTableEntityNoDiscriminatorColumnMappingSub1 extends SingleTableEntityNoDiscriminatorColumnMapping {} -class SingleTableEntityNoDiscriminatorColumnMappingSub2 extends SingleTableEntityNoDiscriminatorColumnMapping {} +class SingleTableEntityNoDiscriminatorColumnMappingSub1 extends SingleTableEntityNoDiscriminatorColumnMapping +{ +} +class SingleTableEntityNoDiscriminatorColumnMappingSub2 extends SingleTableEntityNoDiscriminatorColumnMapping +{ +} /** * @Entity @@ -1538,12 +1500,12 @@ class SingleTableEntityIncompleteDiscriminatorColumnMapping */ public $id; - public static function loadMetadata(ClassMetadataInfo $metadata) + public static function loadMetadata(ClassMetadataInfo $metadata): void { $metadata->mapField( [ - 'id' => true, - 'fieldName' => 'id', + 'id' => true, + 'fieldName' => 'id', ] ); @@ -1551,7 +1513,9 @@ public static function loadMetadata(ClassMetadataInfo $metadata) } } -class SingleTableEntityIncompleteDiscriminatorColumnMappingSub1 - extends SingleTableEntityIncompleteDiscriminatorColumnMapping {} -class SingleTableEntityIncompleteDiscriminatorColumnMappingSub2 - extends SingleTableEntityIncompleteDiscriminatorColumnMapping {} +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 e4be969de85..cca9454687e 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/AnnotationDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/AnnotationDriverTest.php @@ -24,7 +24,7 @@ class AnnotationDriverTest extends AbstractMappingDriverTest /** * @group DDC-268 */ - public function testLoadMetadataForNonEntityThrowsException() + public function testLoadMetadataForNonEntityThrowsException(): void { $cm = new ClassMetadata('stdClass'); $cm->initializeReflection(new RuntimeReflectionService()); @@ -35,7 +35,7 @@ public function testLoadMetadataForNonEntityThrowsException() $annotationDriver->loadMetadataForClass('stdClass', $cm); } - public function testFailingSecondLevelCacheAssociation() + public function testFailingSecondLevelCacheAssociation(): void { $this->expectException('Doctrine\ORM\Cache\CacheException'); $this->expectExceptionMessage('Entity association field "Doctrine\Tests\ORM\Mapping\AnnotationSLC#foo" not configured as part of the second-level cache.'); @@ -48,7 +48,7 @@ public function testFailingSecondLevelCacheAssociation() /** * @group DDC-268 */ - public function testColumnWithMissingTypeDefaultsToString() + public function testColumnWithMissingTypeDefaultsToString(): void { $cm = new ClassMetadata(ColumnWithoutType::class); $cm->initializeReflection(new RuntimeReflectionService()); @@ -61,7 +61,7 @@ public function testColumnWithMissingTypeDefaultsToString() /** * @group DDC-318 */ - public function testGetAllClassNamesIsIdempotent() + public function testGetAllClassNamesIsIdempotent(): void { $annotationDriver = $this->_loadDriverForCMSModels(); $original = $annotationDriver->getAllClassNames(); @@ -75,7 +75,7 @@ public function testGetAllClassNamesIsIdempotent() /** * @group DDC-318 */ - public function testGetAllClassNamesIsIdempotentEvenWithDifferentDriverInstances() + public function testGetAllClassNamesIsIdempotentEvenWithDifferentDriverInstances(): void { $annotationDriver = $this->_loadDriverForCMSModels(); $original = $annotationDriver->getAllClassNames(); @@ -89,7 +89,7 @@ public function testGetAllClassNamesIsIdempotentEvenWithDifferentDriverInstances /** * @group DDC-318 */ - public function testGetAllClassNamesReturnsAlreadyLoadedClassesIfAppropriate() + public function testGetAllClassNamesReturnsAlreadyLoadedClassesIfAppropriate(): void { $this->_ensureIsLoaded(CmsUser::class); @@ -102,7 +102,7 @@ public function testGetAllClassNamesReturnsAlreadyLoadedClassesIfAppropriate() /** * @group DDC-318 */ - public function testGetClassNamesReturnsOnlyTheAppropriateClasses() + public function testGetClassNamesReturnsOnlyTheAppropriateClasses(): void { $this->_ensureIsLoaded(ECommerceCart::class); @@ -125,7 +125,7 @@ protected function _loadDriver() return $this->createAnnotationDriver(); } - protected function _ensureIsLoaded($entityClassName) + protected function _ensureIsLoaded($entityClassName): void { new $entityClassName(); } @@ -135,7 +135,7 @@ protected function _ensureIsLoaded($entityClassName) * * Entities for this test are in AbstractMappingDriverTest */ - public function testJoinTablesWithMappedSuperclassForAnnotationDriver() + public function testJoinTablesWithMappedSuperclassForAnnotationDriver(): void { $annotationDriver = $this->_loadDriver(); $annotationDriver->addPaths([__DIR__ . '/../../Models/DirectoryTree/']); @@ -155,7 +155,7 @@ public function testJoinTablesWithMappedSuperclassForAnnotationDriver() /** * @group DDC-945 */ - public function testInvalidMappedSuperClassWithManyToManyAssociation() + public function testInvalidMappedSuperClassWithManyToManyAssociation(): void { $annotationDriver = $this->_loadDriver(); @@ -176,7 +176,7 @@ public function testInvalidMappedSuperClassWithManyToManyAssociation() /** * @group DDC-1050 */ - public function testInvalidMappedSuperClassWithInheritanceInformation() + public function testInvalidMappedSuperClassWithInheritanceInformation(): void { $annotationDriver = $this->_loadDriver(); @@ -197,7 +197,7 @@ public function testInvalidMappedSuperClassWithInheritanceInformation() /** * @group DDC-1034 */ - public function testInheritanceSkipsParentLifecycleCallbacks() + public function testInheritanceSkipsParentLifecycleCallbacks(): void { $annotationDriver = $this->_loadDriver(); @@ -216,7 +216,7 @@ public function testInheritanceSkipsParentLifecycleCallbacks() /** * @group DDC-1156 */ - public function testMappedSuperclassInMiddleOfInheritanceHierarchy() + public function testMappedSuperclassInMiddleOfInheritanceHierarchy(): void { $annotationDriver = $this->_loadDriver(); @@ -229,7 +229,7 @@ public function testMappedSuperclassInMiddleOfInheritanceHierarchy() self::assertInstanceOf(ClassMetadata::class, $factory->getMetadataFor(ChildEntity::class)); } - public function testInvalidFetchOptionThrowsException() + public function testInvalidFetchOptionThrowsException(): void { $annotationDriver = $this->_loadDriver(); @@ -244,7 +244,7 @@ public function testInvalidFetchOptionThrowsException() $factory->getMetadataFor(InvalidFetchOption::class); } - public function testAttributeOverridesMappingWithTrait() + public function testAttributeOverridesMappingWithTrait(): void { $factory = $this->createClassMetadataFactory(); @@ -308,14 +308,14 @@ class AnnotationParent /** * @PostLoad */ - public function postLoad() + public function postLoad(): void { } /** * @PreUpdate */ - public function preUpdate() + public function preUpdate(): void { } } diff --git a/tests/Doctrine/Tests/ORM/Mapping/AnsiQuoteStrategyTest.php b/tests/Doctrine/Tests/ORM/Mapping/AnsiQuoteStrategyTest.php index 344ba6985ab..c1e0a1ef61e 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/AnsiQuoteStrategyTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/AnsiQuoteStrategyTest.php @@ -1,9 +1,13 @@ strategy = new AnsiQuoteStrategy(); } - /** - * @param string $className - * @return \Doctrine\ORM\Mapping\ClassMetadata - */ - private function createClassMetadata($className) + private function createClassMetadata(string $className): ClassMetadata { $class = new ClassMetadata($className); $class->initializeReflection(new RuntimeReflectionService()); @@ -49,117 +44,109 @@ private function createClassMetadata($className) return $class; } - public function testGetColumnName() + public function testGetColumnName(): void { $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)); + $this->assertEquals('id', $this->strategy->getColumnName('id', $class, $this->platform)); + $this->assertEquals('name', $this->strategy->getColumnName('name', $class, $this->platform)); } - public function testGetTableName() + public function testGetTableName(): void { $class = $this->createClassMetadata(CmsUser::class); - $class->setPrimaryTable(['name'=>'cms_user']); - $this->assertEquals('cms_user' ,$this->strategy->getTableName($class, $this->platform)); + $class->setPrimaryTable(['name' => 'cms_user']); + $this->assertEquals('cms_user', $this->strategy->getTableName($class, $this->platform)); } - public function testJoinTableName() + public function testJoinTableName(): void { $class = $this->createClassMetadata(CmsAddress::class); $class->mapManyToMany( [ - 'fieldName' => 'user', - 'targetEntity' => 'CmsUser', - 'inversedBy' => 'users', - 'joinTable' => [ - 'name' => 'cmsaddress_cmsuser' - ] + '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() + public function testIdentifierColumnNames(): void { $class = $this->createClassMetadata(CmsAddress::class); $class->mapField( [ - 'id' => true, - 'fieldName' => 'id', - 'columnName' => 'id', + 'id' => true, + 'fieldName' => 'id', + 'columnName' => 'id', ] ); $this->assertEquals(['id'], $this->strategy->getIdentifierColumnNames($class, $this->platform)); } - - public function testColumnAlias() + public function testColumnAlias(): void { $this->assertEquals('columnName_1', $this->strategy->getColumnAlias('columnName', 1, $this->platform)); } - public function testJoinColumnName() + public function testJoinColumnName(): void { $class = $this->createClassMetadata(DDC117ArticleDetails::class); $class->mapOneToOne( [ - 'id' => true, - 'fieldName' => 'article', - 'targetEntity' => DDC117Article::class, - 'joinColumns' => [ - [ - 'name' => 'article' - ] - ], + '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)); + $this->assertEquals('article', $this->strategy->getJoinColumnName($joinColumn, $class, $this->platform)); } - public function testReferencedJoinColumnName() + public function testReferencedJoinColumnName(): void { $cm = $this->createClassMetadata(DDC117ArticleDetails::class); $cm->mapOneToOne( [ - 'id' => true, - 'fieldName' => 'article', - 'targetEntity' => DDC117Article::class, - 'joinColumns' => [ - [ - 'name' => 'article' - ] - ], + '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)); + $this->assertEquals('id', $this->strategy->getReferencedJoinColumnName($joinColumn, $cm, $this->platform)); } - public function testGetSequenceName() + public function testGetSequenceName(): void { $class = $this->createClassMetadata(CmsUser::class); $definition = [ 'sequenceName' => 'user_id_seq', 'allocationSize' => 1, - 'initialValue' => 2 + 'initialValue' => 2, ]; $class->setSequenceGeneratorDefinition($definition); - $this->assertEquals('user_id_seq',$this->strategy->getSequenceName($definition, $class, $this->platform)); + $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 ae5e21aae99..ec67766a224 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/BasicInheritanceMappingTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/BasicInheritanceMappingTest.php @@ -1,11 +1,12 @@ cmf = new ClassMetadataFactory(); $this->cmf->setEntityManager($this->_getTestEntityManager()); } - public function testGetMetadataForTransientClassThrowsException() + public function testGetMetadataForTransientClassThrowsException(): void { - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); + $this->expectException(MappingException::class); $this->cmf->getMetadataFor(TransientBaseClass::class); } - public function testGetMetadataForSubclassWithTransientBaseClass() + public function testGetMetadataForSubclassWithTransientBaseClass(): void { $class = $this->cmf->getMetadataFor(EntitySubClass::class); @@ -48,7 +48,7 @@ public function testGetMetadataForSubclassWithTransientBaseClass() $this->assertArrayHasKey('name', $class->fieldMappings); } - public function testGetMetadataForSubclassWithMappedSuperclass() + public function testGetMetadataForSubclassWithMappedSuperclass(): void { $class = $this->cmf->getMetadataFor(EntitySubClass2::class); @@ -70,7 +70,7 @@ public function testGetMetadataForSubclassWithMappedSuperclass() /** * @group DDC-869 */ - public function testGetMetadataForSubclassWithMappedSuperclassWithRepository() + public function testGetMetadataForSubclassWithMappedSuperclassWithRepository(): void { $class = $this->cmf->getMetadataFor(DDC869CreditCardPayment::class); @@ -79,7 +79,6 @@ public function testGetMetadataForSubclassWithMappedSuperclassWithRepository() $this->assertArrayHasKey('creditCardNumber', $class->fieldMappings); $this->assertEquals($class->customRepositoryClassName, DDC869PaymentRepository::class); - $class = $this->cmf->getMetadataFor(DDC869ChequePayment::class); $this->assertArrayHasKey('id', $class->fieldMappings); @@ -87,7 +86,6 @@ public function testGetMetadataForSubclassWithMappedSuperclassWithRepository() $this->assertArrayHasKey('serialNumber', $class->fieldMappings); $this->assertEquals($class->customRepositoryClassName, DDC869PaymentRepository::class); - // override repositoryClass $class = $this->cmf->getMetadataFor(SubclassWithRepository::class); @@ -99,13 +97,12 @@ public function testGetMetadataForSubclassWithMappedSuperclassWithRepository() /** * @group DDC-388 */ - public function testSerializationWithPrivateFieldsFromMappedSuperclass() + public function testSerializationWithPrivateFieldsFromMappedSuperclass(): void { - $class = $this->cmf->getMetadataFor(EntitySubClass2::class); $class2 = unserialize(serialize($class)); - $class2->wakeupReflection(new RuntimeReflectionService); + $class2->wakeupReflection(new RuntimeReflectionService()); $this->assertArrayHasKey('mapped1', $class2->reflFields); $this->assertArrayHasKey('mapped2', $class2->reflFields); @@ -115,7 +112,7 @@ public function testSerializationWithPrivateFieldsFromMappedSuperclass() /** * @group DDC-1203 */ - public function testUnmappedSuperclassInHierarchy() + public function testUnmappedSuperclassInHierarchy(): void { $class = $this->cmf->getMetadataFor(HierarchyD::class); @@ -127,11 +124,11 @@ public function testUnmappedSuperclassInHierarchy() /** * @group DDC-1204 */ - public function testUnmappedEntityInHierarchy() + public function testUnmappedEntityInHierarchy(): void { $this->expectException(MappingException::class); $this->expectExceptionMessage( - 'Entity \'Doctrine\Tests\ORM\Mapping\HierarchyBEntity\' has to be part of the discriminator map' + 'Entity \'Doctrine\Tests\ORM\Mapping\HierarchyBEntity\' has to be part of the discriminator map' . ' of \'Doctrine\Tests\ORM\Mapping\HierarchyBase\' to be properly mapped in the inheritance hierarchy.' . ' Alternatively you can make \'Doctrine\Tests\ORM\Mapping\HierarchyBEntity\' an abstract class to' . ' avoid this exception from occurring.' @@ -144,7 +141,7 @@ public function testUnmappedEntityInHierarchy() * @group DDC-1204 * @group DDC-1203 */ - public function testMappedSuperclassWithId() + public function testMappedSuperclassWithId(): void { $class = $this->cmf->getMetadataFor(SuperclassEntity::class); @@ -155,10 +152,10 @@ public function testMappedSuperclassWithId() * @group DDC-1156 * @group DDC-1218 */ - public function testGeneratedValueFromMappedSuperclass() + public function testGeneratedValueFromMappedSuperclass(): void { $class = $this->cmf->getMetadataFor(SuperclassEntity::class); - /* @var $class ClassMetadataInfo */ + assert($class instanceof ClassMetadataInfo); $this->assertInstanceOf(SequenceGenerator::class, $class->idGenerator); $this->assertEquals( @@ -171,10 +168,10 @@ public function testGeneratedValueFromMappedSuperclass() * @group DDC-1156 * @group DDC-1218 */ - public function testSequenceDefinitionInHierarchyWithSandwichMappedSuperclass() + public function testSequenceDefinitionInHierarchyWithSandwichMappedSuperclass(): void { $class = $this->cmf->getMetadataFor(HierarchyD::class); - /* @var $class ClassMetadataInfo */ + assert($class instanceof ClassMetadataInfo); $this->assertInstanceOf(SequenceGenerator::class, $class->idGenerator); $this->assertEquals( @@ -187,10 +184,10 @@ public function testSequenceDefinitionInHierarchyWithSandwichMappedSuperclass() * @group DDC-1156 * @group DDC-1218 */ - public function testMultipleMappedSuperclasses() + public function testMultipleMappedSuperclasses(): void { $class = $this->cmf->getMetadataFor(MediumSuperclassEntity::class); - /* @var $class ClassMetadataInfo */ + assert($class instanceof ClassMetadataInfo); $this->assertInstanceOf(SequenceGenerator::class, $class->idGenerator); $this->assertEquals( @@ -204,10 +201,10 @@ public function testMultipleMappedSuperclasses() * * @group DDC-3418 */ - public function testMappedSuperclassIndex() + public function testMappedSuperclassIndex(): void { $class = $this->cmf->getMetadataFor(EntityIndexSubClass::class); - /* @var $class ClassMetadataInfo */ + assert($class instanceof ClassMetadataInfo); $this->assertArrayHasKey('mapped1', $class->fieldMappings); $this->assertArrayHasKey('IDX_NAME_INDEX', $class->table['uniqueConstraints']); @@ -216,7 +213,8 @@ public function testMappedSuperclassIndex() } } -class TransientBaseClass { +class TransientBaseClass +{ private $transient1; private $transient2; } @@ -231,7 +229,8 @@ class EntitySubClass extends TransientBaseClass } /** @MappedSuperclass */ -class MappedSuperclassBase { +class MappedSuperclassBase +{ /** @Column(type="integer") */ private $mapped1; /** @Column(type="string") */ @@ -243,10 +242,13 @@ class MappedSuperclassBase { private $mappedRelated1; private $transient; } -class MappedSuperclassRelated1 {} +class MappedSuperclassRelated1 +{ +} /** @Entity */ -class EntitySubClass2 extends MappedSuperclassBase { +class EntitySubClass2 extends MappedSuperclassBase +{ /** @Id @Column(type="integer") */ private $id; /** @Column(type="string") */ @@ -260,7 +262,8 @@ class EntitySubClass2 extends MappedSuperclassBase { * indexes={@Index(name="IDX_MAPPED2_INDEX", columns={"mapped2"})} * ) */ -class MappedSuperclassBaseIndex { +class MappedSuperclassBaseIndex +{ /** @Column(type="string") */ private $mapped1; /** @Column(type="string") */ diff --git a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataBuilderTest.php b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataBuilderTest.php index ce42a4ef45f..c2e690cc65f 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataBuilderTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataBuilderTest.php @@ -1,11 +1,14 @@ cm = new ClassMetadata(CmsUser::class); $this->cm->initializeReflection(new RuntimeReflectionService()); $this->builder = new ClassMetadataBuilder($this->cm); } - public function testSetMappedSuperClass() + public function testSetMappedSuperClass(): void { $this->assertIsFluent($this->builder->setMappedSuperClass()); $this->assertTrue($this->cm->isMappedSuperclass); $this->assertFalse($this->cm->isEmbeddedClass); } - public function testSetEmbedable() + public function testSetEmbedable(): void { $this->assertIsFluent($this->builder->setEmbeddable()); $this->assertTrue($this->cm->isEmbeddedClass); $this->assertFalse($this->cm->isMappedSuperclass); } - public function testAddEmbeddedWithOnlyRequiredParams() + public function testAddEmbeddedWithOnlyRequiredParams(): void { $this->assertIsFluent($this->builder->addEmbedded('name', Name::class)); $this->assertEquals( [ - 'name' => [ - 'class' => Name::class, - 'columnPrefix' => null, - 'declaredField' => null, - 'originalField' => null, - ] - ], $this->cm->embeddedClasses); + 'name' => [ + 'class' => Name::class, + 'columnPrefix' => null, + 'declaredField' => null, + 'originalField' => null, + ], + ], + $this->cm->embeddedClasses + ); } - public function testAddEmbeddedWithPrefix() + public function testAddEmbeddedWithPrefix(): void { $this->assertIsFluent( $this->builder->addEmbedded( @@ -74,18 +75,20 @@ public function testAddEmbeddedWithPrefix() $this->assertEquals( [ - 'name' => [ - 'class' => Name::class, - 'columnPrefix' => 'nm_', - 'declaredField' => null, - 'originalField' => null, - ] - ], $this->cm->embeddedClasses); + 'name' => [ + 'class' => Name::class, + 'columnPrefix' => 'nm_', + 'declaredField' => null, + 'originalField' => null, + ], + ], + $this->cm->embeddedClasses + ); } - public function testCreateEmbeddedWithoutExtraParams() + public function testCreateEmbeddedWithoutExtraParams(): void { - $embeddedBuilder = ($this->builder->createEmbedded('name', Name::class)); + $embeddedBuilder = $this->builder->createEmbedded('name', Name::class); $this->assertInstanceOf(EmbeddedBuilder::class, $embeddedBuilder); $this->assertFalse(isset($this->cm->embeddedClasses['name'])); @@ -96,15 +99,15 @@ public function testCreateEmbeddedWithoutExtraParams() 'class' => Name::class, 'columnPrefix' => null, 'declaredField' => null, - 'originalField' => null + 'originalField' => null, ], $this->cm->embeddedClasses['name'] ); } - public function testCreateEmbeddedWithColumnPrefix() + public function testCreateEmbeddedWithColumnPrefix(): void { - $embeddedBuilder = ($this->builder->createEmbedded('name', Name::class)); + $embeddedBuilder = $this->builder->createEmbedded('name', Name::class); $this->assertEquals($embeddedBuilder, $embeddedBuilder->setColumnPrefix('nm_')); @@ -115,43 +118,43 @@ public function testCreateEmbeddedWithColumnPrefix() 'class' => Name::class, 'columnPrefix' => 'nm_', 'declaredField' => null, - 'originalField' => null + 'originalField' => null, ], $this->cm->embeddedClasses['name'] ); } - public function testSetCustomRepositoryClass() + public function testSetCustomRepositoryClass(): void { $this->assertIsFluent($this->builder->setCustomRepositoryClass(CmsGroup::class)); $this->assertEquals(CmsGroup::class, $this->cm->customRepositoryClassName); } - public function testSetReadOnly() + public function testSetReadOnly(): void { $this->assertIsFluent($this->builder->setReadOnly()); $this->assertTrue($this->cm->isReadOnly); } - public function testSetTable() + public function testSetTable(): void { $this->assertIsFluent($this->builder->setTable('users')); $this->assertEquals('users', $this->cm->table['name']); } - public function testAddIndex() + public function testAddIndex(): void { $this->assertIsFluent($this->builder->addIndex(['username', 'name'], 'users_idx')); $this->assertEquals(['users_idx' => ['columns' => ['username', 'name']]], $this->cm->table['indexes']); } - public function testAddUniqueConstraint() + public function testAddUniqueConstraint(): void { $this->assertIsFluent($this->builder->addUniqueConstraint(['username', 'name'], 'users_idx')); $this->assertEquals(['users_idx' => ['columns' => ['username', 'name']]], $this->cm->table['uniqueConstraints']); } - public function testSetPrimaryTableRelated() + public function testSetPrimaryTableRelated(): void { $this->builder->addUniqueConstraint(['username', 'name'], 'users_idx'); $this->builder->addIndex(['username', 'name'], 'users_idx'); @@ -167,55 +170,57 @@ public function testSetPrimaryTableRelated() ); } - public function testSetInheritanceJoined() + public function testSetInheritanceJoined(): void { $this->assertIsFluent($this->builder->setJoinedTableInheritance()); $this->assertEquals(ClassMetadata::INHERITANCE_TYPE_JOINED, $this->cm->inheritanceType); } - public function testSetInheritanceSingleTable() + public function testSetInheritanceSingleTable(): void { $this->assertIsFluent($this->builder->setSingleTableInheritance()); $this->assertEquals(ClassMetadata::INHERITANCE_TYPE_SINGLE_TABLE, $this->cm->inheritanceType); } - public function testSetDiscriminatorColumn() + public function testSetDiscriminatorColumn(): void { $this->assertIsFluent($this->builder->setDiscriminatorColumn('discr', 'string', '124')); $this->assertEquals(['fieldName' => 'discr', 'name' => 'discr', 'type' => 'string', 'length' => '124'], $this->cm->discriminatorColumn); } - public function testAddDiscriminatorMapClass() + public function testAddDiscriminatorMapClass(): void { $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); + ['test' => CmsUser::class, 'test2' => CmsGroup::class], + $this->cm->discriminatorMap + ); $this->assertEquals('test', $this->cm->discriminatorValue); } - public function testChangeTrackingPolicyExplicit() + public function testChangeTrackingPolicyExplicit(): void { $this->assertIsFluent($this->builder->setChangeTrackingPolicyDeferredExplicit()); $this->assertEquals(ClassMetadata::CHANGETRACKING_DEFERRED_EXPLICIT, $this->cm->changeTrackingPolicy); } - public function testChangeTrackingPolicyNotify() + public function testChangeTrackingPolicyNotify(): void { $this->assertIsFluent($this->builder->setChangeTrackingPolicyNotify()); $this->assertEquals(ClassMetadata::CHANGETRACKING_NOTIFY, $this->cm->changeTrackingPolicy); } - public function testAddField() + public function testAddField(): void { $this->assertIsFluent($this->builder->addField('name', 'string')); $this->assertEquals(['columnName' => 'name', 'fieldName' => 'name', 'type' => 'string'], $this->cm->fieldMappings['name']); } - public function testCreateField() + public function testCreateField(): void { - $fieldBuilder = ($this->builder->createField('name', 'string')); + $fieldBuilder = $this->builder->createField('name', 'string'); $this->assertInstanceOf(FieldBuilder::class, $fieldBuilder); $this->assertFalse(isset($this->cm->fieldMappings['name'])); @@ -223,23 +228,25 @@ public function testCreateField() $this->assertEquals(['columnName' => 'name', 'fieldName' => 'name', 'type' => 'string'], $this->cm->fieldMappings['name']); } - public function testCreateVersionedField() + public function testCreateVersionedField(): void { $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']); + 'columnDefinition' => 'foobar', + 'columnName' => 'username', + 'default' => 1, + 'fieldName' => 'name', + 'length' => 124, + 'type' => 'integer', + 'nullable' => true, + 'unique' => true, + ], + $this->cm->fieldMappings['name'] + ); } - public function testCreatePrimaryField() + public function testCreatePrimaryField(): void { $this->builder->createField('id', 'integer')->makePrimaryKey()->generatedValue()->build(); @@ -247,22 +254,24 @@ public function testCreatePrimaryField() $this->assertEquals(['columnName' => 'id', 'fieldName' => 'id', 'id' => true, 'type' => 'integer'], $this->cm->fieldMappings['id']); } - public function testCreateUnsignedOptionField() + public function testCreateUnsignedOptionField(): void { $this->builder->createField('state', 'integer')->option('unsigned', true)->build(); $this->assertEquals( - ['fieldName' => 'state', 'type' => 'integer', 'options' => ['unsigned' => true], 'columnName' => 'state'], $this->cm->fieldMappings['state']); + ['fieldName' => 'state', 'type' => 'integer', 'options' => ['unsigned' => true], 'columnName' => 'state'], + $this->cm->fieldMappings['state'] + ); } - public function testAddLifecycleEvent() + public function testAddLifecycleEvent(): void { $this->builder->addLifecycleEvent('getStatus', 'postLoad'); $this->assertEquals(['postLoad' => ['getStatus']], $this->cm->lifecycleCallbacks); } - public function testCreateManyToOne() + public function testCreateManyToOne(): void { $this->assertIsFluent( $this->builder->createManyToOne('groups', CmsGroup::class) @@ -275,55 +284,51 @@ public function testCreateManyToOne() $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, + '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); + ], + $this->cm->associationMappings + ); } - public function testCreateManyToOneWithIdentity() + public function testCreateManyToOneWithIdentity(): void { $this->assertIsFluent( $this @@ -357,12 +362,12 @@ public function testCreateManyToOneWithIdentity() 'nullable' => true, 'unique' => false, 'onDelete' => 'CASCADE', - 'columnDefinition' => NULL, + 'columnDefinition' => null, ], ], 'type' => 2, - 'mappedBy' => NULL, - 'inversedBy' => NULL, + 'mappedBy' => null, + 'inversedBy' => null, 'isOwningSide' => true, 'sourceEntity' => CmsUser::class, 'isCascadeRemove' => true, @@ -371,26 +376,20 @@ public function testCreateManyToOneWithIdentity() 'isCascadeMerge' => true, 'isCascadeDetach' => true, 'sourceToTargetKeyColumns' => - [ - 'group_id' => 'id', - ], + ['group_id' => 'id'], 'joinColumnFieldNames' => - [ - 'group_id' => 'group_id', - ], + ['group_id' => 'group_id'], 'targetToSourceKeyColumns' => - [ - 'id' => 'group_id', - ], + ['id' => 'group_id'], 'orphanRemoval' => false, - 'id' => true + 'id' => true, ], ], $this->cm->associationMappings ); } - public function testCreateOneToOne() + public function testCreateOneToOne(): void { $this->assertIsFluent( $this->builder->createOneToOne('groups', CmsGroup::class) @@ -403,55 +402,51 @@ public function testCreateOneToOne() $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 + '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); + ], + $this->cm->associationMappings + ); } - public function testCreateOneToOneWithIdentity() + public function testCreateOneToOneWithIdentity(): void { $this->assertIsFluent( $this @@ -486,12 +481,12 @@ public function testCreateOneToOneWithIdentity() 'nullable' => true, 'unique' => false, 'onDelete' => 'CASCADE', - 'columnDefinition' => NULL, + 'columnDefinition' => null, ], ], 'type' => 1, - 'mappedBy' => NULL, - 'inversedBy' => NULL, + 'mappedBy' => null, + 'inversedBy' => null, 'isOwningSide' => true, 'sourceEntity' => CmsUser::class, 'isCascadeRemove' => true, @@ -500,27 +495,21 @@ public function testCreateOneToOneWithIdentity() 'isCascadeMerge' => true, 'isCascadeDetach' => true, 'sourceToTargetKeyColumns' => - [ - 'group_id' => 'id', - ], + ['group_id' => 'id'], 'joinColumnFieldNames' => - [ - 'group_id' => 'group_id', - ], + ['group_id' => 'group_id'], 'targetToSourceKeyColumns' => - [ - 'id' => 'group_id', - ], - 'orphanRemoval' => false + ['id' => 'group_id'], + 'orphanRemoval' => false, ], ], $this->cm->associationMappings ); } - public function testThrowsExceptionOnCreateOneToOneWithIdentityOnInverseSide() + public function testThrowsExceptionOnCreateOneToOneWithIdentityOnInverseSide(): void { - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); + $this->expectException(MappingException::class); $this ->builder @@ -531,7 +520,7 @@ public function testThrowsExceptionOnCreateOneToOneWithIdentityOnInverseSide() ->build(); } - public function testCreateManyToMany() + public function testCreateManyToMany(): void { $this->assertIsFluent( $this->builder->createManyToMany('groups', CmsGroup::class) @@ -545,79 +534,77 @@ public function testCreateManyToMany() $this->assertEquals( [ - 'groups' => - [ - 'fieldName' => 'groups', - 'targetEntity' => CmsGroup::class, - 'cascade' => + 'groups' => [ - 0 => 'remove', - 1 => 'persist', - 2 => 'refresh', - 3 => 'merge', - 4 => 'detach', - ], - 'fetch' => 4, - 'joinTable' => - [ - 'joinColumns' => + 'fieldName' => 'groups', + 'targetEntity' => CmsGroup::class, + 'cascade' => [ - 0 => - [ - 'name' => 'group_id', - 'referencedColumnName' => 'id', - 'nullable' => true, - 'unique' => false, - 'onDelete' => 'CASCADE', - 'columnDefinition' => NULL, - ], + 0 => 'remove', + 1 => 'persist', + 2 => 'refresh', + 3 => 'merge', + 4 => 'detach', ], - 'inverseJoinColumns' => + 'fetch' => 4, + 'joinTable' => [ - 0 => + 'joinColumns' => [ - 'name' => 'user_id', - 'referencedColumnName' => 'id', - 'nullable' => true, - 'unique' => false, - 'onDelete' => NULL, - 'columnDefinition' => NULL, + 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', ], - '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', + '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, ], - 'orphanRemoval' => false, ], - ], $this->cm->associationMappings); + $this->cm->associationMappings + ); } - public function testThrowsExceptionOnCreateManyToManyWithIdentity() + public function testThrowsExceptionOnCreateManyToManyWithIdentity(): void { - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); + $this->expectException(MappingException::class); $this->builder->createManyToMany('groups', CmsGroup::class) ->makePrimaryKey() @@ -629,10 +616,10 @@ public function testThrowsExceptionOnCreateManyToManyWithIdentity() ->build(); } - public function testCreateOneToMany() + public function testCreateOneToMany(): void { $this->assertIsFluent( - $this->builder->createOneToMany('groups', CmsGroup::class) + $this->builder->createOneToMany('groups', CmsGroup::class) ->mappedBy('test') ->setOrderBy(['test']) ->setIndexBy('test') @@ -641,37 +628,36 @@ public function testCreateOneToMany() $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' => + '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, ], - 'isCascadeRemove' => false, - 'isCascadePersist' => false, - 'isCascadeRefresh' => false, - 'isCascadeMerge' => false, - 'isCascadeDetach' => false, - 'orphanRemoval' => false, ], - ], $this->cm->associationMappings); + $this->cm->associationMappings + ); } - public function testThrowsExceptionOnCreateOneToManyWithIdentity() + public function testThrowsExceptionOnCreateOneToManyWithIdentity(): void { - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); + $this->expectException(MappingException::class); $this->builder->createOneToMany('groups', CmsGroup::class) ->makePrimaryKey() @@ -681,7 +667,7 @@ public function testThrowsExceptionOnCreateOneToManyWithIdentity() ->build(); } - public function testOrphanRemovalOnCreateOneToOne() + public function testOrphanRemovalOnCreateOneToOne(): void { $this->assertIsFluent( $this->builder @@ -693,50 +679,46 @@ public function testOrphanRemovalOnCreateOneToOne() $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', + '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, ], - 'orphanRemoval' => true ], - ], $this->cm->associationMappings); + $this->cm->associationMappings + ); } - public function testOrphanRemovalOnCreateOneToMany() + public function testOrphanRemovalOnCreateOneToMany(): void { $this->assertIsFluent( $this->builder @@ -748,30 +730,32 @@ public function testOrphanRemovalOnCreateOneToMany() $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, + '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); + $this->cm->associationMappings + ); } - public function testExceptionOnOrphanRemovalOnManyToOne() + public function testExceptionOnOrphanRemovalOnManyToOne(): void { - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); + $this->expectException(MappingException::class); $this->builder ->createManyToOne('groups', CmsGroup::class) @@ -780,7 +764,7 @@ public function testExceptionOnOrphanRemovalOnManyToOne() ->build(); } - public function testOrphanRemovalOnManyToMany() + public function testOrphanRemovalOnManyToMany(): void { $this->builder ->createManyToMany('groups', CmsGroup::class) @@ -790,59 +774,57 @@ public function testOrphanRemovalOnManyToMany() $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, + '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', ], - 'inverseJoinColumns' => [ - 0 => [ - 'name' => 'cmsgroup_id', - 'referencedColumnName' => 'id', - 'onDelete' => 'CASCADE' - ] + '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', ], - '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, ], - 'relationToTargetKeyColumns' => [ - 'cmsgroup_id' => 'id', - ], - 'orphanRemoval' => true, ], - ], $this->cm->associationMappings); + $this->cm->associationMappings + ); } - public function assertIsFluent($ret) + public function assertIsFluent($ret): void { - $this->assertSame($this->builder, $ret, "Return Value has to be same instance as used builder"); + $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 7174b8370f3..17ad44b70c2 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataFactoryTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataFactoryTest.php @@ -1,5 +1,7 @@ _createEntityManager($mockDriver); - $conn = $entityManager->getConnection(); + $conn = $entityManager->getConnection(); $mockPlatform = $conn->getDatabasePlatform(); $mockPlatform->setPrefersSequences(true); $mockPlatform->setPrefersIdentityColumns(false); @@ -68,12 +77,12 @@ public function testGetMetadataForSingleClass() $this->assertTrue($cmMap1->hasField('name')); } - public function testGetMetadataFor_ReturnsLoadedCustomIdGenerator() + public function testGetMetadataFor_ReturnsLoadedCustomIdGenerator(): void { $cm1 = $this->_createValidClassMetadata(); $cm1->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_CUSTOM); $cm1->customGeneratorDefinition = ['class' => CustomIdGenerator::class]; - $cmf = $this->_createTestFactory(); + $cmf = $this->_createTestFactory(); $cmf->setMetadataForClass($cm1->name, $cm1); $actual = $cmf->getMetadataFor($cm1->name); @@ -82,19 +91,19 @@ public function testGetMetadataFor_ReturnsLoadedCustomIdGenerator() $this->assertInstanceOf(CustomIdGenerator::class, $actual->idGenerator); } - public function testGetMetadataFor_ThrowsExceptionOnUnknownCustomGeneratorClass() + public function testGetMetadataFor_ThrowsExceptionOnUnknownCustomGeneratorClass(): void { $cm1 = $this->_createValidClassMetadata(); $cm1->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_CUSTOM); - $cm1->customGeneratorDefinition = ["class" => "NotExistingGenerator"]; - $cmf = $this->_createTestFactory(); + $cm1->customGeneratorDefinition = ['class' => 'NotExistingGenerator']; + $cmf = $this->_createTestFactory(); $cmf->setMetadataForClass($cm1->name, $cm1); $this->expectException(ORMException::class); $actual = $cmf->getMetadataFor($cm1->name); } - public function testGetMetadataFor_ThrowsExceptionOnMissingCustomGeneratorDefinition() + public function testGetMetadataFor_ThrowsExceptionOnMissingCustomGeneratorDefinition(): void { $cm1 = $this->_createValidClassMetadata(); $cm1->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_CUSTOM); @@ -105,9 +114,9 @@ public function testGetMetadataFor_ThrowsExceptionOnMissingCustomGeneratorDefini $actual = $cmf->getMetadataFor($cm1->name); } - public function testHasGetMetadata_NamespaceSeparatorIsNotNormalized() + public function testHasGetMetadata_NamespaceSeparatorIsNotNormalized(): void { - require_once __DIR__."/../../Models/Global/GlobalNamespaceModel.php"; + require_once __DIR__ . '/../../Models/Global/GlobalNamespaceModel.php'; $metadataDriver = $this->createAnnotationDriver([__DIR__ . '/../../Models/Global/']); @@ -127,9 +136,9 @@ public function testHasGetMetadata_NamespaceSeparatorIsNotNormalized() /** * @group DDC-1512 */ - public function testIsTransient() + public function testIsTransient(): void { - $cmf = new ClassMetadataFactory(); + $cmf = new ClassMetadataFactory(); $driver = $this->createMock(MappingDriver::class); $driver->expects($this->at(0)) ->method('isTransient') @@ -149,9 +158,9 @@ public function testIsTransient() /** * @group DDC-1512 */ - public function testIsTransientEntityNamespace() + public function testIsTransientEntityNamespace(): void { - $cmf = new ClassMetadataFactory(); + $cmf = new ClassMetadataFactory(); $driver = $this->createMock(MappingDriver::class); $driver->expects($this->at(0)) ->method('isTransient') @@ -169,28 +178,28 @@ public function testIsTransientEntityNamespace() $this->assertFalse($em->getMetadataFactory()->isTransient('CMS:CmsArticle')); } - public function testAddDefaultDiscriminatorMap() + public function testAddDefaultDiscriminatorMap(): void { self::markTestSkipped('This test is just incorrect and must be fixed'); - $cmf = new ClassMetadataFactory(); + $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); - $childMetadata = $cmf->getMetadataFor(ChildClass::class); - $anotherChildMetadata = $cmf->getMetadataFor(AnotherChildClass::class); - $rootDiscriminatorMap = $rootMetadata->discriminatorMap; - $childDiscriminatorMap = $childMetadata->discriminatorMap; + $rootMetadata = $cmf->getMetadataFor(RootClass::class); + $childMetadata = $cmf->getMetadataFor(ChildClass::class); + $anotherChildMetadata = $cmf->getMetadataFor(AnotherChildClass::class); + $rootDiscriminatorMap = $rootMetadata->discriminatorMap; + $childDiscriminatorMap = $childMetadata->discriminatorMap; $anotherChildDiscriminatorMap = $anotherChildMetadata->discriminatorMap; - $rootClass = RootClass::class; - $childClass = ChildClass::class; + $rootClass = RootClass::class; + $childClass = ChildClass::class; $anotherChildClass = AnotherChildClass::class; - $rootClassKey = array_search($rootClass, $rootDiscriminatorMap); - $childClassKey = array_search($childClass, $rootDiscriminatorMap); + $rootClassKey = array_search($rootClass, $rootDiscriminatorMap); + $childClassKey = array_search($childClass, $rootDiscriminatorMap); $anotherChildClassKey = array_search($anotherChildClass, $rootDiscriminatorMap); $this->assertEquals('rootclass', $rootClassKey); @@ -210,16 +219,16 @@ public function testAddDefaultDiscriminatorMap() $rootMetadata = $cmf->getMetadataFor(RootClass::class); } - public function testGetAllMetadataWorksWithBadConnection() + public function testGetAllMetadataWorksWithBadConnection(): void { // DDC-3551 - $conn = $this->createMock(Connection::class); - $mockDriver = new MetadataDriverMock(); - $em = $this->_createEntityManager($mockDriver, $conn); + $conn = $this->createMock(Connection::class); + $mockDriver = new MetadataDriverMock(); + $em = $this->_createEntityManager($mockDriver, $conn); $conn->expects($this->any()) ->method('getDatabasePlatform') - ->will($this->throwException(new \Exception('Exception thrown in test when calling getDatabasePlatform'))); + ->will($this->throwException(new Exception('Exception thrown in test when calling getDatabasePlatform'))); $cmf = new ClassMetadataFactory(); $cmf->setEntityManager($em); @@ -233,35 +242,33 @@ public function testGetAllMetadataWorksWithBadConnection() protected function _createEntityManager($metadataDriver, $conn = null) { $driverMock = new DriverMock(); - $config = new Configuration(); + $config = new Configuration(); $config->setProxyDir(__DIR__ . '/../../Proxies'); $config->setProxyNamespace('Doctrine\Tests\Proxies'); $eventManager = new EventManager(); - if (!$conn) { + if (! $conn) { $conn = new ConnectionMock([], $driverMock, $config, $eventManager); } + $config->setMetadataDriverImpl($metadataDriver); return EntityManagerMock::create($conn, $config, $eventManager); } - /** - * @return ClassMetadataFactoryTestSubject - */ - protected function _createTestFactory() + protected function _createTestFactory(): ClassMetadataFactoryTestSubject { - $mockDriver = new MetadataDriverMock(); + $mockDriver = new MetadataDriverMock(); $entityManager = $this->_createEntityManager($mockDriver); - $cmf = new ClassMetadataFactoryTestSubject(); + $cmf = new ClassMetadataFactoryTestSubject(); $cmf->setEntityManager($entityManager); + return $cmf; } /** * @param string $class - * @return ClassMetadata */ - protected function _createValidClassMetadata() + protected function _createValidClassMetadata(): ClassMetadata { // Self-made metadata $cm1 = new ClassMetadata(TestEntity1::class); @@ -275,32 +282,31 @@ protected function _createValidClassMetadata() $cm1->mapOneToOne(['fieldName' => 'other', 'targetEntity' => 'TestEntity1', 'mappedBy' => 'this']); // and an association on the owning side $joinColumns = [ - ['name' => 'other_id', 'referencedColumnName' => 'id'] + ['name' => 'other_id', 'referencedColumnName' => 'id'], ]; $cm1->mapOneToOne( ['fieldName' => 'association', 'targetEntity' => 'TestEntity1', 'joinColumns' => $joinColumns] ); // and an id generator type $cm1->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_AUTO); + return $cm1; } /** - * @group DDC-1845 - */ - public function testQuoteMetadata() + * @group DDC-1845 + */ + public function testQuoteMetadata(): void { $cmf = new ClassMetadataFactory(); $driver = $this->createAnnotationDriver([__DIR__ . '/../../Models/Quote/']); $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); - + $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']); @@ -311,8 +317,6 @@ public function testQuoteMetadata() $this->assertEquals('user-id', $user['joinColumns'][0]['name']); $this->assertEquals('user-id', $user['joinColumns'][0]['referencedColumnName']); - - // User Group Metadata $this->assertTrue($groupMetadata->fieldMappings['id']['quoted']); $this->assertTrue($groupMetadata->fieldMappings['name']['quoted']); @@ -325,7 +329,6 @@ public function testQuoteMetadata() $this->assertEquals('parent-id', $user['joinColumns'][0]['name']); $this->assertEquals('group-id', $user['joinColumns'][0]['referencedColumnName']); - // Address Class Metadata $this->assertTrue($addressMetadata->fieldMappings['id']['quoted']); $this->assertTrue($addressMetadata->fieldMappings['zip']['quoted']); @@ -338,8 +341,6 @@ public function testQuoteMetadata() $this->assertEquals('user-id', $user['joinColumns'][0]['name']); $this->assertEquals('user-id', $user['joinColumns'][0]['referencedColumnName']); - - // User Class Metadata $this->assertTrue($userMetadata->fieldMappings['id']['quoted']); $this->assertTrue($userMetadata->fieldMappings['name']['quoted']); @@ -347,7 +348,6 @@ public function testQuoteMetadata() $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']); @@ -370,23 +370,23 @@ public function testQuoteMetadata() * @group 1181 * @group 385 */ - public function testFallbackLoadingCausesEventTriggeringThatCanModifyFetchedMetadata() + public function testFallbackLoadingCausesEventTriggeringThatCanModifyFetchedMetadata(): void { - $test = $this; - /** @var ClassMetadata $metadata */ - $metadata = $this->createMock(ClassMetadata::class); - $cmf = new ClassMetadataFactory(); - $mockDriver = new MetadataDriverMock(); - $em = $this->_createEntityManager($mockDriver); - $listener = $this->getMockBuilder(\stdClass::class)->setMethods(['onClassMetadataNotFound'])->getMock(); - $eventManager = $em->getEventManager(); + $test = $this; + $metadata = $this->createMock(ClassMetadata::class); + assert($metadata instanceof ClassMetadata); + $cmf = new ClassMetadataFactory(); + $mockDriver = new MetadataDriverMock(); + $em = $this->_createEntityManager($mockDriver); + $listener = $this->getMockBuilder(stdClass::class)->setMethods(['onClassMetadataNotFound'])->getMock(); + $eventManager = $em->getEventManager(); $cmf->setEntityManager($em); $listener ->expects($this->any()) ->method('onClassMetadataNotFound') - ->will($this->returnCallback(function (OnClassMetadataNotFoundEventArgs $args) use ($metadata, $em, $test) { + ->will($this->returnCallback(static function (OnClassMetadataNotFoundEventArgs $args) use ($metadata, $em, $test): void { $test->assertNull($args->getFoundMetadata()); $test->assertSame('Foo', $args->getClassName()); $test->assertSame($em, $args->getObjectManager()); @@ -402,12 +402,12 @@ public function testFallbackLoadingCausesEventTriggeringThatCanModifyFetchedMeta /** * @group DDC-3427 */ - public function testAcceptsEntityManagerInterfaceInstances() + public function testAcceptsEntityManagerInterfaceInstances(): void { $classMetadataFactory = new ClassMetadataFactory(); - /* @var $entityManager EntityManager */ - $entityManager = $this->createMock(EntityManagerInterface::class); + $entityManager = $this->createMock(EntityManagerInterface::class); + assert($entityManager instanceof EntityManager); $classMetadataFactory->setEntityManager($entityManager); @@ -421,15 +421,15 @@ public function testAcceptsEntityManagerInterfaceInstances() /** * @group DDC-3305 */ - public function testRejectsEmbeddableWithoutValidClassName() + public function testRejectsEmbeddableWithoutValidClassName(): void { $metadata = $this->_createValidClassMetadata(); $metadata->mapEmbedded( [ - 'fieldName' => 'embedded', - 'class' => '', - 'columnPrefix' => false, + 'fieldName' => 'embedded', + 'class' => '', + 'columnPrefix' => false, ] ); @@ -446,11 +446,11 @@ public function testRejectsEmbeddableWithoutValidClassName() /** * @group DDC-4006 */ - public function testInheritsIdGeneratorMappingFromEmbeddable() + public function testInheritsIdGeneratorMappingFromEmbeddable(): void { - $cmf = new ClassMetadataFactory(); + $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); @@ -458,7 +458,7 @@ public function testInheritsIdGeneratorMappingFromEmbeddable() $this->assertTrue($userMetadata->isIdGeneratorIdentity()); } - public function testInvalidSubClassCase() + public function testInvalidSubClassCase(): void { $this->expectException(MappingException::class); $this->expectExceptionMessage('Entity class \'Doctrine\Tests\ORM\Mapping\cube\' used in the discriminator map of class \'Doctrine\Tests\ORM\Mapping\Shape\' does not exist.'); @@ -492,20 +492,21 @@ final class Cube extends Shape /* Test subject class with overridden factory method for mocking purposes */ class ClassMetadataFactoryTestSubject extends ClassMetadataFactory { - private $mockMetadata = []; + private $mockMetadata = []; private $requestedClasses = []; /** @override */ protected function newClassMetadataInstance($className) { $this->requestedClasses[] = $className; - if ( ! isset($this->mockMetadata[$className])) { - throw new \InvalidArgumentException("No mock metadata found for class $className."); + if (! isset($this->mockMetadata[$className])) { + throw new InvalidArgumentException("No mock metadata found for class $className."); } + return $this->mockMetadata[$className]; } - public function setMetadataForClass($className, $metadata) + public function setMetadataForClass($className, $metadata): void { $this->mockMetadata[$className] = $metadata; } @@ -527,7 +528,7 @@ class TestEntity1 class CustomIdGenerator extends AbstractIdGenerator { - public function generate(EntityManager $em, $entity) + public function generate(EntityManager $em, $entity): void { } } diff --git a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataLoadEventTest.php b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataLoadEventTest.php index bf268cf829a..e951c6de851 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataLoadEventTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataLoadEventTest.php @@ -1,5 +1,7 @@ _getTestEntityManager(); + $em = $this->_getTestEntityManager(); $metadataFactory = $em->getMetadataFactory(); - $evm = $em->getEventManager(); + $evm = $em->getEventManager(); $evm->addEventListener(Events::loadClassMetadata, $this); $classMetadata = $metadataFactory->getMetadataFor(LoadEventTestEntity::class); $this->assertTrue($classMetadata->hasField('about')); @@ -23,13 +25,13 @@ public function testEvent() $this->assertInstanceOf('ReflectionProperty', $classMetadata->reflFields['about']); } - public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs) + public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs): void { $classMetadata = $eventArgs->getClassMetadata(); - $field = [ + $field = [ 'fieldName' => 'about', 'type' => 'string', - 'length' => 255 + 'length' => 255, ]; $classMetadata->mapField($field); } @@ -46,9 +48,7 @@ class LoadEventTestEntity * @GeneratedValue(strategy="AUTO") */ private $id; - /** - * @Column(type="string", length=255) - */ + /** @Column(type="string", length=255) */ private $name; private $about; diff --git a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataTest.php b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataTest.php index b5fbe239724..cc2cce062aa 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataTest.php @@ -1,10 +1,14 @@ initializeReflection(new RuntimeReflectionService()); // Test initial state - $this->assertTrue(count($cm->getReflectionProperties()) == 0); + $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); @@ -41,9 +57,9 @@ public function testClassMetadataInstanceSerialization() // Customize state $cm->setInheritanceType(ClassMetadata::INHERITANCE_TYPE_SINGLE_TABLE); - $cm->setSubclasses(["One", "Two", "Three"]); - $cm->setParentClasses(["UserParent"]); - $cm->setCustomRepositoryClass("UserRepository"); + $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(); @@ -51,30 +67,30 @@ public function testClassMetadataInstanceSerialization() $this->assertEquals(1, count($cm->associationMappings)); $serialized = serialize($cm); - $cm = unserialize($serialized); + $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->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->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->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); + $this->assertEquals(['dql' => ['name' => 'dql', 'query' => 'foo', 'dql' => 'foo']], $cm->namedQueries); } - public function testFieldIsNullable() + public function testFieldIsNullable(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); @@ -89,67 +105,69 @@ public function testFieldIsNullable() // Implicit Not Nullable $cm->mapField(['fieldName' => 'name', 'type' => 'string', 'length' => 50]); - $this->assertFalse($cm->isNullable('name'), "By default a field should not be nullable."); + $this->assertFalse($cm->isNullable('name'), 'By default a field should not be nullable.'); } /** * @group DDC-115 */ - public function testMapAssociationInGlobalNamespace() + public function testMapAssociationInGlobalNamespace(): void { - require_once __DIR__."/../../Models/Global/GlobalNamespaceModel.php"; + 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']], - ], + 'fieldName' => 'author', + 'targetEntity' => 'DoctrineGlobal_User', + 'joinTable' => [ + 'name' => 'bar', + 'joinColumns' => [['name' => 'bar_id', 'referencedColumnName' => 'id']], + 'inverseJoinColumns' => [['name' => 'baz_id', 'referencedColumnName' => 'id']], + ], ] ); - $this->assertEquals("DoctrineGlobal_User", $cm->associationMappings['author']['targetEntity']); + $this->assertEquals('DoctrineGlobal_User', $cm->associationMappings['author']['targetEntity']); } - public function testMapManyToManyJoinTableDefaults() + public function testMapManyToManyJoinTableDefaults(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $cm->mapManyToMany( [ - 'fieldName' => 'groups', - 'targetEntity' => 'CmsGroup' + 'fieldName' => 'groups', + 'targetEntity' => 'CmsGroup', ] ); $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']); + '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']); } - public function testSerializeManyToManyJoinTableCascade() + public function testSerializeManyToManyJoinTableCascade(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $cm->mapManyToMany( [ - 'fieldName' => 'groups', - 'targetEntity' => 'CmsGroup' + 'fieldName' => 'groups', + 'targetEntity' => 'CmsGroup', ] ); - /* @var $assoc \Doctrine\ORM\Mapping\ManyToMany */ $assoc = $cm->associationMappings['groups']; + assert($assoc instanceof ManyToMany); $assoc = unserialize(serialize($assoc)); $this->assertTrue($assoc['isOnDeleteCascade']); @@ -158,68 +176,68 @@ public function testSerializeManyToManyJoinTableCascade() /** * @group DDC-115 */ - public function testSetDiscriminatorMapInGlobalNamespace() + public function testSetDiscriminatorMapInGlobalNamespace(): void { - require_once __DIR__."/../../Models/Global/GlobalNamespaceModel.php"; + require_once __DIR__ . '/../../Models/Global/GlobalNamespaceModel.php'; $cm = new ClassMetadata('DoctrineGlobal_User'); $cm->initializeReflection(new RuntimeReflectionService()); $cm->setDiscriminatorMap(['descr' => 'DoctrineGlobal_Article', 'foo' => 'DoctrineGlobal_User']); - $this->assertEquals("DoctrineGlobal_Article", $cm->discriminatorMap['descr']); - $this->assertEquals("DoctrineGlobal_User", $cm->discriminatorMap['foo']); + $this->assertEquals('DoctrineGlobal_Article', $cm->discriminatorMap['descr']); + $this->assertEquals('DoctrineGlobal_User', $cm->discriminatorMap['foo']); } /** * @group DDC-115 */ - public function testSetSubClassesInGlobalNamespace() + public function testSetSubClassesInGlobalNamespace(): void { - require_once __DIR__."/../../Models/Global/GlobalNamespaceModel.php"; + require_once __DIR__ . '/../../Models/Global/GlobalNamespaceModel.php'; $cm = new ClassMetadata('DoctrineGlobal_User'); $cm->initializeReflection(new RuntimeReflectionService()); $cm->setSubclasses(['DoctrineGlobal_Article']); - $this->assertEquals("DoctrineGlobal_Article", $cm->subClasses[0]); + $this->assertEquals('DoctrineGlobal_Article', $cm->subClasses[0]); } /** * @group DDC-268 */ - public function testSetInvalidVersionMapping_ThrowsException() + public function testSetInvalidVersionMapping_ThrowsException(): void { - $field = []; + $field = []; $field['fieldName'] = 'foo'; - $field['type'] = 'string'; + $field['type'] = 'string'; $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); + $this->expectException(MappingException::class); $cm->setVersionMapping($field); } - public function testGetSingleIdentifierFieldName_MultipleIdentifierEntity_ThrowsException() + public function testGetSingleIdentifierFieldName_MultipleIdentifierEntity_ThrowsException(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->isIdentifierComposite = true; + $cm->isIdentifierComposite = true; - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); + $this->expectException(MappingException::class); $cm->getSingleIdentifierFieldName(); } - public function testGetSingleIdentifierFieldName_NoIdEntity_ThrowsException() + public function testGetSingleIdentifierFieldName_NoIdEntity_ThrowsException(): void { $cm = new ClassMetadata(DDC6412File::class); $cm->initializeReflection(new RuntimeReflectionService()); - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); + $this->expectException(MappingException::class); $cm->getSingleIdentifierFieldName(); } - public function testDuplicateAssociationMappingException() + public function testDuplicateAssociationMappingException(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); @@ -228,69 +246,69 @@ public function testDuplicateAssociationMappingException() $a2 = ['fieldName' => 'foo', 'sourceEntity' => 'stdClass', 'targetEntity' => 'stdClass', 'mappedBy' => 'foo']; $cm->addInheritedAssociationMapping($a1); - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); + $this->expectException(MappingException::class); $cm->addInheritedAssociationMapping($a2); } - public function testDuplicateColumnName_ThrowsMappingException() + public function testDuplicateColumnName_ThrowsMappingException(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $cm->mapField(['fieldName' => 'name', 'columnName' => 'name']); - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); + $this->expectException(MappingException::class); $cm->mapField(['fieldName' => 'username', 'columnName' => 'name']); } - public function testDuplicateColumnName_DiscriminatorColumn_ThrowsMappingException() + public function testDuplicateColumnName_DiscriminatorColumn_ThrowsMappingException(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $cm->mapField(['fieldName' => 'name', 'columnName' => 'name']); - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); + $this->expectException(MappingException::class); $cm->setDiscriminatorColumn(['name' => 'name']); } - public function testDuplicateColumnName_DiscriminatorColumn2_ThrowsMappingException() + public function testDuplicateColumnName_DiscriminatorColumn2_ThrowsMappingException(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $cm->setDiscriminatorColumn(['name' => 'name']); - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); + $this->expectException(MappingException::class); $cm->mapField(['fieldName' => 'name', 'columnName' => 'name']); } - public function testDuplicateFieldAndAssociationMapping1_ThrowsException() + public function testDuplicateFieldAndAssociationMapping1_ThrowsException(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $cm->mapField(['fieldName' => 'name', 'columnName' => 'name']); - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); + $this->expectException(MappingException::class); $cm->mapOneToOne(['fieldName' => 'name', 'targetEntity' => 'CmsUser']); } - public function testDuplicateFieldAndAssociationMapping2_ThrowsException() + public function testDuplicateFieldAndAssociationMapping2_ThrowsException(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $cm->mapOneToOne(['fieldName' => 'name', 'targetEntity' => 'CmsUser']); - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); + $this->expectException(MappingException::class); $cm->mapField(['fieldName' => 'name', 'columnName' => 'name']); } /** * @group DDC-1224 */ - public function testGetTemporaryTableNameSchema() + public function testGetTemporaryTableNameSchema(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); @@ -300,7 +318,7 @@ public function testGetTemporaryTableNameSchema() $this->assertEquals('foo_bar_id_tmp', $cm->getTemporaryIdTableName()); } - public function testDefaultTableName() + public function testDefaultTableName(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); @@ -322,14 +340,14 @@ public function testDefaultTableName() 'inversedBy' => 'users', 'joinTable' => [ 'joinColumns' => [['referencedColumnName' => 'id']], - 'inverseJoinColumns' => [['referencedColumnName' => 'id']] - ] + 'inverseJoinColumns' => [['referencedColumnName' => 'id']], + ], ] ); $this->assertEquals('cmsaddress_cmsuser', $cm->associationMappings['user']['joinTable']['name']); } - public function testDefaultJoinColumnName() + public function testDefaultJoinColumnName(): void { $cm = new ClassMetadata(CMS\CmsAddress::class); $cm->initializeReflection(new RuntimeReflectionService()); @@ -338,9 +356,9 @@ public function testDefaultJoinColumnName() // joinColumn's name will be automatically set to user_id $cm->mapOneToOne( [ - 'fieldName' => 'user', - 'targetEntity' => 'CmsUser', - 'joinColumns' => [['referencedColumnName' => 'id']] + 'fieldName' => 'user', + 'targetEntity' => 'CmsUser', + 'joinColumns' => [['referencedColumnName' => 'id']], ] ); $this->assertEquals('user_id', $cm->associationMappings['user']['joinColumns'][0]['name']); @@ -349,14 +367,14 @@ public function testDefaultJoinColumnName() $cm->initializeReflection(new RuntimeReflectionService()); $cm->mapManyToMany( [ - 'fieldName' => 'user', - 'targetEntity' => 'CmsUser', - 'inversedBy' => 'users', - 'joinTable' => [ + 'fieldName' => 'user', + 'targetEntity' => 'CmsUser', + 'inversedBy' => 'users', + 'joinTable' => [ 'name' => 'user_CmsUser', 'joinColumns' => [['referencedColumnName' => 'id']], - 'inverseJoinColumns' => [['referencedColumnName' => 'id']] - ] + 'inverseJoinColumns' => [['referencedColumnName' => 'id']], + ], ] ); $this->assertEquals('cmsaddress_id', $cm->associationMappings['user']['joinTable']['joinColumns'][0]['name']); @@ -366,7 +384,7 @@ public function testDefaultJoinColumnName() /** * @group DDC-559 */ - public function testUnderscoreNamingStrategyDefaults() + public function testUnderscoreNamingStrategyDefaults(): void { $namingStrategy = new UnderscoreNamingStrategy(CASE_UPPER); $oneToOneMetadata = new ClassMetadata(CMS\CmsAddress::class, $namingStrategy); @@ -374,31 +392,30 @@ public function testUnderscoreNamingStrategyDefaults() $oneToOneMetadata->mapOneToOne( [ - 'fieldName' => 'user', - 'targetEntity' => 'CmsUser' + 'fieldName' => 'user', + 'targetEntity' => 'CmsUser', ] ); $manyToManyMetadata->mapManyToMany( [ - 'fieldName' => 'user', - 'targetEntity' => 'CmsUser' + 'fieldName' => 'user', + 'targetEntity' => 'CmsUser', ] ); - $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']); + $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']); $this->assertEquals('USER_ID', $oneToOneMetadata->associationMappings['user']['joinColumns'][0]['name']); $this->assertEquals('ID', $oneToOneMetadata->associationMappings['user']['joinColumns'][0]['referencedColumnName']); - $this->assertEquals('CMS_ADDRESS_CMS_USER', $manyToManyMetadata->associationMappings['user']['joinTable']['name']); - $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']); + $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']); $this->assertEquals('CMS_ADDRESS_ID', $manyToManyMetadata->associationMappings['user']['joinTable']['joinColumns'][0]['name']); $this->assertEquals('CMS_USER_ID', $manyToManyMetadata->associationMappings['user']['joinTable']['inverseJoinColumns'][0]['name']); @@ -406,7 +423,6 @@ public function testUnderscoreNamingStrategyDefaults() $this->assertEquals('ID', $manyToManyMetadata->associationMappings['user']['joinTable']['joinColumns'][0]['referencedColumnName']); $this->assertEquals('ID', $manyToManyMetadata->associationMappings['user']['joinTable']['inverseJoinColumns'][0]['referencedColumnName']); - $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']); @@ -415,7 +431,7 @@ public function testUnderscoreNamingStrategyDefaults() /** * @group DDC-886 */ - public function testSetMultipleIdentifierSetsComposite() + public function testSetMultipleIdentifierSetsComposite(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); @@ -430,7 +446,7 @@ public function testSetMultipleIdentifierSetsComposite() /** * @group DDC-944 */ - public function testMappingNotFound() + public function testMappingNotFound(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); @@ -444,7 +460,7 @@ public function testMappingNotFound() /** * @group DDC-961 */ - public function testJoinTableMappingDefaults() + public function testJoinTableMappingDefaults(): void { $cm = new ClassMetadata('DoctrineGlobal_Article'); $cm->initializeReflection(new RuntimeReflectionService()); @@ -457,28 +473,28 @@ public function testJoinTableMappingDefaults() /** * @group DDC-117 */ - public function testMapIdentifierAssociation() + public function testMapIdentifierAssociation(): void { $cm = new ClassMetadata(DDC117ArticleDetails::class); $cm->initializeReflection(new RuntimeReflectionService()); $cm->mapOneToOne( [ - 'fieldName' => 'article', - 'id' => true, - 'targetEntity' => DDC117Article::class, - 'joinColumns' => [], + 'fieldName' => 'article', + 'id' => true, + 'targetEntity' => DDC117Article::class, + 'joinColumns' => [], ] ); $this->assertTrue($cm->containsForeignIdentifier, "Identifier Association should set 'containsForeignIdentifier' boolean flag."); - $this->assertEquals(["article"], $cm->identifier); + $this->assertEquals(['article'], $cm->identifier); } /** * @group DDC-117 */ - public function testOrphanRemovalIdentifierAssociation() + public function testOrphanRemovalIdentifierAssociation(): void { $cm = new ClassMetadata(DDC117ArticleDetails::class); $cm->initializeReflection(new RuntimeReflectionService()); @@ -488,11 +504,11 @@ public function testOrphanRemovalIdentifierAssociation() $cm->mapOneToOne( [ - 'fieldName' => 'article', - 'id' => true, - 'targetEntity' => DDC117Article::class, - 'orphanRemoval' => true, - 'joinColumns' => [], + 'fieldName' => 'article', + 'id' => true, + 'targetEntity' => DDC117Article::class, + 'orphanRemoval' => true, + 'joinColumns' => [], ] ); } @@ -500,7 +516,7 @@ public function testOrphanRemovalIdentifierAssociation() /** * @group DDC-117 */ - public function testInverseIdentifierAssociation() + public function testInverseIdentifierAssociation(): void { $cm = new ClassMetadata(DDC117ArticleDetails::class); $cm->initializeReflection(new RuntimeReflectionService()); @@ -510,11 +526,11 @@ public function testInverseIdentifierAssociation() $cm->mapOneToOne( [ - 'fieldName' => 'article', - 'id' => true, - 'mappedBy' => 'details', // INVERSE! - 'targetEntity' => DDC117Article::class, - 'joinColumns' => [], + 'fieldName' => 'article', + 'id' => true, + 'mappedBy' => 'details', // INVERSE! + 'targetEntity' => DDC117Article::class, + 'joinColumns' => [], ] ); } @@ -522,7 +538,7 @@ public function testInverseIdentifierAssociation() /** * @group DDC-117 */ - public function testIdentifierAssociationManyToMany() + public function testIdentifierAssociationManyToMany(): void { $cm = new ClassMetadata(DDC117ArticleDetails::class); $cm->initializeReflection(new RuntimeReflectionService()); @@ -532,10 +548,10 @@ public function testIdentifierAssociationManyToMany() $cm->mapManyToMany( [ - 'fieldName' => 'article', - 'id' => true, - 'targetEntity' => DDC117Article::class, - 'joinColumns' => [], + 'fieldName' => 'article', + 'id' => true, + 'targetEntity' => DDC117Article::class, + 'joinColumns' => [], ] ); } @@ -543,7 +559,7 @@ public function testIdentifierAssociationManyToMany() /** * @group DDC-996 */ - public function testEmptyFieldNameThrowsException() + public function testEmptyFieldNameThrowsException(): void { $this->expectException(MappingException::class); $this->expectExceptionMessage("The field or association mapping misses the 'fieldName' attribute in entity '" . CMS\CmsUser::class . "'."); @@ -554,18 +570,17 @@ public function testEmptyFieldNameThrowsException() $cm->mapField(['fieldName' => '']); } - public function testRetrievalOfNamedQueries() + public function testRetrievalOfNamedQueries(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $this->assertEquals(0, count($cm->getNamedQueries())); $cm->addNamedQuery( [ - 'name' => 'userById', - 'query' => 'SELECT u FROM __CLASS__ u WHERE u.id = ?1' + 'name' => 'userById', + 'query' => 'SELECT u FROM __CLASS__ u WHERE u.id = ?1', ] ); @@ -575,38 +590,36 @@ public function testRetrievalOfNamedQueries() /** * @group DDC-1663 */ - public function testRetrievalOfResultSetMappings() + public function testRetrievalOfResultSetMappings(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $this->assertEquals(0, count($cm->getSqlResultSetMappings())); $cm->addSqlResultSetMapping( [ - 'name' => 'find-all', - 'entities' => [ - [ - 'entityClass' => CMS\CmsUser::class, + 'name' => 'find-all', + 'entities' => [ + [ + 'entityClass' => CMS\CmsUser::class, + ], ], - ], ] ); $this->assertEquals(1, count($cm->getSqlResultSetMappings())); } - public function testExistanceOfNamedQuery() + public function testExistanceOfNamedQuery(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->addNamedQuery( [ - 'name' => 'all', - 'query' => 'SELECT u FROM __CLASS__ u' + 'name' => 'all', + 'query' => 'SELECT u FROM __CLASS__ u', ] ); @@ -617,26 +630,26 @@ public function testExistanceOfNamedQuery() /** * @group DDC-1663 */ - public function testRetrieveOfNamedNativeQuery() + public function testRetrieveOfNamedNativeQuery(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $cm->addNamedNativeQuery( [ - 'name' => 'find-all', - 'query' => 'SELECT * FROM cms_users', - 'resultSetMapping' => 'result-mapping-name', - 'resultClass' => CMS\CmsUser::class, + 'name' => 'find-all', + 'query' => 'SELECT * FROM cms_users', + 'resultSetMapping' => 'result-mapping-name', + 'resultClass' => CMS\CmsUser::class, ] ); $cm->addNamedNativeQuery( [ - 'name' => 'find-by-id', - 'query' => 'SELECT * FROM cms_users WHERE id = ?', - 'resultClass' => '__CLASS__', - 'resultSetMapping' => 'result-mapping-name', + 'name' => 'find-by-id', + 'query' => 'SELECT * FROM cms_users WHERE id = ?', + 'resultClass' => '__CLASS__', + 'resultSetMapping' => 'result-mapping-name', ] ); @@ -654,59 +667,57 @@ public function testRetrieveOfNamedNativeQuery() /** * @group DDC-1663 */ - public function testRetrieveOfSqlResultSetMapping() + public function testRetrieveOfSqlResultSetMapping(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $cm->addSqlResultSetMapping( [ - 'name' => 'find-all', - 'entities' => [ - [ - 'entityClass' => '__CLASS__', - 'fields' => [ - [ - 'name' => 'id', - 'column'=> 'id' + 'name' => 'find-all', + 'entities' => [ + [ + 'entityClass' => '__CLASS__', + 'fields' => [ + [ + 'name' => 'id', + 'column' => 'id', + ], + [ + 'name' => 'name', + 'column' => 'name', + ], ], - [ - 'name' => 'name', - 'column'=> 'name' - ] - ] - ], - [ - 'entityClass' => CMS\CmsEmail::class, - 'fields' => [ - [ - 'name' => 'id', - 'column'=> 'id' + ], + [ + 'entityClass' => CMS\CmsEmail::class, + 'fields' => [ + [ + 'name' => 'id', + 'column' => 'id', + ], + [ + 'name' => 'email', + 'column' => 'email', + ], ], - [ - '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]); + $this->assertEquals(['name' => 'id', 'column' => 'id'], $mapping['entities'][0]['fields'][0]); + $this->assertEquals(['name' => 'name', 'column' => 'name'], $mapping['entities'][0]['fields'][1]); $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]); + $this->assertEquals(['name' => 'id', 'column' => 'id'], $mapping['entities'][1]['fields'][0]); + $this->assertEquals(['name' => 'email', 'column' => 'email'], $mapping['entities'][1]['fields'][1]); $this->assertEquals('scalarColumn', $mapping['columns'][0]['name']); } @@ -714,19 +725,19 @@ public function testRetrieveOfSqlResultSetMapping() /** * @group DDC-1663 */ - public function testExistanceOfSqlResultSetMapping() + public function testExistanceOfSqlResultSetMapping(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $cm->addSqlResultSetMapping( [ - 'name' => 'find-all', - 'entities' => [ - [ - 'entityClass' => CMS\CmsUser::class, + 'name' => 'find-all', + 'entities' => [ + [ + 'entityClass' => CMS\CmsUser::class, + ], ], - ], ] ); @@ -737,18 +748,17 @@ public function testExistanceOfSqlResultSetMapping() /** * @group DDC-1663 */ - public function testExistanceOfNamedNativeQuery() + public function testExistanceOfNamedNativeQuery(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->addNamedNativeQuery( [ - 'name' => 'find-all', - 'query' => 'SELECT * FROM cms_users', - 'resultClass' => CMS\CmsUser::class, - 'resultSetMapping' => 'result-mapping-name' + 'name' => 'find-all', + 'query' => 'SELECT * FROM cms_users', + 'resultClass' => CMS\CmsUser::class, + 'resultSetMapping' => 'result-mapping-name', ] ); @@ -756,16 +766,15 @@ public function testExistanceOfNamedNativeQuery() $this->assertFalse($cm->hasNamedNativeQuery('find-by-id')); } - public function testRetrieveOfNamedQuery() + public function testRetrieveOfNamedQuery(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->addNamedQuery( [ - 'name' => 'userById', - 'query' => 'SELECT u FROM __CLASS__ u WHERE u.id = ?1' + 'name' => 'userById', + 'query' => 'SELECT u FROM __CLASS__ u WHERE u.id = ?1', ] ); @@ -775,7 +784,7 @@ public function testRetrieveOfNamedQuery() /** * @group DDC-1663 */ - public function testRetrievalOfNamedNativeQueries() + public function testRetrievalOfNamedNativeQueries(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); @@ -784,10 +793,10 @@ public function testRetrievalOfNamedNativeQueries() $cm->addNamedNativeQuery( [ - 'name' => 'find-all', - 'query' => 'SELECT * FROM cms_users', - 'resultClass' => CMS\CmsUser::class, - 'resultSetMapping' => 'result-mapping-name' + 'name' => 'find-all', + 'query' => 'SELECT * FROM cms_users', + 'resultClass' => CMS\CmsUser::class, + 'resultSetMapping' => 'result-mapping-name', ] ); @@ -797,7 +806,7 @@ public function testRetrievalOfNamedNativeQueries() /** * @group DDC-2451 */ - public function testSerializeEntityListeners() + public function testSerializeEntityListeners(): void { $metadata = new ClassMetadata(CompanyContract::class); @@ -811,7 +820,7 @@ public function testSerializeEntityListeners() $this->assertEquals($metadata->entityListeners, $unserialize->entityListeners); } - public function testNamingCollisionNamedQueryShouldThrowException() + public function testNamingCollisionNamedQueryShouldThrowException(): void { $this->expectException('Doctrine\ORM\Mapping\MappingException'); $this->expectExceptionMessage('Query named "userById" in "Doctrine\Tests\Models\CMS\CmsUser" was already declared, but it must be declared only once'); @@ -820,15 +829,15 @@ public function testNamingCollisionNamedQueryShouldThrowException() $cm->addNamedQuery( [ - 'name' => 'userById', - 'query' => 'SELECT u FROM __CLASS__ u WHERE u.id = ?1' + 'name' => 'userById', + 'query' => 'SELECT u FROM __CLASS__ u WHERE u.id = ?1', ] ); $cm->addNamedQuery( [ - 'name' => 'userById', - 'query' => 'SELECT u FROM __CLASS__ u WHERE u.id = ?1' + 'name' => 'userById', + 'query' => 'SELECT u FROM __CLASS__ u WHERE u.id = ?1', ] ); } @@ -836,7 +845,7 @@ public function testNamingCollisionNamedQueryShouldThrowException() /** * @group DDC-1663 */ - public function testNamingCollisionNamedNativeQueryShouldThrowException() + public function testNamingCollisionNamedNativeQueryShouldThrowException(): void { $this->expectException('Doctrine\ORM\Mapping\MappingException'); $this->expectExceptionMessage('Query named "find-all" in "Doctrine\Tests\Models\CMS\CmsUser" was already declared, but it must be declared only once'); @@ -845,19 +854,19 @@ public function testNamingCollisionNamedNativeQueryShouldThrowException() $cm->addNamedNativeQuery( [ - 'name' => 'find-all', - 'query' => 'SELECT * FROM cms_users', - 'resultClass' => CMS\CmsUser::class, - 'resultSetMapping' => 'result-mapping-name' + 'name' => 'find-all', + 'query' => 'SELECT * FROM cms_users', + 'resultClass' => CMS\CmsUser::class, + 'resultSetMapping' => 'result-mapping-name', ] ); $cm->addNamedNativeQuery( [ - 'name' => 'find-all', - 'query' => 'SELECT * FROM cms_users', - 'resultClass' => CMS\CmsUser::class, - 'resultSetMapping' => 'result-mapping-name' + 'name' => 'find-all', + 'query' => 'SELECT * FROM cms_users', + 'resultClass' => CMS\CmsUser::class, + 'resultSetMapping' => 'result-mapping-name', ] ); } @@ -865,7 +874,7 @@ public function testNamingCollisionNamedNativeQueryShouldThrowException() /** * @group DDC-1663 */ - public function testNamingCollisionSqlResultSetMappingShouldThrowException() + public function testNamingCollisionSqlResultSetMappingShouldThrowException(): void { $this->expectException('Doctrine\ORM\Mapping\MappingException'); $this->expectExceptionMessage('Result set mapping named "find-all" in "Doctrine\Tests\Models\CMS\CmsUser" was already declared, but it must be declared only once'); @@ -874,23 +883,23 @@ public function testNamingCollisionSqlResultSetMappingShouldThrowException() $cm->addSqlResultSetMapping( [ - 'name' => 'find-all', - 'entities' => [ - [ - 'entityClass' => CMS\CmsUser::class, + 'name' => 'find-all', + 'entities' => [ + [ + 'entityClass' => CMS\CmsUser::class, + ], ], - ], ] ); $cm->addSqlResultSetMapping( [ - 'name' => 'find-all', - 'entities' => [ - [ - 'entityClass' => CMS\CmsUser::class, + 'name' => 'find-all', + 'entities' => [ + [ + 'entityClass' => CMS\CmsUser::class, + ], ], - ], ] ); } @@ -898,10 +907,10 @@ public function testNamingCollisionSqlResultSetMappingShouldThrowException() /** * @group DDC-1068 */ - public function testClassCaseSensitivity() + public function testClassCaseSensitivity(): void { $user = new CMS\CmsUser(); - $cm = new ClassMetadata(strtoupper(CMS\CmsUser::class)); + $cm = new ClassMetadata(strtoupper(CMS\CmsUser::class)); $cm->initializeReflection(new RuntimeReflectionService()); $this->assertEquals(CMS\CmsUser::class, $cm->name); @@ -910,7 +919,7 @@ public function testClassCaseSensitivity() /** * @group DDC-659 */ - public function testLifecycleCallbackNotFound() + public function testLifecycleCallbackNotFound(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); @@ -925,7 +934,7 @@ public function testLifecycleCallbackNotFound() /** * @group ImproveErrorMessages */ - public function testTargetEntityNotFound() + public function testTargetEntityNotFound(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); @@ -940,23 +949,21 @@ public function testTargetEntityNotFound() /** * @group DDC-1663 */ - public function testNameIsMandatoryForNamedQueryMappingException() + public function testNameIsMandatoryForNamedQueryMappingException(): void { $this->expectException('Doctrine\ORM\Mapping\MappingException'); $this->expectExceptionMessage('Query name on entity class \'Doctrine\Tests\Models\CMS\CmsUser\' is not defined.'); $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $cm->addNamedQuery( - [ - 'query' => 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', - ] + ['query' => 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u'] ); } /** * @group DDC-1663 */ - public function testNameIsMandatoryForNameNativeQueryMappingException() + public function testNameIsMandatoryForNameNativeQueryMappingException(): void { $this->expectException('Doctrine\ORM\Mapping\MappingException'); $this->expectExceptionMessage('Query name on entity class \'Doctrine\Tests\Models\CMS\CmsUser\' is not defined.'); @@ -964,9 +971,9 @@ public function testNameIsMandatoryForNameNativeQueryMappingException() $cm->initializeReflection(new RuntimeReflectionService()); $cm->addNamedQuery( [ - 'query' => 'SELECT * FROM cms_users', - 'resultClass' => CMS\CmsUser::class, - 'resultSetMapping' => 'result-mapping-name' + 'query' => 'SELECT * FROM cms_users', + 'resultClass' => CMS\CmsUser::class, + 'resultSetMapping' => 'result-mapping-name', ] ); } @@ -974,7 +981,7 @@ public function testNameIsMandatoryForNameNativeQueryMappingException() /** * @group DDC-1663 */ - public function testNameIsMandatoryForEntityNameSqlResultSetMappingException() + public function testNameIsMandatoryForEntityNameSqlResultSetMappingException(): void { $this->expectException('Doctrine\ORM\Mapping\MappingException'); $this->expectExceptionMessage('Result set mapping named "find-all" in "Doctrine\Tests\Models\CMS\CmsUser requires a entity class name.'); @@ -982,17 +989,17 @@ public function testNameIsMandatoryForEntityNameSqlResultSetMappingException() $cm->initializeReflection(new RuntimeReflectionService()); $cm->addSqlResultSetMapping( [ - 'name' => 'find-all', - 'entities' => [ - [ - 'fields' => [] - ] - ], + 'name' => 'find-all', + 'entities' => [ + [ + 'fields' => [], + ], + ], ] ); } - public function testNameIsMandatoryForDiscriminatorColumnsMappingException() + public function testNameIsMandatoryForDiscriminatorColumnsMappingException(): void { $this->expectException('Doctrine\ORM\Mapping\MappingException'); $this->expectExceptionMessage('Discriminator column name on entity class \'Doctrine\Tests\Models\CMS\CmsUser\' is not defined.'); @@ -1006,12 +1013,12 @@ public function testNameIsMandatoryForDiscriminatorColumnsMappingException() * @group DDC-559 * @group DDC-1575 */ - public function testFullyQualifiedClassNameShouldBeGivenToNamingStrategy() + public function testFullyQualifiedClassNameShouldBeGivenToNamingStrategy(): void { - $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 = new ClassMetadata(CMS\CmsAddress::class, $namingStrategy); + $articleMetadata = new ClassMetadata(DoctrineGlobal_Article::class, $namingStrategy); + $routingMetadata = new ClassMetadata(RoutingLeg::class, $namingStrategy); $addressMetadata->initializeReflection(new RuntimeReflectionService()); $articleMetadata->initializeReflection(new RuntimeReflectionService()); @@ -1019,15 +1026,15 @@ public function testFullyQualifiedClassNameShouldBeGivenToNamingStrategy() $addressMetadata->mapManyToMany( [ - 'fieldName' => 'user', - 'targetEntity' => 'CmsUser' + 'fieldName' => 'user', + 'targetEntity' => 'CmsUser', ] ); $articleMetadata->mapManyToMany( [ - 'fieldName' => 'author', - 'targetEntity' => CMS\CmsUser::class + 'fieldName' => 'author', + 'targetEntity' => CMS\CmsUser::class, ] ); @@ -1040,41 +1047,40 @@ public function testFullyQualifiedClassNameShouldBeGivenToNamingStrategy() * @group DDC-984 * @group DDC-559 */ - public function testFullyQualifiedClassNameShouldBeGivenToNamingStrategyPropertyToColumnName() + public function testFullyQualifiedClassNameShouldBeGivenToNamingStrategyPropertyToColumnName(): void { $namingStrategy = new MyPrefixNamingStrategy(); $metadata = new ClassMetadata(CMS\CmsAddress::class, $namingStrategy); $metadata->initializeReflection(new RuntimeReflectionService()); - $metadata->mapField(['fieldName'=>'country']); - $metadata->mapField(['fieldName'=>'city']); + $metadata->mapField(['fieldName' => 'country']); + $metadata->mapField(['fieldName' => 'city']); $this->assertEquals($metadata->fieldNames, [ 'cmsaddress_country' => 'country', - 'cmsaddress_city' => 'city' - ] - ); + 'cmsaddress_city' => 'city', + ]); } /** * @group DDC-1746 */ - public function testInvalidCascade() + public function testInvalidCascade(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $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'"); + $this->expectExceptionMessage('You have specified invalid cascade options for ' . CMS\CmsUser::class . "::\$address: 'invalid'; available options: 'remove', 'persist', 'refresh', 'merge', and 'detach'"); $cm->mapManyToOne(['fieldName' => 'address', 'targetEntity' => 'UnknownClass', 'cascade' => ['invalid']]); - } + } /** * @group DDC-964 */ - public function testInvalidPropertyAssociationOverrideNameException() + public function testInvalidPropertyAssociationOverrideNameException(): void { $this->expectException('Doctrine\ORM\Mapping\MappingException'); $this->expectExceptionMessage('Invalid field override named \'invalidPropertyName\' for class \'Doctrine\Tests\Models\DDC964\DDC964Admin'); @@ -1088,7 +1094,7 @@ public function testInvalidPropertyAssociationOverrideNameException() /** * @group DDC-964 */ - public function testInvalidPropertyAttributeOverrideNameException() + public function testInvalidPropertyAttributeOverrideNameException(): void { $this->expectException('Doctrine\ORM\Mapping\MappingException'); $this->expectExceptionMessage('Invalid field override named \'invalidPropertyName\' for class \'Doctrine\Tests\Models\DDC964\DDC964Guest\'.'); @@ -1102,21 +1108,21 @@ public function testInvalidPropertyAttributeOverrideNameException() /** * @group DDC-964 */ - public function testInvalidOverrideAttributeFieldTypeException() + public function testInvalidOverrideAttributeFieldTypeException(): void { $this->expectException('Doctrine\ORM\Mapping\MappingException'); $this->expectExceptionMessage('The column type of attribute \'name\' on class \'Doctrine\Tests\Models\DDC964\DDC964Guest\' could not be changed.'); $cm = new ClassMetadata(DDC964Guest::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->mapField(['fieldName' => 'name', 'type'=>'string']); + $cm->mapField(['fieldName' => 'name', 'type' => 'string']); - $cm->setAttributeOverride('name', ['type'=>'date']); + $cm->setAttributeOverride('name', ['type' => 'date']); } /** * @group DDC-1955 */ - public function testInvalidEntityListenerClassException() + public function testInvalidEntityListenerClassException(): void { $this->expectException('Doctrine\ORM\Mapping\MappingException'); $this->expectExceptionMessage('Entity Listener "\InvalidClassName" declared on "Doctrine\Tests\Models\CMS\CmsUser" not found.'); @@ -1129,7 +1135,7 @@ public function testInvalidEntityListenerClassException() /** * @group DDC-1955 */ - public function testInvalidEntityListenerMethodException() + public function testInvalidEntityListenerMethodException(): void { $this->expectException('Doctrine\ORM\Mapping\MappingException'); $this->expectExceptionMessage('Entity Listener "\Doctrine\Tests\Models\Company\CompanyContractListener" declared on "Doctrine\Tests\Models\CMS\CmsUser" has no method "invalidMethod".'); @@ -1139,14 +1145,14 @@ public function testInvalidEntityListenerMethodException() $cm->addEntityListener(Events::postLoad, '\Doctrine\Tests\Models\Company\CompanyContractListener', 'invalidMethod'); } - public function testManyToManySelfReferencingNamingStrategyDefaults() + public function testManyToManySelfReferencingNamingStrategyDefaults(): void { $cm = new ClassMetadata(CustomTypeParent::class); $cm->initializeReflection(new RuntimeReflectionService()); $cm->mapManyToMany( [ 'fieldName' => 'friendsWithMe', - 'targetEntity' => 'CustomTypeParent' + 'targetEntity' => 'CustomTypeParent', ] ); @@ -1166,12 +1172,12 @@ public function testManyToManySelfReferencingNamingStrategyDefaults() /** * @group DDC-2608 */ - public function testSetSequenceGeneratorThrowsExceptionWhenSequenceNameIsMissing() + public function testSetSequenceGeneratorThrowsExceptionWhenSequenceNameIsMissing(): void { $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); + $this->expectException(MappingException::class); $cm->setSequenceGeneratorDefinition([]); } @@ -1179,7 +1185,7 @@ public function testSetSequenceGeneratorThrowsExceptionWhenSequenceNameIsMissing * @group DDC-2662 * @group 6682 */ - public function testQuotedSequenceName() : void + public function testQuotedSequenceName(): void { $cm = new ClassMetadata(CMS\CmsUser::class); @@ -1195,7 +1201,7 @@ public function testQuotedSequenceName() : void /** * @group DDC-2700 */ - public function testIsIdentifierMappedSuperClass() + public function testIsIdentifierMappedSuperClass(): void { $class = new ClassMetadata(DDC2700MappedSuperClass::class); @@ -1205,7 +1211,7 @@ public function testIsIdentifierMappedSuperClass() /** * @group DDC-3120 */ - public function testCanInstantiateInternalPhpClassSubclass() + public function testCanInstantiateInternalPhpClassSubclass(): void { $classMetadata = new ClassMetadata(MyArrayObjectEntity::class); @@ -1215,25 +1221,25 @@ public function testCanInstantiateInternalPhpClassSubclass() /** * @group DDC-3120 */ - public function testCanInstantiateInternalPhpClassSubclassFromUnserializedMetadata() + public function testCanInstantiateInternalPhpClassSubclassFromUnserializedMetadata(): void { - /* @var $classMetadata ClassMetadata */ $classMetadata = unserialize(serialize(new ClassMetadata(MyArrayObjectEntity::class))); + assert($classMetadata instanceof ClassMetadata); $classMetadata->wakeupReflection(new RuntimeReflectionService()); $this->assertInstanceOf(MyArrayObjectEntity::class, $classMetadata->newInstance()); } - public function testWakeupReflectionWithEmbeddableAndStaticReflectionService() + public function testWakeupReflectionWithEmbeddableAndStaticReflectionService(): void { $classMetadata = new ClassMetadata(TestEntity1::class); $classMetadata->mapEmbedded( [ - 'fieldName' => 'test', - 'class' => TestEntity1::class, - 'columnPrefix' => false, + 'fieldName' => 'test', + 'class' => TestEntity1::class, + 'columnPrefix' => false, ] ); @@ -1242,7 +1248,7 @@ public function testWakeupReflectionWithEmbeddableAndStaticReflectionService() 'type' => 'string', 'originalClass' => TestEntity1::class, 'declaredField' => 'test', - 'originalField' => 'embeddedProperty' + 'originalField' => 'embeddedProperty', ]; $classMetadata->mapField($field); @@ -1251,7 +1257,7 @@ public function testWakeupReflectionWithEmbeddableAndStaticReflectionService() $this->assertEquals(['test' => null, 'test.embeddedProperty' => null], $classMetadata->getReflectionProperties()); } - public function testGetColumnNamesWithGivenFieldNames() + public function testGetColumnNamesWithGivenFieldNames(): void { $metadata = new ClassMetadata(CMS\CmsUser::class); $metadata->initializeReflection(new RuntimeReflectionService()); @@ -1266,7 +1272,7 @@ public function testGetColumnNamesWithGivenFieldNames() /** * @group DDC-6460 */ - public function testInlineEmbeddable() + public function testInlineEmbeddable(): void { $classMetadata = new ClassMetadata(TestEntity1::class); @@ -1317,6 +1323,6 @@ public function propertyToColumnName($propertyName, $className = null) } } -class MyArrayObjectEntity extends \ArrayObject +class MyArrayObjectEntity extends ArrayObject { } diff --git a/tests/Doctrine/Tests/ORM/Mapping/DefaultQuoteStrategyTest.php b/tests/Doctrine/Tests/ORM/Mapping/DefaultQuoteStrategyTest.php index 765518c41bb..689eb99646c 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/DefaultQuoteStrategyTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/DefaultQuoteStrategyTest.php @@ -1,5 +1,7 @@ */ class DefaultQuoteStrategyTest extends OrmTestCase { @@ -18,13 +20,13 @@ class DefaultQuoteStrategyTest extends OrmTestCase * @group DDC-3590 * @group 1316 */ - public function testGetJoinTableName() + public function testGetJoinTableName(): void { $em = $this->_getTestEntityManager(); $metadata = $em->getClassMetadata(NonPublicSchemaUser::class); $strategy = new DefaultQuoteStrategy(); - /* @var $platform AbstractPlatform */ $platform = $this->getMockForAbstractClass(AbstractPlatform::class); + assert($platform instanceof AbstractPlatform); $this->assertSame( 'readers.author_reader', diff --git a/tests/Doctrine/Tests/ORM/Mapping/EntityListenerResolverTest.php b/tests/Doctrine/Tests/ORM/Mapping/EntityListenerResolverTest.php index 878ab11379c..237f80dc9e7 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/EntityListenerResolverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/EntityListenerResolverTest.php @@ -1,5 +1,7 @@ resolver = new DefaultEntityListenerResolver(); + $this->resolver = new DefaultEntityListenerResolver(); } - public function testResolve() + public function testResolve(): void { - $className = '\Doctrine\Tests\Models\Company\CompanyContractListener'; - $object = $this->resolver->resolve($className); + $className = '\Doctrine\Tests\Models\Company\CompanyContractListener'; + $object = $this->resolver->resolve($className); $this->assertInstanceOf($className, $object); $this->assertSame($object, $this->resolver->resolve($className)); } - public function testRegisterAndResolve() + public function testRegisterAndResolve(): void { - $className = '\Doctrine\Tests\Models\Company\CompanyContractListener'; - $object = new $className(); + $className = '\Doctrine\Tests\Models\Company\CompanyContractListener'; + $object = new $className(); $this->resolver->register($object); $this->assertSame($object, $this->resolver->resolve($className)); } - public function testClearOne() + public function testClearOne(): void { - $className1 = '\Doctrine\Tests\Models\Company\CompanyContractListener'; - $className2 = '\Doctrine\Tests\Models\Company\CompanyFlexUltraContractListener'; + $className1 = '\Doctrine\Tests\Models\Company\CompanyContractListener'; + $className2 = '\Doctrine\Tests\Models\Company\CompanyFlexUltraContractListener'; $obj1 = $this->resolver->resolve($className1); $obj2 = $this->resolver->resolve($className2); @@ -64,10 +63,10 @@ public function testClearOne() $this->assertSame($obj2, $this->resolver->resolve($className2)); } - public function testClearAll() + public function testClearAll(): void { - $className1 = '\Doctrine\Tests\Models\Company\CompanyContractListener'; - $className2 = '\Doctrine\Tests\Models\Company\CompanyFlexUltraContractListener'; + $className1 = '\Doctrine\Tests\Models\Company\CompanyContractListener'; + $className2 = '\Doctrine\Tests\Models\Company\CompanyFlexUltraContractListener'; $obj1 = $this->resolver->resolve($className1); $obj2 = $this->resolver->resolve($className2); @@ -87,7 +86,7 @@ public function testClearAll() $this->assertNotSame($obj2, $this->resolver->resolve($className2)); } - public function testRegisterStringException() + public function testRegisterStringException(): void { $this->expectException('InvalidArgumentException'); $this->expectExceptionMessage('An object was expected, but got "string".'); diff --git a/tests/Doctrine/Tests/ORM/Mapping/FieldBuilderTest.php b/tests/Doctrine/Tests/ORM/Mapping/FieldBuilderTest.php index 0ec0798aae1..88fd2c7624d 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/FieldBuilderTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/FieldBuilderTest.php @@ -1,5 +1,7 @@ */ - public static function dataClassToTableName() : array + public static function dataClassToTableName(): array { return [ // DefaultNamingStrategy @@ -79,7 +80,7 @@ public static function dataClassToTableName() : array /** * @dataProvider dataClassToTableName */ - public function testClassToTableName(NamingStrategy $strategy, string $expected, string $className) : void + public function testClassToTableName(NamingStrategy $strategy, string $expected, string $className): void { self::assertSame($expected, $strategy->classToTableName($className)); } @@ -89,7 +90,7 @@ public function testClassToTableName(NamingStrategy $strategy, string $expected, * * @return array */ - public static function dataPropertyToColumnName() : array + public static function dataPropertyToColumnName(): array { return [ // DefaultNamingStrategy @@ -124,7 +125,7 @@ public static function dataPropertyToColumnName() : array /** * @dataProvider dataPropertyToColumnName */ - public function testPropertyToColumnName(NamingStrategy $strategy, string $expected, string $propertyName) : void + public function testPropertyToColumnName(NamingStrategy $strategy, string $expected, string $propertyName): void { self::assertSame($expected, $strategy->propertyToColumnName($propertyName)); } @@ -134,7 +135,7 @@ public function testPropertyToColumnName(NamingStrategy $strategy, string $expec * * @return array */ - public static function dataReferenceColumnName() : array + public static function dataReferenceColumnName(): array { return [ // DefaultNamingStrategy @@ -153,7 +154,7 @@ public static function dataReferenceColumnName() : array /** * @dataProvider dataReferenceColumnName */ - public function testReferenceColumnName(NamingStrategy $strategy, string $expected) : void + public function testReferenceColumnName(NamingStrategy $strategy, string $expected): void { self::assertSame($expected, $strategy->referenceColumnName()); } @@ -163,7 +164,7 @@ public function testReferenceColumnName(NamingStrategy $strategy, string $expect * * @return array */ - public static function dataJoinColumnName() : array + public static function dataJoinColumnName(): array { return [ // DefaultNamingStrategy @@ -200,7 +201,7 @@ public function testJoinColumnName( string $expected, string $propertyName, ?string $className = null - ) : void { + ): void { self::assertSame($expected, $strategy->joinColumnName($propertyName, $className)); } @@ -209,7 +210,7 @@ public function testJoinColumnName( * * @return array */ - public static function dataJoinTableName() : array + public static function dataJoinTableName(): array { return [ // DefaultNamingStrategy @@ -248,7 +249,7 @@ public function testJoinTableName( string $ownerEntity, string $associatedEntity, ?string $propertyName = null - ) : void { + ): void { self::assertSame($expected, $strategy->joinTableName($ownerEntity, $associatedEntity, $propertyName)); } @@ -257,7 +258,7 @@ public function testJoinTableName( * * @return array */ - public static function dataJoinKeyColumnName() : array + public static function dataJoinKeyColumnName(): array { return [ // DefaultNamingStrategy @@ -295,7 +296,7 @@ public function testJoinKeyColumnName( string $propertyEntityName, ?string $referencedColumnName = null, ?string $propertyName = null - ) : void { + ): void { self::assertSame($expected, $strategy->joinKeyColumnName($propertyEntityName, $referencedColumnName, $propertyName)); } } diff --git a/tests/Doctrine/Tests/ORM/Mapping/PHPMappingDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/PHPMappingDriverTest.php index 5a30fc36f03..a27364d0197 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/PHPMappingDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/PHPMappingDriverTest.php @@ -1,5 +1,7 @@ createClassMetadata(DDC889Class::class)); } - public function testFailingSecondLevelCacheAssociation() + public function testFailingSecondLevelCacheAssociation(): void { $this->expectException('Doctrine\ORM\Cache\CacheException'); $this->expectExceptionMessage('Entity association field "Doctrine\Tests\ORM\Mapping\PHPSLC#foo" not configured as part of the second-level cache.'); diff --git a/tests/Doctrine/Tests/ORM/Mapping/QuoteStrategyTest.php b/tests/Doctrine/Tests/ORM/Mapping/QuoteStrategyTest.php index 37ff16d4dea..1c2dd4ea1d3 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/QuoteStrategyTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/QuoteStrategyTest.php @@ -1,7 +1,10 @@ _getTestEntityManager(); + $em = $this->_getTestEntityManager(); $this->platform = $em->getConnection()->getDatabasePlatform(); $this->strategy = new DefaultQuoteStrategy(); } - /** - * @param string $className - * @return \Doctrine\ORM\Mapping\ClassMetadata - */ - private function createClassMetadata($className) + private function createClassMetadata(string $className): ClassMetadata { $cm = new ClassMetadata($className); $cm->initializeReflection(new RuntimeReflectionService()); @@ -48,7 +42,7 @@ private function createClassMetadata($className) return $cm; } - public function testConfiguration() + public function testConfiguration(): void { $em = $this->_getTestEntityManager(); $config = $em->getConfiguration(); @@ -62,78 +56,73 @@ public function testConfiguration() $this->assertInstanceOf(MyQuoteStrategy::class, $config->getQuoteStrategy()); } - public function testGetColumnName() + public function testGetColumnName(): void { $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)); + $this->assertEquals('id', $this->strategy->getColumnName('id', $cm, $this->platform)); + $this->assertEquals('"name"', $this->strategy->getColumnName('name', $cm, $this->platform)); } - public function testGetTableName() + public function testGetTableName(): void { $cm = $this->createClassMetadata(CmsUser::class); - $cm->setPrimaryTable(['name'=>'`cms_user`']); + $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']); + $cm->setPrimaryTable(['name' => 'cms_user']); $this->assertEquals('cms_user', $this->strategy->getTableName($cm, $this->platform)); } - public function testJoinTableName() + public function testJoinTableName(): void { $cm1 = $this->createClassMetadata(CmsAddress::class); $cm2 = $this->createClassMetadata(CmsAddress::class); $cm1->mapManyToMany( [ - 'fieldName' => 'user', - 'targetEntity' => 'CmsUser', - 'inversedBy' => 'users', - 'joinTable' => [ - 'name' => '`cmsaddress_cmsuser`' - ] + 'fieldName' => 'user', + 'targetEntity' => 'CmsUser', + 'inversedBy' => 'users', + 'joinTable' => ['name' => '`cmsaddress_cmsuser`'], ] ); $cm2->mapManyToMany( [ - 'fieldName' => 'user', - 'targetEntity' => 'CmsUser', - 'inversedBy' => 'users', - 'joinTable' => [ - 'name' => 'cmsaddress_cmsuser' - ] + '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() + public function testIdentifierColumnNames(): void { $cm1 = $this->createClassMetadata(CmsAddress::class); $cm2 = $this->createClassMetadata(CmsAddress::class); $cm1->mapField( [ - 'id' => true, - 'fieldName' => 'id', - 'columnName' => '`id`', + 'id' => true, + 'fieldName' => 'id', + 'columnName' => '`id`', ] ); $cm2->mapField( [ - 'id' => true, - 'fieldName' => 'id', - 'columnName' => 'id', + 'id' => true, + 'fieldName' => 'id', + 'columnName' => 'id', ] ); @@ -141,8 +130,7 @@ public function testIdentifierColumnNames() $this->assertEquals(['id'], $this->strategy->getIdentifierColumnNames($cm2, $this->platform)); } - - public function testColumnAlias() + public function testColumnAlias(): void { $i = 0; $this->assertEquals('columnName_0', $this->strategy->getColumnAlias('columnName', $i++, $this->platform)); @@ -151,70 +139,63 @@ public function testColumnAlias() $this->assertEquals('COLUMNNAME_3', $this->strategy->getColumnAlias('COLUMN-NAME-', $i++, $this->platform)); } - public function testQuoteIdentifierJoinColumns() + public function testQuoteIdentifierJoinColumns(): void { $cm = $this->createClassMetadata(DDC117ArticleDetails::class); $cm->mapOneToOne( [ - 'id' => true, - 'fieldName' => 'article', - 'targetEntity' => DDC117Article::class, - 'joinColumns' => [ - [ - 'name' => '`article`' - ] - ], + 'id' => true, + 'fieldName' => 'article', + 'targetEntity' => DDC117Article::class, + 'joinColumns' => [ + ['name' => '`article`'], + ], ] ); $this->assertEquals(['"article"'], $this->strategy->getIdentifierColumnNames($cm, $this->platform)); } - public function testJoinColumnName() + public function testJoinColumnName(): void { $cm = $this->createClassMetadata(DDC117ArticleDetails::class); $cm->mapOneToOne( [ - 'id' => true, - 'fieldName' => 'article', - 'targetEntity' => DDC117Article::class, - 'joinColumns' => [ - [ - 'name' => '`article`' - ] - ], + '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)); + $this->assertEquals('"article"', $this->strategy->getJoinColumnName($joinColumn, $cm, $this->platform)); } - public function testReferencedJoinColumnName() + public function testReferencedJoinColumnName(): void { $cm = $this->createClassMetadata(DDC117ArticleDetails::class); $cm->mapOneToOne( [ - 'id' => true, - 'fieldName' => 'article', - 'targetEntity' => DDC117Article::class, - 'joinColumns' => [ - [ - 'name' => '`article`' - ] - ], + '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)); + $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 index 86c4393513f..e668baa26c0 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/Reflection/ReflectionPropertiesGetterTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/Reflection/ReflectionPropertiesGetterTest.php @@ -1,5 +1,7 @@ getProperties(ClassWithMixedProperties::class); @@ -29,7 +34,7 @@ public function testRetrievesProperties() } } - public function testRetrievedInstancesAreNotStatic() + public function testRetrievedInstancesAreNotStatic(): void { $properties = (new ReflectionPropertiesGetter(new RuntimeReflectionService())) ->getProperties(ClassWithMixedProperties::class); @@ -39,7 +44,7 @@ public function testRetrievedInstancesAreNotStatic() } } - public function testExpectedKeys() + public function testExpectedKeys(): void { $properties = (new ReflectionPropertiesGetter(new RuntimeReflectionService())) ->getProperties(ClassWithMixedProperties::class); @@ -61,12 +66,12 @@ public function testExpectedKeys() $properties ); $this->assertArrayHasKey( - "publicProperty", + 'publicProperty', $properties ); } - public function testPropertiesAreAccessible() + public function testPropertiesAreAccessible(): void { $object = new ClassWithMixedProperties(); $properties = (new ReflectionPropertiesGetter(new RuntimeReflectionService())) @@ -77,7 +82,7 @@ public function testPropertiesAreAccessible() } } - public function testPropertyGetterIsIdempotent() + public function testPropertyGetterIsIdempotent(): void { $getter = (new ReflectionPropertiesGetter(new RuntimeReflectionService())); @@ -87,10 +92,10 @@ public function testPropertyGetterIsIdempotent() ); } - public function testPropertyGetterWillSkipPropertiesNotRetrievedByTheRuntimeReflectionService() + public function testPropertyGetterWillSkipPropertiesNotRetrievedByTheRuntimeReflectionService(): void { - /* @var $reflectionService ReflectionService|\PHPUnit_Framework_MockObject_MockObject */ $reflectionService = $this->createMock(ReflectionService::class); + assert($reflectionService instanceof ReflectionService || $reflectionService instanceof PHPUnit_Framework_MockObject_MockObject); $reflectionService ->expects($this->exactly(2)) @@ -110,10 +115,10 @@ public function testPropertyGetterWillSkipPropertiesNotRetrievedByTheRuntimeRefl $this->assertEmpty($getter->getProperties(ClassWithMixedProperties::class)); } - public function testPropertyGetterWillSkipClassesNotRetrievedByTheRuntimeReflectionService() + public function testPropertyGetterWillSkipClassesNotRetrievedByTheRuntimeReflectionService(): void { - /* @var $reflectionService ReflectionService|\PHPUnit_Framework_MockObject_MockObject */ $reflectionService = $this->createMock(ReflectionService::class); + assert($reflectionService instanceof ReflectionService || $reflectionService instanceof PHPUnit_Framework_MockObject_MockObject); $reflectionService ->expects($this->once()) diff --git a/tests/Doctrine/Tests/ORM/Mapping/ReflectionEmbeddedPropertyTest.php b/tests/Doctrine/Tests/ORM/Mapping/ReflectionEmbeddedPropertyTest.php index 82761282ad4..a5037ce901c 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/ReflectionEmbeddedPropertyTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/ReflectionEmbeddedPropertyTest.php @@ -1,11 +1,12 @@ getReflectionProperty(BooleanModel::class, 'id'), $this->getReflectionProperty(BooleanModel::class, 'id'), - BooleanModel::class + BooleanModel::class, ], // reflection on embeddables that have properties defined in abstract ancestors: [ $this->getReflectionProperty(BooleanModel::class, 'id'), $this->getReflectionProperty(AbstractEmbeddable::class, 'propertyInAbstractClass'), - ConcreteEmbeddable::class + ConcreteEmbeddable::class, ], [ $this->getReflectionProperty(BooleanModel::class, 'id'), $this->getReflectionProperty(ConcreteEmbeddable::class, 'propertyInConcreteClass'), - ConcreteEmbeddable::class + ConcreteEmbeddable::class, ], // reflection on classes extending internal PHP classes: [ $this->getReflectionProperty(ArrayObjectExtendingClass::class, 'publicProperty'), $this->getReflectionProperty(ArrayObjectExtendingClass::class, 'privateProperty'), - ArrayObjectExtendingClass::class + ArrayObjectExtendingClass::class, ], [ $this->getReflectionProperty(ArrayObjectExtendingClass::class, 'publicProperty'), $this->getReflectionProperty(ArrayObjectExtendingClass::class, 'protectedProperty'), - ArrayObjectExtendingClass::class + ArrayObjectExtendingClass::class, ], [ $this->getReflectionProperty(ArrayObjectExtendingClass::class, 'publicProperty'), $this->getReflectionProperty(ArrayObjectExtendingClass::class, 'publicProperty'), - ArrayObjectExtendingClass::class + ArrayObjectExtendingClass::class, ], ]; } - /** - * @param string $className - * @param string $propertyName - * - * @return ReflectionProperty - */ - private function getReflectionProperty($className, $propertyName) + private function getReflectionProperty(string $className, string $propertyName): ReflectionProperty { $reflectionProperty = new ReflectionProperty($className, $propertyName); diff --git a/tests/Doctrine/Tests/ORM/Mapping/StaticPHPMappingDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/StaticPHPMappingDriverTest.php index bdce6343d19..432d45c12e4 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/StaticPHPMappingDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/StaticPHPMappingDriverTest.php @@ -1,11 +1,15 @@ createClassMetadata(DDC889Class::class)); } @@ -27,7 +31,7 @@ public function testinvalidEntityOrMappedSuperClassShouldMentionParentClasses() * @group DDC-2825 * @group 881 */ - public function testSchemaDefinitionViaExplicitTableSchemaAnnotationProperty() + public function testSchemaDefinitionViaExplicitTableSchemaAnnotationProperty(): void { $this->markTestIncomplete(); } @@ -36,7 +40,7 @@ public function testSchemaDefinitionViaExplicitTableSchemaAnnotationProperty() * @group DDC-2825 * @group 881 */ - public function testSchemaDefinitionViaSchemaDefinedInTableNameInTableAnnotationProperty() + public function testSchemaDefinitionViaSchemaDefinedInTableNameInTableAnnotationProperty(): void { $this->markTestIncomplete(); } diff --git a/tests/Doctrine/Tests/ORM/Mapping/Symfony/AbstractDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/Symfony/AbstractDriverTest.php index 99e2d0230fb..76ce5b6cc98 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/Symfony/AbstractDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/Symfony/AbstractDriverTest.php @@ -1,77 +1,87 @@ getDriver( [ - 'MyNamespace\MySubnamespace\EntityFoo' => 'foo', - 'MyNamespace\MySubnamespace\Entity' => $this->dir, + 'MyNamespace\MySubnamespace\EntityFoo' => 'foo', + 'MyNamespace\MySubnamespace\Entity' => $this->dir, ] ); - touch($filename = $this->dir.'/Foo'.$this->getFileExtension()); + touch($filename = $this->dir . '/Foo' . $this->getFileExtension()); $this->assertEquals($filename, $driver->getLocator()->findMappingFile('MyNamespace\MySubnamespace\Entity\Foo')); } - public function testFindMappingFileInSubnamespace() + public function testFindMappingFileInSubnamespace(): void { $driver = $this->getDriver( [ - 'MyNamespace\MySubnamespace\Entity' => $this->dir, + 'MyNamespace\MySubnamespace\Entity' => $this->dir, ] ); - touch($filename = $this->dir.'/Foo.Bar'.$this->getFileExtension()); + touch($filename = $this->dir . '/Foo.Bar' . $this->getFileExtension()); $this->assertEquals($filename, $driver->getLocator()->findMappingFile('MyNamespace\MySubnamespace\Entity\Foo\Bar')); } - public function testFindMappingFileNamespacedFoundFileNotFound() + public function testFindMappingFileNamespacedFoundFileNotFound(): void { $this->expectException(MappingException::class); $this->expectExceptionMessage('No mapping file found named'); $driver = $this->getDriver( [ - 'MyNamespace\MySubnamespace\Entity' => $this->dir, + 'MyNamespace\MySubnamespace\Entity' => $this->dir, ] ); $driver->getLocator()->findMappingFile('MyNamespace\MySubnamespace\Entity\Foo'); } - public function testFindMappingNamespaceNotFound() + public function testFindMappingNamespaceNotFound(): void { $this->expectException(MappingException::class); $this->expectExceptionMessage("No mapping file found named 'Foo" . $this->getFileExtension() . "' for class 'MyOtherNamespace\MySubnamespace\Entity\Foo'."); $driver = $this->getDriver( [ - 'MyNamespace\MySubnamespace\Entity' => $this->dir, + 'MyNamespace\MySubnamespace\Entity' => $this->dir, ] ); $driver->getLocator()->findMappingFile('MyOtherNamespace\MySubnamespace\Entity\Foo'); } - protected function setUp() : void + protected function setUp(): void { - $this->dir = sys_get_temp_dir().'/abstract_driver_test'; + $this->dir = sys_get_temp_dir() . '/abstract_driver_test'; @mkdir($this->dir, 0777, true); } - protected function tearDown() : void + protected function tearDown(): void { - $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->dir), \RecursiveIteratorIterator::CHILD_FIRST); + $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->dir), RecursiveIteratorIterator::CHILD_FIRST); foreach ($iterator as $path) { if ($path->isDir()) { @@ -84,6 +94,7 @@ protected function tearDown() : void @rmdir($this->dir); } - abstract protected function getFileExtension(); - abstract protected function getDriver(array $paths = []); + abstract protected function getFileExtension(): void; + + abstract protected function getDriver(array $paths = []): void; } diff --git a/tests/Doctrine/Tests/ORM/Mapping/Symfony/XmlDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/Symfony/XmlDriverTest.php index 2fa83681316..8771d42a4d8 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/Symfony/XmlDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/Symfony/XmlDriverTest.php @@ -1,8 +1,12 @@ _loadDriver(); @@ -42,7 +55,7 @@ public function testClassTableInheritanceDiscriminatorMap() $this->assertEquals($expectedMap, $class->discriminatorMap); } - public function testFailingSecondLevelCacheAssociation() + public function testFailingSecondLevelCacheAssociation(): void { $this->expectException('Doctrine\ORM\Cache\CacheException'); $this->expectExceptionMessage('Entity association field "Doctrine\Tests\ORM\Mapping\XMLSLC#foo" not configured as part of the second-level cache.'); @@ -52,7 +65,7 @@ public function testFailingSecondLevelCacheAssociation() $mappingDriver->loadMetadataForClass(XMLSLC::class, $class); } - public function testIdentifierWithAssociationKey() + public function testIdentifierWithAssociationKey(): void { $driver = $this->_loadDriver(); $em = $this->_getTestEntityManager(); @@ -70,7 +83,7 @@ public function testIdentifierWithAssociationKey() $this->assertTrue($class->associationMappings['article']['id']); } - public function testEmbeddableMapping() + public function testEmbeddableMapping(): void { $class = $this->createClassMetadata(Name::class); @@ -82,7 +95,7 @@ public function testEmbeddableMapping() * @group DDC-3477 * @group 1238 */ - public function testEmbeddedMappingsWithUseColumnPrefix() + public function testEmbeddedMappingsWithUseColumnPrefix(): void { $factory = new ClassMetadataFactory(); $em = $this->_getTestEntityManager(); @@ -102,7 +115,7 @@ public function testEmbeddedMappingsWithUseColumnPrefix() * @group DDC-3477 * @group 1238 */ - public function testEmbeddedMappingsWithFalseUseColumnPrefix() + public function testEmbeddedMappingsWithFalseUseColumnPrefix(): void { $factory = new ClassMetadataFactory(); $em = $this->_getTestEntityManager(); @@ -116,7 +129,7 @@ public function testEmbeddedMappingsWithFalseUseColumnPrefix() ); } - public function testEmbeddedMapping() + public function testEmbeddedMapping(): void { $class = $this->createClassMetadata(Person::class); @@ -127,7 +140,7 @@ public function testEmbeddedMapping() 'columnPrefix' => 'nm_', 'declaredField' => null, 'originalField' => null, - ] + ], ], $class->embeddedClasses ); @@ -136,7 +149,7 @@ public function testEmbeddedMapping() /** * @group DDC-1468 */ - public function testInvalidMappingFileException() + public function testInvalidMappingFileException(): void { $this->expectException('Doctrine\Persistence\Mapping\MappingException'); $this->expectExceptionMessage('Invalid mapping file \'Doctrine.Tests.Models.Generic.SerializationModel.dcm.xml\' for class \'Doctrine\Tests\Models\Generic\SerializationModel\'.'); @@ -144,32 +157,29 @@ public function testInvalidMappingFileException() } /** - * @param string $xmlMappingFile * @dataProvider dataValidSchema * @group DDC-2429 */ - public function testValidateXmlSchema($xmlMappingFile) + public function testValidateXmlSchema(string $xmlMappingFile): void { $xsdSchemaFile = __DIR__ . '/../../../../../doctrine-mapping.xsd'; - $dom = new \DOMDocument(); + $dom = new DOMDocument(); $dom->load($xmlMappingFile); $this->assertTrue($dom->schemaValidate($xsdSchemaFile)); } - static public function dataValidSchema() + public static function dataValidSchema() { $list = glob(__DIR__ . '/xml/*.xml'); - $invalid = [ - 'Doctrine.Tests.Models.DDC889.DDC889Class.dcm' - ]; + $invalid = ['Doctrine.Tests.Models.DDC889.DDC889Class.dcm']; - $list = array_filter($list, function($item) use ($invalid){ + $list = array_filter($list, static function ($item) use ($invalid) { return ! in_array(pathinfo($item, PATHINFO_FILENAME), $invalid); }); - return array_map(function($item){ + return array_map(static function ($item) { return [$item]; }, $list); } @@ -177,7 +187,7 @@ static public function dataValidSchema() /** * @group GH-7141 */ - public function testOneToManyDefaultOrderByAsc() + public function testOneToManyDefaultOrderByAsc(): void { $driver = $this->_loadDriver(); $class = new ClassMetadata(GH7141Article::class); @@ -185,16 +195,15 @@ public function testOneToManyDefaultOrderByAsc() $class->initializeReflection(new RuntimeReflectionService()); $driver->loadMetadataForClass(GH7141Article::class, $class); - $this->assertEquals( Criteria::ASC, $class->getMetadataValue('associationMappings')['tags']['orderBy']['position'] ); } - public function testManyToManyDefaultOrderByAsc() : void + public function testManyToManyDefaultOrderByAsc(): void { - $class = new ClassMetadata(GH7316Article::class); + $class = new ClassMetadata(GH7316Article::class); $class->initializeReflection(new RuntimeReflectionService()); $driver = $this->_loadDriver(); @@ -209,7 +218,7 @@ public function testManyToManyDefaultOrderByAsc() : void /** * @group DDC-889 */ - public function testinvalidEntityOrMappedSuperClassShouldMentionParentClasses() + public function testinvalidEntityOrMappedSuperClassShouldMentionParentClasses(): void { $this->expectException('Doctrine\Persistence\Mapping\MappingException'); $this->expectExceptionMessage('Invalid mapping file \'Doctrine.Tests.Models.DDC889.DDC889Class.dcm.xml\' for class \'Doctrine\Tests\Models\DDC889\DDC889Class\'.'); @@ -222,9 +231,15 @@ class CTI public $id; } -class CTIFoo extends CTI {} -class CTIBar extends CTI {} -class CTIBaz extends CTI {} +class CTIFoo extends CTI +{ +} +class CTIBar extends CTI +{ +} +class CTIBaz extends CTI +{ +} class XMLSLC { diff --git a/tests/Doctrine/Tests/ORM/Mapping/YamlMappingDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/YamlMappingDriverTest.php index 1edc4a1010e..e0d0ad5eaaf 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/YamlMappingDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/YamlMappingDriverTest.php @@ -1,5 +1,7 @@ markTestSkipped('Please install Symfony YAML Component into the include path of your PHP installation.'); } @@ -29,7 +35,7 @@ protected function _loadDriver() * * Entities for this test are in AbstractMappingDriverTest */ - public function testJoinTablesWithMappedSuperclassForYamlDriver() + public function testJoinTablesWithMappedSuperclassForYamlDriver(): void { $yamlDriver = $this->_loadDriver(); $yamlDriver->getLocator()->addPaths([__DIR__ . DIRECTORY_SEPARATOR . 'yaml']); @@ -52,7 +58,7 @@ public function testJoinTablesWithMappedSuperclassForYamlDriver() /** * @group DDC-1468 */ - public function testInvalidMappingFileException() + public function testInvalidMappingFileException(): void { $this->expectException('Doctrine\Persistence\Mapping\MappingException'); $this->expectExceptionMessage('Invalid mapping file \'Doctrine.Tests.Models.Generic.SerializationModel.dcm.yml\' for class \'Doctrine\Tests\Models\Generic\SerializationModel\'.'); @@ -62,7 +68,7 @@ public function testInvalidMappingFileException() /** * @group DDC-2069 */ - public function testSpacesShouldBeIgnoredWhenUseExplode() + public function testSpacesShouldBeIgnoredWhenUseExplode(): void { $metadata = $this->createClassMetadata(DDC2069Entity::class); $unique = $metadata->table['uniqueConstraints'][0]['columns']; @@ -82,7 +88,7 @@ public function testSpacesShouldBeIgnoredWhenUseExplode() $this->assertHasDeprecationMessages(); } - public function testDeprecation() : void + public function testDeprecation(): void { $this->createClassMetadata(DDC2069Entity::class); $this->expectDeprecationMessageSame('YAML mapping driver is deprecated and will be removed in Doctrine ORM 3.0, please migrate to annotation or XML driver.'); 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 index 7238eb15a05..1907de9d866 100644 --- 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 @@ -1,117 +1,115 @@ setPrimaryTable( - [ - 'name' => 'company_person', - ] + ['name' => 'company_person'] ); $metadata->mapField( [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', + 'id' => true, + 'fieldName' => 'id', + 'type' => 'integer', ] ); $metadata->mapField( [ - 'fieldName' => 'zip', - 'length' => 50, + 'fieldName' => 'zip', + 'length' => 50, ] ); $metadata->mapField( [ - 'fieldName' => 'city', - 'length' => 50, + 'fieldName' => 'city', + 'length' => 50, ] ); $metadata->mapOneToOne( [ - 'fieldName' => 'user', - 'targetEntity' => 'CmsUser', - 'joinColumns' => [['referencedColumnName' => 'id']] + 'fieldName' => 'user', + 'targetEntity' => 'CmsUser', + 'joinColumns' => [['referencedColumnName' => 'id']], ] ); $metadata->addNamedNativeQuery( [ - 'name' => 'find-all', - 'query' => 'SELECT id, country, city FROM cms_addresses', - 'resultSetMapping' => 'mapping-find-all', + '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, + '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', + '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, + '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' => [] - ] - ] + 'name' => 'mapping-without-fields', + 'columns' => [], + 'entities' => [ + [ + 'entityClass' => CmsAddress::class, + 'fields' => [], + ], + ], ] ); $metadata->addSqlResultSetMapping( [ - 'name' => 'mapping-count', - 'columns' => [ - [ - 'name' => 'count', + 'name' => 'mapping-count', + 'columns' => [ + ['name' => 'count'], ], ] - ] ); $metadata->addEntityListener(Events::postPersist, 'CmsAddressListener', 'postPersist'); 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 index 4b0075ecfe4..7e4eb9852c9 100644 --- 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 @@ -1,213 +1,209 @@ setPrimaryTable( - [ - 'name' => 'cms_users', - ] + ['name' => 'cms_users'] ); $metadata->addNamedNativeQuery( [ - 'name' => 'fetchIdAndUsernameWithResultClass', - 'query' => 'SELECT id, username FROM cms_users WHERE username = ?', - 'resultClass' => CmsUser::class, + '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, + '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', + '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', + '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', + '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" + '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 + '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 + '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', - ] + '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'], ], - 'entityClass' => CmsUser::class, - 'discriminatorColumn' => null - ] - ], - 'columns' => [ - [ - 'name' => 'numphones', - ] - ] ] ); $metadata->addSqlResultSetMapping( [ - 'name' => 'mappingMultipleJoinsEntityResults', - 'entities' => [ - [ - 'fields' => [ - [ - 'name' => 'id', - 'column' => 'u_id', + 'name' => 'mappingMultipleJoinsEntityResults', + 'entities' => [ + [ + 'fields' => [ + [ + 'name' => 'id', + 'column' => 'u_id', + ], + [ + 'name' => 'name', + 'column' => 'u_name', + ], + [ + 'name' => 'status', + 'column' => 'u_status', + ], ], - [ - 'name' => 'name', - 'column' => 'u_name', - ], - [ - 'name' => 'status', - 'column' => 'u_status', - ] + 'entityClass' => CmsUser::class, + 'discriminatorColumn' => null, ], - 'entityClass' => CmsUser::class, - 'discriminatorColumn' => null, - ], - [ - 'fields' => [ - [ - 'name' => 'id', - 'column' => 'a_id', - ], - [ - 'name' => 'zip', - 'column' => 'a_zip', - ], - [ - 'name' => 'country', - 'column' => 'a_country', + [ + 'fields' => [ + [ + 'name' => 'id', + 'column' => 'a_id', + ], + [ + 'name' => 'zip', + 'column' => 'a_zip', + ], + [ + 'name' => 'country', + 'column' => 'a_country', + ], ], + 'entityClass' => CmsAddress::class, + 'discriminatorColumn' => null, ], - 'entityClass' => CmsAddress::class, - 'discriminatorColumn' => null, ], - ], - 'columns' => [ - [ - 'name' => 'numphones', - ] - ] + '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 index 6ee9a78fc0b..ef01fa46232 100644 --- 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 @@ -1,5 +1,7 @@ enableCache( [ - 'usage' => ClassMetadataInfo::CACHE_USAGE_READ_ONLY + 'usage' => ClassMetadataInfo::CACHE_USAGE_READ_ONLY, ] ); $metadata->mapField( [ - 'fieldName' => 'id', - 'type' => 'integer', - 'id' => true, + 'fieldName' => 'id', + 'type' => 'integer', + 'id' => true, ] ); $metadata->mapField( [ - 'fieldName' => 'name', - 'type' => 'string', + 'fieldName' => 'name', + 'type' => 'string', ] ); $metadata->mapOneToOne( [ - 'fieldName' => 'state', - 'targetEntity' => State::class, - 'inversedBy' => 'cities', - 'joinColumns' => - [ - [ - 'name' => 'state_id', - 'referencedColumnName' => 'id', - ] - ] + 'fieldName' => 'state', + 'targetEntity' => State::class, + 'inversedBy' => 'cities', + 'joinColumns' => + [ + [ + 'name' => 'state_id', + 'referencedColumnName' => 'id', + ], + ], ] ); $metadata->enableAssociationCache('state', [ - 'usage' => ClassMetadataInfo::CACHE_USAGE_READ_ONLY -] -); + 'usage' => ClassMetadataInfo::CACHE_USAGE_READ_ONLY, +]); $metadata->mapManyToMany( [ - 'fieldName' => 'travels', - 'targetEntity' => Travel::class, - 'mappedBy' => 'visitedCities', + 'fieldName' => 'travels', + 'targetEntity' => Travel::class, + 'mappedBy' => 'visitedCities', ] ); $metadata->mapOneToMany( [ - 'fieldName' => 'attractions', - 'targetEntity' => Attraction::class, - 'mappedBy' => 'city', - 'orderBy' => ['name' => 'ASC',], + 'fieldName' => 'attractions', + 'targetEntity' => Attraction::class, + 'mappedBy' => 'city', + 'orderBy' => ['name' => 'ASC'], ] ); $metadata->enableAssociationCache('attractions', [ - 'usage' => ClassMetadataInfo::CACHE_USAGE_READ_ONLY -] -); + '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 index 33389ce9530..842980e2203 100644 --- 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 @@ -1,48 +1,51 @@ setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_JOINED); -$metadata->setTableName( 'company_contracts'); +$metadata->setTableName('company_contracts'); $metadata->setDiscriminatorColumn( [ - 'name' => 'discr', - 'type' => 'string', + 'name' => 'discr', + 'type' => 'string', ] ); $metadata->mapField( [ - 'id' => true, - 'name' => 'id', - 'fieldName' => 'id', + 'id' => true, + 'name' => 'id', + 'fieldName' => 'id', ] ); $metadata->mapField( [ - 'type' => 'boolean', - 'name' => 'completed', - 'fieldName' => 'completed', + 'type' => 'boolean', + 'name' => 'completed', + 'fieldName' => 'completed', ] ); $metadata->setDiscriminatorMap( [ - "fix" => "CompanyFixContract", - "flexible" => "CompanyFlexContract", - "flexultra" => "CompanyFlexUltraContract" + 'fix' => 'CompanyFixContract', + 'flexible' => 'CompanyFlexContract', + 'flexultra' => 'CompanyFlexUltraContract', ] ); -$metadata->addEntityListener(\Doctrine\ORM\Events::postPersist, 'CompanyContractListener', 'postPersistHandler'); -$metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CompanyContractListener', 'prePersistHandler'); +$metadata->addEntityListener(Events::postPersist, 'CompanyContractListener', 'postPersistHandler'); +$metadata->addEntityListener(Events::prePersist, 'CompanyContractListener', 'prePersistHandler'); -$metadata->addEntityListener(\Doctrine\ORM\Events::postUpdate, 'CompanyContractListener', 'postUpdateHandler'); -$metadata->addEntityListener(\Doctrine\ORM\Events::preUpdate, 'CompanyContractListener', 'preUpdateHandler'); +$metadata->addEntityListener(Events::postUpdate, 'CompanyContractListener', 'postUpdateHandler'); +$metadata->addEntityListener(Events::preUpdate, 'CompanyContractListener', 'preUpdateHandler'); -$metadata->addEntityListener(\Doctrine\ORM\Events::postRemove, 'CompanyContractListener', 'postRemoveHandler'); -$metadata->addEntityListener(\Doctrine\ORM\Events::preRemove, 'CompanyContractListener', 'preRemoveHandler'); +$metadata->addEntityListener(Events::postRemove, 'CompanyContractListener', 'postRemoveHandler'); +$metadata->addEntityListener(Events::preRemove, 'CompanyContractListener', 'preRemoveHandler'); -$metadata->addEntityListener(\Doctrine\ORM\Events::preFlush, 'CompanyContractListener', 'preFlushHandler'); -$metadata->addEntityListener(\Doctrine\ORM\Events::postLoad, 'CompanyContractListener', 'postLoadHandler'); +$metadata->addEntityListener(Events::preFlush, 'CompanyContractListener', 'preFlushHandler'); +$metadata->addEntityListener(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 index 3ea44ee7399..45cb4d631e2 100644 --- 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 @@ -1,9 +1,11 @@ mapField( [ - 'type' => 'integer', - 'name' => 'fixPrice', - 'fieldName' => 'fixPrice', + '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 index 7cc2b5504c9..76a7e05f420 100644 --- 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 @@ -1,17 +1,19 @@ mapField( [ - 'type' => 'integer', - 'name' => 'hoursWorked', - 'fieldName' => 'hoursWorked', + 'type' => 'integer', + 'name' => 'hoursWorked', + 'fieldName' => 'hoursWorked', ] ); $metadata->mapField( [ - 'type' => 'integer', - 'name' => 'pricePerHour', - 'fieldName' => 'pricePerHour', + '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 index 9e392416ded..0d9a1b53c4e 100644 --- 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 @@ -1,23 +1,27 @@ mapField( [ - 'type' => 'integer', - 'name' => 'maxPrice', - 'fieldName' => 'maxPrice', + 'type' => 'integer', + 'name' => 'maxPrice', + 'fieldName' => 'maxPrice', ] ); -$metadata->addEntityListener(\Doctrine\ORM\Events::postPersist, 'CompanyContractListener', 'postPersistHandler'); -$metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CompanyContractListener', 'prePersistHandler'); +$metadata->addEntityListener(Events::postPersist, 'CompanyContractListener', 'postPersistHandler'); +$metadata->addEntityListener(Events::prePersist, 'CompanyContractListener', 'prePersistHandler'); -$metadata->addEntityListener(\Doctrine\ORM\Events::postUpdate, 'CompanyContractListener', 'postUpdateHandler'); -$metadata->addEntityListener(\Doctrine\ORM\Events::preUpdate, 'CompanyContractListener', 'preUpdateHandler'); +$metadata->addEntityListener(Events::postUpdate, 'CompanyContractListener', 'postUpdateHandler'); +$metadata->addEntityListener(Events::preUpdate, 'CompanyContractListener', 'preUpdateHandler'); -$metadata->addEntityListener(\Doctrine\ORM\Events::postRemove, 'CompanyContractListener', 'postRemoveHandler'); -$metadata->addEntityListener(\Doctrine\ORM\Events::preRemove, 'CompanyContractListener', 'preRemoveHandler'); +$metadata->addEntityListener(Events::postRemove, 'CompanyContractListener', 'postRemoveHandler'); +$metadata->addEntityListener(Events::preRemove, 'CompanyContractListener', 'preRemoveHandler'); -$metadata->addEntityListener(\Doctrine\ORM\Events::preFlush, 'CompanyContractListener', 'preFlushHandler'); -$metadata->addEntityListener(\Doctrine\ORM\Events::postLoad, 'CompanyContractListener', 'postLoadHandler'); +$metadata->addEntityListener(Events::preFlush, 'CompanyContractListener', 'preFlushHandler'); +$metadata->addEntityListener(Events::postLoad, 'CompanyContractListener', 'postLoadHandler'); -$metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CompanyFlexUltraContractListener', 'prePersistHandler1'); -$metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CompanyFlexUltraContractListener', 'prePersistHandler2'); +$metadata->addEntityListener(Events::prePersist, 'CompanyFlexUltraContractListener', 'prePersistHandler1'); +$metadata->addEntityListener(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 index d92bd218b8f..f7656ccd732 100644 --- 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 @@ -1,48 +1,48 @@ setPrimaryTable( - [ - 'name' => 'company_person', - ] + ['name' => 'company_person'] ); $metadata->addNamedNativeQuery( [ - 'name' => 'fetchAllWithResultClass', - 'query' => 'SELECT id, name, discr FROM company_persons ORDER BY name', - 'resultClass' => CompanyPerson::class, + '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', + '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', + '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 index 62459aad000..b7ff3b83491 100644 --- 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 @@ -1,16 +1,16 @@ mapField( [ - 'id' => true, - 'fieldName' => 'id', + 'id' => true, + 'fieldName' => 'id', ] ); $metadata->mapField( - [ - 'fieldName' => 'name' - ] + ['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 index 85128c9ae4a..6f2cb73b445 100644 --- 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 @@ -1,20 +1,22 @@ setPrimaryTable( [ - 'name' => 'explicit_table', - 'schema' => 'explicit_schema', + 'name' => 'explicit_table', + 'schema' => 'explicit_schema', ] ); $metadata->mapField( [ - 'id' => true, - 'fieldName' => 'id', + 'id' => true, + 'fieldName' => 'id', ] ); 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 index fb2edfcfb26..7b3ccb8295c 100644 --- 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 @@ -1,19 +1,19 @@ setPrimaryTable( - [ - 'name' => 'implicit_schema.implicit_table', - ] + ['name' => 'implicit_schema.implicit_table'] ); $metadata->mapField( [ - 'id' => true, - 'fieldName' => 'id', + 'id' => true, + 'fieldName' => 'id', ] ); 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 index 9b7c87b3e9b..94ed4de9755 100644 --- 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 @@ -1,6 +1,5 @@ setAssociationOverride('groups', [ - 'inversedBy' => 'admins' -] -); +declare(strict_types=1); + +$metadata->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 index d5f22817276..cccc0e494d5 100644 --- 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 @@ -1,34 +1,36 @@ isMappedSuperclass = true; $metadata->mapField( [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - 'columnName' => 'user_id', - 'length' => 150, + '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, + 'fieldName' => 'name', + 'type' => 'string', + 'columnName' => 'user_name', + 'nullable' => true, + 'unique' => false, + 'length' => 250, ] ); $metadata->mapManyToMany( [ - 'fieldName' => 'groups', - 'targetEntity' => 'DDC3579Group' + 'fieldName' => 'groups', + 'targetEntity' => 'DDC3579Group', ] ); 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 index fca4bb1185e..3680a69a4a5 100644 --- 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 @@ -1,12 +1,14 @@ mapField([ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - 'columnName' => 'id', + 'id' => true, + 'fieldName' => 'id', + 'type' => 'integer', + 'columnName' => 'id', ]); $metadata->mapManyToMany([ 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 index 3ecf178a63c..e46a32f26f1 100644 --- 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 @@ -1,5 +1,7 @@ setAssociationOverride('members', [ 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 index e97e16f9596..c7e5cae4ae4 100644 --- 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 @@ -1,7 +1,10 @@ mapField( [ - 'fieldName' => 'serialNumber', - 'type' => 'string', + '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 index de9d8dae0ee..a9698997d59 100644 --- 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 @@ -1,7 +1,10 @@ mapField( [ - 'fieldName' => 'creditCardNumber', - 'type' => 'string', + '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 index 1f3f12b2d5f..803dcbc4cd6 100644 --- 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 @@ -1,20 +1,22 @@ mapField( [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - 'columnName' => 'id', + 'id' => true, + 'fieldName' => 'id', + 'type' => 'integer', + 'columnName' => 'id', ] ); $metadata->mapField( [ - 'fieldName' => 'value', - 'type' => 'float', + 'fieldName' => 'value', + 'type' => 'float', ] ); $metadata->isMappedSuperclass = true; 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 index e1161da1360..0e0099321c3 100644 --- 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 @@ -1,13 +1,13 @@ mapField( [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - 'columnName' => 'id', + 'id' => true, + 'fieldName' => 'id', + 'type' => 'integer', + 'columnName' => 'id', ] ); 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 index 4ab21f9ce3a..174d7fd709f 100644 --- 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 @@ -1,3 +1,3 @@ mapField( [ - 'fieldName' => 'name', - 'type' => 'string', + 'fieldName' => 'name', + 'type' => 'string', ] ); $metadata->isMappedSuperclass = true; 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 index 10175feca96..b76d5222907 100644 --- 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 @@ -1,29 +1,31 @@ setAssociationOverride('address', - [ - 'joinColumns'=> [ - [ - 'name' => 'adminaddress_id', - 'referencedColumnName' => 'id', - ] - ] - ] -); +declare(strict_types=1); -$metadata->setAssociationOverride('groups', +$metadata->setAssociationOverride( + 'address', [ - 'joinTable' => [ - 'name' => 'ddc964_users_admingroups', 'joinColumns' => [ [ - 'name' => 'adminuser_id', - ] + 'name' => 'adminaddress_id', + 'referencedColumnName' => 'id', + ], ], - - 'inverseJoinColumns' => [[ - 'name' => 'admingroup_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 index 28f6f48c592..af20773f8ca 100644 --- 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 @@ -1,16 +1,19 @@ setAttributeOverride('id', [ 'columnName' => 'guest_id', 'type' => 'integer', 'length' => 140, -] -); +]); -$metadata->setAttributeOverride('name', +$metadata->setAttributeOverride( + 'name', [ - 'columnName' => 'guest_name', - 'nullable' => false, - 'unique' => true, - 'length' => 240, + '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 index 6e6172bfafb..736ff5b569d 100644 --- 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 @@ -1,59 +1,61 @@ isMappedSuperclass = true; $metadata->mapField( [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - 'columnName' => 'user_id', - 'length' => 150, + '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, + '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'], + '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', - ] + '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', + ], + ], ], - 'inverseJoinColumns'=> [ - [ - 'name'=>'group_id', - 'referencedColumnName'=>'id', - ] - ] - ] ] ); 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 index 5000a68a229..c40b9b42aef 100644 --- 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 @@ -1,38 +1,40 @@ setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_SINGLE_TABLE); $metadata->setDiscriminatorColumn( [ - 'name' => 'dtype', - 'type' => 'string', - 'length' => 255, - 'fieldName' => 'dtype', + 'name' => 'dtype', + 'type' => 'string', + 'length' => 255, + 'fieldName' => 'dtype', ] ); $metadata->setDiscriminatorMap( [ - 'cat' => Cat::class, - 'dog' => Dog::class, + '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', + '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"]); +$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 index a33ebbaeb37..4c3f733427a 100644 --- 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 @@ -1,25 +1,27 @@ setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_NONE); $metadata->setPrimaryTable( [ - 'indexes' => [ - ['columns' => ['content'], 'flags' => ['fulltext'], 'options'=> ['where' => 'content IS NOT NULL']] - ] + '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', + '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 index dd442ceb0e4..397c4c85f00 100644 --- 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 @@ -1,19 +1,21 @@ mapField( [ - 'id' => true, - 'fieldName' => 'id', - 'columnDefinition' => 'INT unsigned NOT NULL', + 'id' => true, + 'fieldName' => 'id', + 'columnDefinition' => 'INT unsigned NOT NULL', ] ); $metadata->mapField( [ - 'fieldName' => 'value', - 'columnDefinition' => 'VARCHAR(255) NOT NULL' + 'fieldName' => 'value', + 'columnDefinition' => 'VARCHAR(255) NOT NULL', ] ); 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 index c9d8ad9f29d..ff2786400c8 100644 --- 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 @@ -1,18 +1,20 @@ mapField( [ - 'id' => true, - 'fieldName' => 'id', + 'id' => true, + 'fieldName' => 'id', ] ); $metadata->setDiscriminatorColumn( [ - 'name' => "dtype", - 'columnDefinition' => "ENUM('ONE','TWO')" + 'name' => 'dtype', + 'columnDefinition' => "ENUM('ONE','TWO')", ] ); 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 index ad1ed23bfc7..a19b2da1b2c 100644 --- 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 @@ -1,16 +1,18 @@ enableCache( [ - 'usage' => ClassMetadataInfo::CACHE_USAGE_READ_ONLY + 'usage' => ClassMetadataInfo::CACHE_USAGE_READ_ONLY, ] ); $metadata->mapManyToOne( [ - 'fieldName' => 'foo', - 'id' => true, - 'targetEntity' => 'PHPSLCFoo' + '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 index b716893b6fb..2d89ffed367 100644 --- 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 @@ -1,5 +1,7 @@ setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_NONE); $metadata->setPrimaryTable( - [ - 'name' => 'cms_users', - ] + ['name' => 'cms_users'] ); $metadata->setChangeTrackingPolicy(ClassMetadataInfo::CHANGETRACKING_DEFERRED_IMPLICIT); $metadata->addLifecycleCallback('doStuffOnPrePersist', 'prePersist'); @@ -17,36 +17,36 @@ $metadata->addLifecycleCallback('doStuffOnPostPersist', 'postPersist'); $metadata->addNamedQuery( [ - 'name' => 'all', - 'query' => 'SELECT u FROM __CLASS__ u' + 'name' => 'all', + 'query' => 'SELECT u FROM __CLASS__ u', ] ); $metadata->mapField( [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - 'columnName' => 'id', - 'options' => ['foo' => 'bar', 'unsigned' => false], + '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], + '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', + 'fieldName' => 'email', + 'type' => 'string', + 'columnName' => 'user_email', + 'columnDefinition' => 'CHAR(32) NOT NULL', ] ); $mapping = ['fieldName' => 'version', 'type' => 'integer']; @@ -55,90 +55,85 @@ $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, + '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', - ], + '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, + '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'] = [ +$metadata->table['options'] = [ 'foo' => 'bar', - 'baz' => ['key' => 'val'] + '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->table['indexes'] = [ + 'name_idx' => ['columns' => ['name']], + 0 => ['columns' => ['user_email']], ]; $metadata->setSequenceGeneratorDefinition( [ diff --git a/tests/Doctrine/Tests/ORM/ORMInvalidArgumentExceptionTest.php b/tests/Doctrine/Tests/ORM/ORMInvalidArgumentExceptionTest.php index 85b5b3795d9..3a99c78fe36 100644 --- a/tests/Doctrine/Tests/ORM/ORMInvalidArgumentExceptionTest.php +++ b/tests/Doctrine/Tests/ORM/ORMInvalidArgumentExceptionTest.php @@ -1,41 +1,27 @@ getMessage()); } - public function newEntitiesFoundThroughRelationshipsErrorMessages() : array + public function newEntitiesFoundThroughRelationshipsErrorMessages(): array { $stringEntity3 = uniqid('entity3', true); - $entity1 = new \stdClass(); - $entity2 = new \stdClass(); - $entity3 = $this->getMockBuilder(\stdClass::class)->setMethods(['__toString'])->getMock(); + $entity1 = new stdClass(); + $entity2 = new stdClass(); + $entity3 = $this->getMockBuilder(stdClass::class)->setMethods(['__toString'])->getMock(); $association1 = [ 'sourceEntity' => 'foo1', 'fieldName' => 'bar1', @@ -130,7 +116,7 @@ public function newEntitiesFoundThroughRelationshipsErrorMessages() : array . '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"}). If you cannot find out which entity causes the problem ' - . 'implement \'baz2#__toString()\' to get a clue.' + . 'implement \'baz2#__toString()\' to get a clue.', ], 'two entities found, one is stringable' => [ [ diff --git a/tests/Doctrine/Tests/ORM/Performance/SecondLevelCacheTest.php b/tests/Doctrine/Tests/ORM/Performance/SecondLevelCacheTest.php index 568bd56b8d2..8ace5f185b6 100644 --- a/tests/Doctrine/Tests/ORM/Performance/SecondLevelCacheTest.php +++ b/tests/Doctrine/Tests/ORM/Performance/SecondLevelCacheTest.php @@ -1,13 +1,23 @@ _getEntityManager(); @@ -35,16 +42,12 @@ public function createEntityManager() return $em; } - /** - * @param \Doctrine\ORM\EntityManagerInterface $em - * @return integer - */ - public function countQuery(EntityManagerInterface $em) + public function countQuery(EntityManagerInterface $em): int { return count($em->getConfiguration()->getSQLLogger()->queries); } - public function testFindEntityWithoutCache() + public function testFindEntityWithoutCache(): void { $em = $this->createEntityManager(); @@ -53,7 +56,7 @@ public function testFindEntityWithoutCache() $this->assertEquals(6002, $this->countQuery($em)); } - public function testFindEntityWithCache() + public function testFindEntityWithCache(): void { parent::enableSecondLevelCache(false); @@ -64,7 +67,7 @@ public function testFindEntityWithCache() $this->assertEquals(502, $this->countQuery($em)); } - public function testFindAllEntityWithoutCache() + public function testFindAllEntityWithoutCache(): void { $em = $this->createEntityManager(); @@ -73,7 +76,7 @@ public function testFindAllEntityWithoutCache() $this->assertEquals(153, $this->countQuery($em)); } - public function testFindAllEntityWithCache() + public function testFindAllEntityWithCache(): void { parent::enableSecondLevelCache(false); @@ -84,7 +87,7 @@ public function testFindAllEntityWithCache() $this->assertEquals(53, $this->countQuery($em)); } - public function testFindEntityOneToManyWithoutCache() + public function testFindEntityOneToManyWithoutCache(): void { $em = $this->createEntityManager(); @@ -93,7 +96,7 @@ public function testFindEntityOneToManyWithoutCache() $this->assertEquals(502, $this->countQuery($em)); } - public function testFindEntityOneToManyWithCache() + public function testFindEntityOneToManyWithCache(): void { parent::enableSecondLevelCache(false); @@ -104,7 +107,7 @@ public function testFindEntityOneToManyWithCache() $this->assertEquals(472, $this->countQuery($em)); } - public function testQueryEntityWithoutCache() + public function testQueryEntityWithoutCache(): void { $em = $this->createEntityManager(); @@ -113,7 +116,7 @@ public function testQueryEntityWithoutCache() $this->assertEquals(602, $this->countQuery($em)); } - public function testQueryEntityWithCache() + public function testQueryEntityWithCache(): void { parent::enableSecondLevelCache(false); @@ -124,7 +127,7 @@ public function testQueryEntityWithCache() $this->assertEquals(503, $this->countQuery($em)); } - private function queryEntity(EntityManagerInterface $em, $label) + private function queryEntity(EntityManagerInterface $em, $label): void { $times = 100; $size = 500; @@ -141,12 +144,12 @@ private function queryEntity(EntityManagerInterface $em, $label) printf("\n[%s] persist %s countries", number_format(microtime(true) - $startPersist, 6), $size); - $dql = 'SELECT c FROM Doctrine\Tests\Models\Cache\Country c WHERE c.name LIKE :name'; - $startFind = microtime(true); + $dql = 'SELECT c FROM Doctrine\Tests\Models\Cache\Country c WHERE c.name LIKE :name'; + $startFind = microtime(true); for ($i = 0; $i < $times; $i++) { $em->createQuery($dql) - ->setParameter('name', "%Country%") + ->setParameter('name', '%Country%') ->setCacheable(true) ->getResult(); } @@ -155,14 +158,14 @@ private function queryEntity(EntityManagerInterface $em, $label) printf("\n%s\n", str_repeat('-', 50)); } - public function findEntityOneToMany(EntityManagerInterface $em, $label) + public function findEntityOneToMany(EntityManagerInterface $em, $label): void { $times = 50; $size = 30; $states = []; $cities = []; $startPersist = microtime(true); - $country = new Country("Country"); + $country = new Country('Country'); echo PHP_EOL . $label; @@ -194,14 +197,12 @@ public function findEntityOneToMany(EntityManagerInterface $em, $label) $em->flush(); $em->clear(); - printf("\n[%s] persist %s states and %s cities", number_format( microtime(true) - $startPersist, 6), count($states), count($cities)); + printf("\n[%s] persist %s states and %s cities", number_format(microtime(true) - $startPersist, 6), count($states), count($cities)); - $startFind = microtime(true); + $startFind = microtime(true); for ($i = 0; $i < $times; $i++) { - foreach ($states as $state) { - $state = $em->find(State::class, $state->getId()); foreach ($state->getCities() as $city) { @@ -214,7 +215,7 @@ public function findEntityOneToMany(EntityManagerInterface $em, $label) printf("\n%s\n", str_repeat('-', 50)); } - private function findEntity(EntityManagerInterface $em, $label) + private function findEntity(EntityManagerInterface $em, $label): void { $times = 10; $size = 500; @@ -236,7 +237,7 @@ private function findEntity(EntityManagerInterface $em, $label) printf("\n[%s] persist %s countries", number_format(microtime(true) - $startPersist, 6), $size); - $startFind = microtime(true); + $startFind = microtime(true); for ($i = 0; $i <= $times; $i++) { foreach ($countries as $country) { @@ -249,7 +250,7 @@ private function findEntity(EntityManagerInterface $em, $label) printf("\n%s\n", str_repeat('-', 50)); } - private function findAllEntity(EntityManagerInterface $em, $label) + private function findAllEntity(EntityManagerInterface $em, $label): void { $times = 100; $size = 50; @@ -267,7 +268,7 @@ private function findAllEntity(EntityManagerInterface $em, $label) printf("\n[%s] persist %s countries", number_format(microtime(true) - $startPersist, 6), $size); - $startFind = microtime(true); + $startFind = microtime(true); for ($i = 0; $i <= $times; $i++) { $list = $rep->findAll(); diff --git a/tests/Doctrine/Tests/ORM/PersistentCollectionTest.php b/tests/Doctrine/Tests/ORM/PersistentCollectionTest.php index b8a1523cb04..642e7b96fc7 100644 --- a/tests/Doctrine/Tests/ORM/PersistentCollectionTest.php +++ b/tests/Doctrine/Tests/ORM/PersistentCollectionTest.php @@ -1,9 +1,10 @@ - * @author Austin Morris */ class PersistentCollectionTest extends OrmTestCase { - /** - * @var PersistentCollection - */ + /** @var PersistentCollection */ protected $collection; - /** - * @var EntityManagerMock - */ + /** @var EntityManagerMock */ private $_emMock; - protected function setUp() : void + protected function setUp(): void { parent::setUp(); @@ -42,18 +42,18 @@ protected function setUp() : void /** * Set up the PersistentCollection used for collection initialization tests. */ - public function setUpPersistentCollection() + public function setUpPersistentCollection(): void { - $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')); } - public function testCanBePutInLazyLoadingMode() + public function testCanBePutInLazyLoadingMode(): void { - $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()); } @@ -61,7 +61,7 @@ public function testCanBePutInLazyLoadingMode() /** * Test that PersistentCollection::current() initializes the collection. */ - public function testCurrentInitializesCollection() + public function testCurrentInitializesCollection(): void { $this->collection->current(); $this->assertTrue($this->collection->isInitialized()); @@ -70,7 +70,7 @@ public function testCurrentInitializesCollection() /** * Test that PersistentCollection::key() initializes the collection. */ - public function testKeyInitializesCollection() + public function testKeyInitializesCollection(): void { $this->collection->key(); $this->assertTrue($this->collection->isInitialized()); @@ -79,7 +79,7 @@ public function testKeyInitializesCollection() /** * Test that PersistentCollection::next() initializes the collection. */ - public function testNextInitializesCollection() + public function testNextInitializesCollection(): void { $this->collection->next(); $this->assertTrue($this->collection->isInitialized()); @@ -88,31 +88,31 @@ public function testNextInitializesCollection() /** * @group DDC-3382 */ - public function testNonObjects() + public function testNonObjects(): void { $this->assertEmpty($this->collection); - $this->collection->add("dummy"); + $this->collection->add('dummy'); $this->assertNotEmpty($this->collection); $product = new ECommerceProduct(); $this->collection->set(1, $product); - $this->collection->set(2, "dummy"); + $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('dummy', $this->collection->get(2)); $this->assertSame(null, $this->collection->get(3)); } /** * @group 6110 */ - public function testRemovingElementsAlsoRemovesKeys() + public function testRemovingElementsAlsoRemovesKeys(): void { - $dummy = new \stdClass(); + $dummy = new stdClass(); $this->collection->add($dummy); $this->assertEquals([0], array_keys($this->collection->toArray())); @@ -124,9 +124,9 @@ public function testRemovingElementsAlsoRemovesKeys() /** * @group 6110 */ - public function testClearWillAlsoClearKeys() + public function testClearWillAlsoClearKeys(): void { - $this->collection->add(new \stdClass()); + $this->collection->add(new stdClass()); $this->collection->clear(); $this->assertEquals([], array_keys($this->collection->toArray())); } @@ -134,9 +134,9 @@ public function testClearWillAlsoClearKeys() /** * @group 6110 */ - public function testClearWillAlsoResetKeyPositions() + public function testClearWillAlsoResetKeyPositions(): void { - $dummy = new \stdClass(); + $dummy = new stdClass(); $this->collection->add($dummy); $this->collection->removeElement($dummy); @@ -150,15 +150,15 @@ public function testClearWillAlsoResetKeyPositions() * @group 6614 * @group 6616 */ - public function testWillKeepNewItemsInDirtyCollectionAfterInitialization() : void + public function testWillKeepNewItemsInDirtyCollectionAfterInitialization(): void { - /* @var $unitOfWork UnitOfWork|\PHPUnit_Framework_MockObject_MockObject */ $unitOfWork = $this->createMock(UnitOfWork::class); + assert($unitOfWork instanceof UnitOfWork || $unitOfWork instanceof PHPUnit_Framework_MockObject_MockObject); $this->_emMock->setUnitOfWork($unitOfWork); - $newElement = new \stdClass(); - $persistedElement = new \stdClass(); + $newElement = new stdClass(); + $persistedElement = new stdClass(); $this->collection->add($newElement); @@ -169,7 +169,7 @@ public function testWillKeepNewItemsInDirtyCollectionAfterInitialization() : voi ->expects(self::once()) ->method('loadCollection') ->with($this->collection) - ->willReturnCallback(function (PersistentCollection $persistentCollection) use ($persistedElement) : void { + ->willReturnCallback(static function (PersistentCollection $persistentCollection) use ($persistedElement): void { $persistentCollection->unwrap()->add($persistedElement); }); @@ -185,16 +185,16 @@ public function testWillKeepNewItemsInDirtyCollectionAfterInitialization() : voi * @group 6614 * @group 6616 */ - public function testWillDeDuplicateNewItemsThatWerePreviouslyPersistedInDirtyCollectionAfterInitialization() : void + public function testWillDeDuplicateNewItemsThatWerePreviouslyPersistedInDirtyCollectionAfterInitialization(): void { - /* @var $unitOfWork UnitOfWork|\PHPUnit_Framework_MockObject_MockObject */ $unitOfWork = $this->createMock(UnitOfWork::class); + assert($unitOfWork instanceof UnitOfWork || $unitOfWork instanceof PHPUnit_Framework_MockObject_MockObject); $this->_emMock->setUnitOfWork($unitOfWork); - $newElement = new \stdClass(); - $newElementThatIsAlsoPersisted = new \stdClass(); - $persistedElement = new \stdClass(); + $newElement = new stdClass(); + $newElementThatIsAlsoPersisted = new stdClass(); + $persistedElement = new stdClass(); $this->collection->add($newElementThatIsAlsoPersisted); $this->collection->add($newElement); @@ -206,10 +206,10 @@ public function testWillDeDuplicateNewItemsThatWerePreviouslyPersistedInDirtyCol ->expects(self::once()) ->method('loadCollection') ->with($this->collection) - ->willReturnCallback(function (PersistentCollection $persistentCollection) use ( + ->willReturnCallback(static function (PersistentCollection $persistentCollection) use ( $persistedElement, $newElementThatIsAlsoPersisted - ) : void { + ): void { $persistentCollection->unwrap()->add($newElementThatIsAlsoPersisted); $persistentCollection->unwrap()->add($persistedElement); }); @@ -229,15 +229,15 @@ public function testWillDeDuplicateNewItemsThatWerePreviouslyPersistedInDirtyCol * @group 6614 * @group 6616 */ - public function testWillNotMarkCollectionAsDirtyAfterInitializationIfNoElementsWereAdded() : void + public function testWillNotMarkCollectionAsDirtyAfterInitializationIfNoElementsWereAdded(): void { - /* @var $unitOfWork UnitOfWork|\PHPUnit_Framework_MockObject_MockObject */ $unitOfWork = $this->createMock(UnitOfWork::class); + assert($unitOfWork instanceof UnitOfWork || $unitOfWork instanceof PHPUnit_Framework_MockObject_MockObject); $this->_emMock->setUnitOfWork($unitOfWork); - $newElementThatIsAlsoPersisted = new \stdClass(); - $persistedElement = new \stdClass(); + $newElementThatIsAlsoPersisted = new stdClass(); + $persistedElement = new stdClass(); $this->collection->add($newElementThatIsAlsoPersisted); @@ -248,10 +248,10 @@ public function testWillNotMarkCollectionAsDirtyAfterInitializationIfNoElementsW ->expects(self::once()) ->method('loadCollection') ->with($this->collection) - ->willReturnCallback(function (PersistentCollection $persistentCollection) use ( + ->willReturnCallback(static function (PersistentCollection $persistentCollection) use ( $persistedElement, $newElementThatIsAlsoPersisted - ) : void { + ): void { $persistentCollection->unwrap()->add($newElementThatIsAlsoPersisted); $persistentCollection->unwrap()->add($persistedElement); }); @@ -266,7 +266,7 @@ public function testWillNotMarkCollectionAsDirtyAfterInitializationIfNoElementsW self::assertFalse($this->collection->isDirty()); } - public function testModifyUOWForDeferredImplicitOwnerOnClear() : void + public function testModifyUOWForDeferredImplicitOwnerOnClear(): void { $unitOfWork = $this->createMock(UnitOfWork::class); $unitOfWork->expects(self::once())->method('scheduleCollectionDeletion'); diff --git a/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterCompositeTypeParametersTest.php b/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterCompositeTypeParametersTest.php index e427318ad8d..f515f216efa 100644 --- a/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterCompositeTypeParametersTest.php +++ b/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterCompositeTypeParametersTest.php @@ -1,8 +1,11 @@ _em->getClassMetadata(Admin1AlternateName::class); $this->_persister = new BasicEntityPersister($this->_em, $this->_em->getClassMetadata(Admin1AlternateName::class)); - } - public function testExpandParametersWillExpandCompositeEntityKeys() + public function testExpandParametersWillExpandCompositeEntityKeys(): void { - $country = new Country("IT", "Italy"); - $admin1 = new Admin1(10, "Rome", $country); + $country = new Country('IT', 'Italy'); + $admin1 = new Admin1(10, 'Rome', $country); [$values, $types] = $this->_persister->expandParameters(['admin1' => $admin1]); @@ -49,13 +44,13 @@ public function testExpandParametersWillExpandCompositeEntityKeys() $this->assertEquals([10, 'IT'], $values); } - public function testExpandCriteriaParametersWillExpandCompositeEntityKeys() + public function testExpandCriteriaParametersWillExpandCompositeEntityKeys(): void { - $country = new Country("IT", "Italy"); - $admin1 = new Admin1(10, "Rome", $country); + $country = new Country('IT', 'Italy'); + $admin1 = new Admin1(10, 'Rome', $country); $criteria = Criteria::create(); - $criteria->andWhere(Criteria::expr()->eq("admin1", $admin1)); + $criteria->andWhere(Criteria::expr()->eq('admin1', $admin1)); [$values, $types] = $this->_persister->expandCriteriaParameters($criteria); diff --git a/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterCompositeTypeSqlTest.php b/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterCompositeTypeSqlTest.php index 2d7592d1c4b..5268ba72953 100644 --- a/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterCompositeTypeSqlTest.php +++ b/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterCompositeTypeSqlTest.php @@ -1,54 +1,50 @@ _em = $this->_getTestEntityManager(); + $this->_em = $this->_getTestEntityManager(); $this->_persister = new BasicEntityPersister($this->_em, $this->_em->getClassMetadata(Admin1AlternateName::class)); } - public function testSelectConditionStatementEq() + public function testSelectConditionStatementEq(): void { $statement = $this->_persister->getSelectConditionStatementSQL('admin1', 1, [], Comparison::EQ); $this->assertEquals('t0.admin1 = ? AND t0.country = ?', $statement); } - public function testSelectConditionStatementEqNull() + public function testSelectConditionStatementEqNull(): void { $statement = $this->_persister->getSelectConditionStatementSQL('admin1', null, [], Comparison::IS); $this->assertEquals('t0.admin1 IS NULL AND t0.country IS NULL', $statement); } - public function testSelectConditionStatementNeqNull() + public function testSelectConditionStatementNeqNull(): void { $statement = $this->_persister->getSelectConditionStatementSQL('admin1', null, [], Comparison::NEQ); $this->assertEquals('t0.admin1 IS NOT NULL AND t0.country IS NOT NULL', $statement); } - public function testSelectConditionStatementIn() + public function testSelectConditionStatementIn(): void { $this->expectException('Doctrine\ORM\ORMException'); $this->_persister->getSelectConditionStatementSQL('admin1', [], [], Comparison::IN); diff --git a/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterTypeValueSqlTest.php b/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterTypeValueSqlTest.php index d721c25cc41..de96cf7f950 100644 --- a/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterTypeValueSqlTest.php +++ b/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterTypeValueSqlTest.php @@ -1,33 +1,29 @@ _persister = new BasicEntityPersister($this->_em, $this->_em->getClassMetadata(CustomTypeParent::class)); } - public function testGetInsertSQLUsesTypeValuesSQL() + public function testGetInsertSQLUsesTypeValuesSQL(): void { - $method = new \ReflectionMethod($this->_persister, 'getInsertSQL'); + $method = new ReflectionMethod($this->_persister, 'getInsertSQL'); $method->setAccessible(true); $sql = $method->invoke($this->_persister); @@ -58,13 +54,13 @@ public function testGetInsertSQLUsesTypeValuesSQL() $this->assertEquals('INSERT INTO customtype_parents (customInteger, child_id) VALUES (ABS(?), ?)', $sql); } - public function testUpdateUsesTypeValuesSQL() + public function testUpdateUsesTypeValuesSQL(): void { $child = new CustomTypeChild(); - $parent = new CustomTypeParent(); + $parent = new CustomTypeParent(); $parent->customInteger = 1; - $parent->child = $child; + $parent->child = $child; $this->_em->getUnitOfWork()->registerManaged($parent, ['id' => 1], ['customInteger' => 0, 'child' => null]); $this->_em->getUnitOfWork()->registerManaged($child, ['id' => 1], []); @@ -79,12 +75,12 @@ public function testUpdateUsesTypeValuesSQL() $this->assertEquals('UPDATE customtype_parents SET customInteger = ABS(?), child_id = ? WHERE id = ?', $executeUpdates[0]['query']); } - public function testGetSelectConditionSQLUsesTypeValuesSQL() + public function testGetSelectConditionSQLUsesTypeValuesSQL(): void { - $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); } @@ -92,10 +88,10 @@ public function testGetSelectConditionSQLUsesTypeValuesSQL() /** * @group DDC-1719 */ - public function testStripNonAlphanumericCharactersFromSelectColumnListSQL() + public function testStripNonAlphanumericCharactersFromSelectColumnListSQL(): void { - $persister = new BasicEntityPersister($this->_em, $this->_em->getClassMetadata(NonAlphaColumnsEntity::class)); - $method = new \ReflectionMethod($persister, 'getSelectColumnsSQL'); + $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)); @@ -104,19 +100,19 @@ public function testStripNonAlphanumericCharactersFromSelectColumnListSQL() /** * @group DDC-2073 */ - public function testSelectConditionStatementIsNull() + public function testSelectConditionStatementIsNull(): void { $statement = $this->_persister->getSelectConditionStatementSQL('test', null, [], Comparison::IS); $this->assertEquals('test IS NULL', $statement); } - public function testSelectConditionStatementEqNull() + public function testSelectConditionStatementEqNull(): void { $statement = $this->_persister->getSelectConditionStatementSQL('test', null, [], Comparison::EQ); $this->assertEquals('test IS NULL', $statement); } - public function testSelectConditionStatementNeqNull() + public function testSelectConditionStatementNeqNull(): void { $statement = $this->_persister->getSelectConditionStatementSQL('test', null, [], Comparison::NEQ); $this->assertEquals('test IS NOT NULL', $statement); @@ -125,7 +121,7 @@ public function testSelectConditionStatementNeqNull() /** * @group DDC-3056 */ - public function testSelectConditionStatementWithMultipleValuesContainingNull() + public function testSelectConditionStatementWithMultipleValuesContainingNull(): void { $this->assertEquals( '(t0.id IN (?) OR t0.id IS NULL)', @@ -143,7 +139,7 @@ public function testSelectConditionStatementWithMultipleValuesContainingNull() ); } - public function testCountCondition() + public function testCountCondition(): void { $persister = new BasicEntityPersister($this->_em, $this->_em->getClassMetadata(NonAlphaColumnsEntity::class)); @@ -152,12 +148,12 @@ public function testCountCondition() $this->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')); + $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); } - public function testCountEntities() + public function testCountEntities(): void { $this->assertEquals(0, $this->_persister->count()); } diff --git a/tests/Doctrine/Tests/ORM/Persisters/JoinedSubclassPersisterTest.php b/tests/Doctrine/Tests/ORM/Persisters/JoinedSubclassPersisterTest.php index a4a43cdd3c2..604e3e2d3af 100644 --- a/tests/Doctrine/Tests/ORM/Persisters/JoinedSubclassPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Persisters/JoinedSubclassPersisterTest.php @@ -1,7 +1,10 @@ em = $this->_getTestEntityManager(); + $this->em = $this->_getTestEntityManager(); $this->persister = new JoinedSubclassPersister($this->em, $this->em->getClassMetadata(RootClass::class)); } /** * @group DDC-3470 */ - public function testExecuteInsertsWillReturnEmptySetWithNoQueuedInserts() + public function testExecuteInsertsWillReturnEmptySetWithNoQueuedInserts(): void { $this->assertSame([], $this->persister->executeInserts()); } diff --git a/tests/Doctrine/Tests/ORM/Persisters/ManyToManyPersisterTest.php b/tests/Doctrine/Tests/ORM/Persisters/ManyToManyPersisterTest.php index 843ff239536..18dcdd9a34e 100644 --- a/tests/Doctrine/Tests/ORM/Persisters/ManyToManyPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Persisters/ManyToManyPersisterTest.php @@ -1,5 +1,7 @@ persist($parent); $em->flush(); - /** @var ChildClass|null $childReloaded */ $childReloaded = $em->find(ChildClass::class, ['id1' => 1, 'otherParent' => $otherParent]); + assert($childReloaded instanceof ChildClass || $childReloaded === null); self::assertNotNull($childReloaded); $persister = new ManyToManyPersister($em); $persister->delete($childReloaded->parents); - /** @var ConnectionMock $conn */ $conn = $em->getConnection(); + assert($conn instanceof ConnectionMock); $updates = $conn->getExecuteUpdates(); $lastUpdate = array_pop($updates); diff --git a/tests/Doctrine/Tests/ORM/Proxy/ProxyFactoryTest.php b/tests/Doctrine/Tests/ORM/Proxy/ProxyFactoryTest.php index 666edc9a465..a1024fab0e6 100644 --- a/tests/Doctrine/Tests/ORM/Proxy/ProxyFactoryTest.php +++ b/tests/Doctrine/Tests/ORM/Proxy/ProxyFactoryTest.php @@ -1,8 +1,11 @@ */ class ProxyFactoryTest extends OrmTestCase { - /** - * @var ConnectionMock - */ + /** @var ConnectionMock */ private $connectionMock; - /** - * @var UnitOfWorkMock - */ + /** @var UnitOfWorkMock */ private $uowMock; - /** - * @var EntityManagerMock - */ + /** @var EntityManagerMock */ private $emMock; - /** - * @var \Doctrine\ORM\Proxy\ProxyFactory - */ + /** @var ProxyFactory */ private $proxyFactory; - /** - * {@inheritDoc} - */ - protected function setUp() : void + protected function setUp(): void { parent::setUp(); $this->connectionMock = new ConnectionMock([], new DriverMock()); - $this->emMock = EntityManagerMock::create($this->connectionMock); - $this->uowMock = new UnitOfWorkMock($this->emMock); + $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); } - public function testReferenceProxyDelegatesLoadingToThePersister() + public function testReferenceProxyDelegatesLoadingToThePersister(): void { $identifier = ['id' => 42]; $proxyClass = 'Proxies\__CG__\Doctrine\Tests\Models\ECommerce\ECommerceFeature'; @@ -70,14 +66,14 @@ public function testReferenceProxyDelegatesLoadingToThePersister() ->expects($this->atLeastOnce()) ->method('load') ->with($this->equalTo($identifier), $this->isInstanceOf($proxyClass)) - ->will($this->returnValue(new \stdClass())); + ->will($this->returnValue(new stdClass())); $proxy->getDescription(); } public function testSkipMappedSuperClassesOnGeneration(): void { - $cm = new ClassMetadata(\stdClass::class); + $cm = new ClassMetadata(stdClass::class); $cm->isMappedSuperclass = true; self::assertSame( @@ -92,7 +88,7 @@ public function testSkipMappedSuperClassesOnGeneration(): void */ public function testSkipEmbeddableClassesOnGeneration(): void { - $cm = new ClassMetadata(\stdClass::class); + $cm = new ClassMetadata(stdClass::class); $cm->isEmbeddedClass = true; self::assertSame( @@ -105,7 +101,7 @@ public function testSkipEmbeddableClassesOnGeneration(): void /** * @group DDC-1771 */ - public function testSkipAbstractClassesOnGeneration() + public function testSkipAbstractClassesOnGeneration(): void { $cm = new ClassMetadata(AbstractClass::class); $cm->initializeReflection(new RuntimeReflectionService()); @@ -113,19 +109,19 @@ public function testSkipAbstractClassesOnGeneration() $num = $this->proxyFactory->generateProxyClasses([$cm]); - $this->assertEquals(0, $num, "No proxies generated."); + $this->assertEquals(0, $num, 'No proxies generated.'); } /** * @group DDC-2432 */ - public function testFailedProxyLoadingDoesNotMarkTheProxyAsInitialized() + public function testFailedProxyLoadingDoesNotMarkTheProxyAsInitialized(): void { $persister = $this->getMockBuilder(BasicEntityPersister::class)->setMethods(['load'])->disableOriginalConstructor()->getMock(); $this->uowMock->setEntityPersister(ECommerceFeature::class, $persister); - /* @var $proxy \Doctrine\Common\Proxy\Proxy */ $proxy = $this->proxyFactory->getProxy(ECommerceFeature::class, ['id' => 42]); + assert($proxy instanceof Proxy); $persister ->expects($this->atLeastOnce()) @@ -146,13 +142,13 @@ public function testFailedProxyLoadingDoesNotMarkTheProxyAsInitialized() /** * @group DDC-2432 */ - public function testFailedProxyCloningDoesNotMarkTheProxyAsInitialized() + public function testFailedProxyCloningDoesNotMarkTheProxyAsInitialized(): void { $persister = $this->getMockBuilder(BasicEntityPersister::class)->setMethods(['load'])->disableOriginalConstructor()->getMock(); $this->uowMock->setEntityPersister(ECommerceFeature::class, $persister); - /* @var $proxy \Doctrine\Common\Proxy\Proxy */ $proxy = $this->proxyFactory->getProxy(ECommerceFeature::class, ['id' => 42]); + assert($proxy instanceof Proxy); $persister ->expects($this->atLeastOnce()) @@ -170,14 +166,14 @@ public function testFailedProxyCloningDoesNotMarkTheProxyAsInitialized() $this->assertInstanceOf('Closure', $proxy->__getCloner(), 'The cloner wasn\'t removed'); } - public function testProxyClonesParentFields() + public function testProxyClonesParentFields(): void { $companyEmployee = new CompanyEmployee(); $companyEmployee->setSalary(1000); // A property on the CompanyEmployee $companyEmployee->setName('Bob'); // A property on the parent class, CompanyPerson // Set the id of the CompanyEmployee (which is in the parent CompanyPerson) - $property = new \ReflectionProperty(CompanyPerson::class, 'id'); + $property = new ReflectionProperty(CompanyPerson::class, 'id'); $property->setAccessible(true); $property->setValue($companyEmployee, 42); @@ -191,8 +187,8 @@ public function testProxyClonesParentFields() ->getMock(); $this->uowMock->setEntityPersister(CompanyEmployee::class, $persister); - /* @var $proxy \Doctrine\Common\Proxy\Proxy */ $proxy = $this->proxyFactory->getProxy(CompanyEmployee::class, ['id' => 42]); + assert($proxy instanceof Proxy); $persister ->expects(self::atLeastOnce()) @@ -204,8 +200,8 @@ public function testProxyClonesParentFields() ->method('getClassMetadata') ->willReturn($classMetaData); - /* @var $cloned CompanyEmployee */ $cloned = clone $proxy; + assert($cloned instanceof CompanyEmployee); self::assertSame(42, $cloned->getId(), 'Expected the Id to be cloned'); self::assertSame(1000, $cloned->getSalary(), 'Expect properties on the CompanyEmployee class to be cloned'); @@ -215,5 +211,4 @@ public function testProxyClonesParentFields() abstract class AbstractClass { - } diff --git a/tests/Doctrine/Tests/ORM/Query/CustomTreeWalkersJoinTest.php b/tests/Doctrine/Tests/ORM/Query/CustomTreeWalkersJoinTest.php index b36e713b1c9..28f057f72f7 100644 --- a/tests/Doctrine/Tests/ORM/Query/CustomTreeWalkersJoinTest.php +++ b/tests/Doctrine/Tests/ORM/Query/CustomTreeWalkersJoinTest.php @@ -1,29 +1,30 @@ - * @license MIT * @link http://www.doctrine-project.org */ class CustomTreeWalkersJoinTest extends OrmTestCase { private $em; - protected function setUp() : void + protected function setUp(): void { $this->em = $this->_getTestEntityManager(); } - public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed) + public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed): void { try { $query = $this->em->createQuery($dqlToBeTested); @@ -32,32 +33,31 @@ public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed) $this->assertEquals($sqlToBeConfirmed, $query->getSql()); $query->free(); - } catch (\Exception $e) { + } catch (Exception $e) { $this->fail($e->getMessage() . ' at "' . $e->getFile() . '" on line ' . $e->getLine()); - } } - public function testAddsJoin() + public function testAddsJoin(): void { $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" + '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' ); } - public function testDoesNotAddJoin() + public function testDoesNotAddJoin(): void { $this->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 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_' ); } } class CustomTreeWalkerJoin extends Query\TreeWalkerAdapter { - public function walkSelectStatement(Query\AST\SelectStatement $selectStatement) + public function walkSelectStatement(Query\AST\SelectStatement $selectStatement): void { foreach ($selectStatement->fromClause->identificationVariableDeclarations as $identificationVariableDeclaration) { $rangeVariableDecl = $identificationVariableDeclaration->rangeVariableDeclaration; @@ -70,7 +70,7 @@ public function walkSelectStatement(Query\AST\SelectStatement $selectStatement) } } - private function modifySelectStatement(Query\AST\SelectStatement $selectStatement, $identificationVariableDecl) + private function modifySelectStatement(Query\AST\SelectStatement $selectStatement, $identificationVariableDecl): void { $rangeVariableDecl = $identificationVariableDecl->rangeVariableDeclaration; $joinAssocPathExpression = new Query\AST\JoinAssociationPathExpression($rangeVariableDecl->aliasIdentificationVariable, 'address'); @@ -85,7 +85,8 @@ private function modifySelectStatement(Query\AST\SelectStatement $selectStatemen $userMetadata = $entityManager->getClassMetadata(CmsUser::class); $addressMetadata = $entityManager->getClassMetadata(CmsAddress::class); - $this->setQueryComponent($rangeVariableDecl->aliasIdentificationVariable . 'a', + $this->setQueryComponent( + $rangeVariableDecl->aliasIdentificationVariable . 'a', [ 'metadata' => $addressMetadata, 'parent' => $rangeVariableDecl->aliasIdentificationVariable, diff --git a/tests/Doctrine/Tests/ORM/Query/CustomTreeWalkersTest.php b/tests/Doctrine/Tests/ORM/Query/CustomTreeWalkersTest.php index 4b8d525bad6..41fb9b88c2a 100644 --- a/tests/Doctrine/Tests/ORM/Query/CustomTreeWalkersTest.php +++ b/tests/Doctrine/Tests/ORM/Query/CustomTreeWalkersTest.php @@ -1,5 +1,7 @@ - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link http://www.doctrine-project.org - * @since 2.0 */ class CustomTreeWalkersTest extends OrmTestCase { private $_em; - protected function setUp() : void + protected function setUp(): void { $this->_em = $this->_getTestEntityManager(); } @@ -38,43 +41,43 @@ public function generateSql($dqlToBeTested, $treeWalkers, $outputWalker) return $query->getSql(); } - public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed, $treeWalkers = [], $outputWalker = null) + public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed, $treeWalkers = [], $outputWalker = null): void { try { $this->assertEquals($sqlToBeConfirmed, $this->generateSql($dqlToBeTested, $treeWalkers, $outputWalker)); - } catch (\Exception $e) { + } catch (Exception $e) { $this->fail($e->getMessage() . ' at "' . $e->getFile() . '" on line ' . $e->getLine()); } } - public function testSupportsQueriesWithoutWhere() + public function testSupportsQueriesWithoutWhere(): void { $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 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', [CustomTreeWalker::class] ); } - public function testSupportsQueriesWithMultipleConditionalExpressions() + public function testSupportsQueriesWithMultipleConditionalExpressions(): void { $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 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', [CustomTreeWalker::class] ); } - public function testSupportsQueriesWithSimpleConditionalExpression() + public function testSupportsQueriesWithSimpleConditionalExpression(): void { $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 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', [CustomTreeWalker::class] ); } - public function testSetUnknownQueryComponentThrowsException() + public function testSetUnknownQueryComponentThrowsException(): void { $this->expectException(QueryException::class); $this->expectExceptionMessage("Invalid query component given for DQL alias 'x', requires 'metadata', 'parent', 'relation', 'map', 'nestingLevel' and 'token' keys."); @@ -86,11 +89,11 @@ public function testSetUnknownQueryComponentThrowsException() ); } - public function testSupportsSeveralHintsQueries() + public function testSupportsSeveralHintsQueries(): void { $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 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', [CustomTreeWalkerJoin::class, CustomTreeWalker::class] ); } @@ -98,7 +101,7 @@ public function testSupportsSeveralHintsQueries() class AddUnknownQueryComponentWalker extends Query\SqlWalker { - public function walkSelectStatement(Query\AST\SelectStatement $selectStatement) + public function walkSelectStatement(Query\AST\SelectStatement $selectStatement): void { parent::walkSelectStatement($selectStatement); @@ -108,7 +111,7 @@ public function walkSelectStatement(Query\AST\SelectStatement $selectStatement) class CustomTreeWalker extends Query\TreeWalkerAdapter { - public function walkSelectStatement(Query\AST\SelectStatement $selectStatement) + public function walkSelectStatement(Query\AST\SelectStatement $selectStatement): void { // Get the DQL aliases of all the classes we want to modify $dqlAliases = []; @@ -116,7 +119,7 @@ public function walkSelectStatement(Query\AST\SelectStatement $selectStatement) 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']->name === CmsUser::class) { $dqlAliases[] = $dqlAlias; } } @@ -124,14 +127,14 @@ public function walkSelectStatement(Query\AST\SelectStatement $selectStatement) // Create our conditions for all involved classes $factors = []; foreach ($dqlAliases as $alias) { - $pathExpr = new Query\AST\PathExpression(Query\AST\PathExpression::TYPE_STATE_FIELD, $alias, 'id'); + $pathExpr = new Query\AST\PathExpression(Query\AST\PathExpression::TYPE_STATE_FIELD, $alias, 'id'); $pathExpr->type = Query\AST\PathExpression::TYPE_STATE_FIELD; $comparisonExpr = new Query\AST\ComparisonExpression($pathExpr, '=', 1); - $condPrimary = new Query\AST\ConditionalPrimary; + $condPrimary = new Query\AST\ConditionalPrimary(); $condPrimary->simpleConditionalExpression = $comparisonExpr; - $factor = new Query\AST\ConditionalFactor($condPrimary); + $factor = new Query\AST\ConditionalFactor($condPrimary); $factors[] = $factor; } @@ -140,7 +143,7 @@ public function walkSelectStatement(Query\AST\SelectStatement $selectStatement) $condExpr = $whereClause->conditionalExpression; // Since Phase 1 AST optimizations were included, we need to re-add the ConditionalExpression - if ( ! ($condExpr instanceof Query\AST\ConditionalExpression)) { + if (! ($condExpr instanceof Query\AST\ConditionalExpression)) { $condExpr = new Query\AST\ConditionalExpression([$condExpr]); $whereClause->conditionalExpression = $condExpr; @@ -152,10 +155,10 @@ public function walkSelectStatement(Query\AST\SelectStatement $selectStatement) // More than one term, so we need to wrap all these terms in a single root term // i.e: "WHERE u.name = :foo or u.other = :bar" => "WHERE (u.name = :foo or u.other = :bar) AND " - $primary = new Query\AST\ConditionalPrimary; + $primary = new Query\AST\ConditionalPrimary(); $primary->conditionalExpression = new Query\AST\ConditionalExpression($existingTerms); - $existingFactor = new Query\AST\ConditionalFactor($primary); - $term = new Query\AST\ConditionalTerm(array_merge([$existingFactor], $factors)); + $existingFactor = new Query\AST\ConditionalFactor($primary); + $term = new Query\AST\ConditionalTerm(array_merge([$existingFactor], $factors)); $selectStatement->whereClause->conditionalExpression->conditionalTerms = [$term]; } else { @@ -163,20 +166,20 @@ public function walkSelectStatement(Query\AST\SelectStatement $selectStatement) $singleTerm = $selectStatement->whereClause->conditionalExpression->conditionalTerms[0]; // Since Phase 1 AST optimizations were included, we need to re-add the ConditionalExpression - if ( ! ($singleTerm instanceof Query\AST\ConditionalTerm)) { + if (! ($singleTerm instanceof Query\AST\ConditionalTerm)) { $singleTerm = new Query\AST\ConditionalTerm([$singleTerm]); $selectStatement->whereClause->conditionalExpression->conditionalTerms[0] = $singleTerm; } - $singleTerm->conditionalFactors = array_merge($singleTerm->conditionalFactors, $factors); + $singleTerm->conditionalFactors = array_merge($singleTerm->conditionalFactors, $factors); $selectStatement->whereClause->conditionalExpression->conditionalTerms = [$singleTerm]; } } else { // Create a new WHERE clause with our factors - $term = new Query\AST\ConditionalTerm($factors); - $condExpr = new Query\AST\ConditionalExpression([$term]); - $whereClause = new Query\AST\WhereClause($condExpr); + $term = new Query\AST\ConditionalTerm($factors); + $condExpr = new Query\AST\ConditionalExpression([$term]); + $whereClause = new Query\AST\WhereClause($condExpr); $selectStatement->whereClause = $whereClause; } } @@ -184,7 +187,7 @@ public function walkSelectStatement(Query\AST\SelectStatement $selectStatement) class CustomTreeWalkerJoin extends Query\TreeWalkerAdapter { - public function walkSelectStatement(Query\AST\SelectStatement $selectStatement) + public function walkSelectStatement(Query\AST\SelectStatement $selectStatement): void { foreach ($selectStatement->fromClause->identificationVariableDeclarations as $identificationVariableDeclaration) { $rangeVariableDecl = $identificationVariableDeclaration->rangeVariableDeclaration; @@ -197,7 +200,7 @@ public function walkSelectStatement(Query\AST\SelectStatement $selectStatement) } } - private function modifySelectStatement(Query\AST\SelectStatement $selectStatement, $identificationVariableDecl) + private function modifySelectStatement(Query\AST\SelectStatement $selectStatement, $identificationVariableDecl): void { $rangeVariableDecl = $identificationVariableDecl->rangeVariableDeclaration; $joinAssocPathExpression = new Query\AST\JoinAssociationPathExpression($rangeVariableDecl->aliasIdentificationVariable, 'address'); @@ -212,7 +215,8 @@ private function modifySelectStatement(Query\AST\SelectStatement $selectStatemen $userMetadata = $entityManager->getClassMetadata(CmsUser::class); $addressMetadata = $entityManager->getClassMetadata(CmsAddress::class); - $this->setQueryComponent($rangeVariableDecl->aliasIdentificationVariable . 'a', + $this->setQueryComponent( + $rangeVariableDecl->aliasIdentificationVariable . 'a', [ 'metadata' => $addressMetadata, 'parent' => $rangeVariableDecl->aliasIdentificationVariable, diff --git a/tests/Doctrine/Tests/ORM/Query/DeleteSqlGenerationTest.php b/tests/Doctrine/Tests/ORM/Query/DeleteSqlGenerationTest.php index 0e4cd6aeb0a..7064032e46b 100644 --- a/tests/Doctrine/Tests/ORM/Query/DeleteSqlGenerationTest.php +++ b/tests/Doctrine/Tests/ORM/Query/DeleteSqlGenerationTest.php @@ -1,18 +1,17 @@ - * @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. @@ -21,18 +20,18 @@ class DeleteSqlGenerationTest extends OrmTestCase { private $_em; - protected function setUp() : void + protected function setUp(): void { $this->_em = $this->_getTestEntityManager(); } - public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed) + public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed): void { try { $query = $this->_em->createQuery($dqlToBeTested); parent::assertEquals($sqlToBeConfirmed, $query->getSql()); $query->free(); - } catch (\Exception $e) { + } catch (Exception $e) { $this->fail($e->getMessage()); } } @@ -40,7 +39,7 @@ public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed) /** * @group 6939 */ - public function testSupportsDeleteWithoutWhereAndAlias() : void + public function testSupportsDeleteWithoutWhereAndAlias(): void { $this->assertSqlGeneration( 'DELETE FROM Doctrine\Tests\Models\CMS\CmsUser', @@ -48,7 +47,7 @@ public function testSupportsDeleteWithoutWhereAndAlias() : void ); } - public function testSupportsDeleteWithoutWhereAndFrom() + public function testSupportsDeleteWithoutWhereAndFrom(): void { $this->assertSqlGeneration( 'DELETE Doctrine\Tests\Models\CMS\CmsUser u', @@ -56,7 +55,7 @@ public function testSupportsDeleteWithoutWhereAndFrom() ); } - public function testSupportsDeleteWithoutWhere() + public function testSupportsDeleteWithoutWhere(): void { $this->assertSqlGeneration( 'DELETE FROM Doctrine\Tests\Models\CMS\CmsUser u', @@ -64,7 +63,7 @@ public function testSupportsDeleteWithoutWhere() ); } - public function testSupportsWhereClause() + public function testSupportsWhereClause(): void { $this->assertSqlGeneration( 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1', @@ -72,7 +71,7 @@ public function testSupportsWhereClause() ); } - public function testSupportsWhereOrExpressions() + public function testSupportsWhereOrExpressions(): void { $this->assertSqlGeneration( 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = ?1 OR u.name = ?2', @@ -80,7 +79,7 @@ public function testSupportsWhereOrExpressions() ); } - public function testSupportsWhereNestedConditionalExpressions() + public function testSupportsWhereNestedConditionalExpressions(): void { $this->assertSqlGeneration( 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1 OR ( u.username = ?2 OR u.name = ?3)', @@ -93,114 +92,114 @@ public function testSupportsWhereNestedConditionalExpressions() //); } - public function testIsCaseAgnostic() + public function testIsCaseAgnostic(): void { $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() + public function testSupportsAndCondition(): void { $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() + public function testSupportsWhereNot(): void { $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() + public function testSupportsWhereNotWithParentheses(): void { $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() + public function testSupportsWhereNotWithAndExpression(): void { $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 = ?)' ); } // ConditionalPrimary was already tested (see testSupportsWhereClause() and testSupportsWhereNot()) - public function testSupportsGreaterThanComparisonClause() + public function testSupportsGreaterThanComparisonClause(): void { // 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() + public function testSupportsGreaterThanOrEqualToComparisonClause(): void { $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() + public function testSupportsLessThanComparisonClause(): void { $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() + public function testSupportsLessThanOrEqualToComparisonClause(): void { $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() + public function testSupportsNotEqualToComparisonClause(): void { $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() + public function testSupportsNotEqualToComparisonClauseExpressedWithExclamationMark(): void { $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() + public function testSupportsNotBetweenClause(): void { $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() + public function testSupportsBetweenClauseUsedWithAndClause(): void { $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 <> ?' ); } - public function testSupportsNotLikeClause() + public function testSupportsNotLikeClause(): void { // "WHERE" Expression LikeExpression $this->assertSqlGeneration( @@ -209,7 +208,7 @@ public function testSupportsNotLikeClause() ); } - public function testSupportsLikeClauseWithEscapeExpression() + public function testSupportsLikeClauseWithEscapeExpression(): void { $this->assertSqlGeneration( "DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username LIKE ?1 ESCAPE '\\'", @@ -217,7 +216,7 @@ public function testSupportsLikeClauseWithEscapeExpression() ); } - public function testSupportsIsNullClause() + public function testSupportsIsNullClause(): void { // "WHERE" Expression NullComparisonExpression $this->assertSqlGeneration( @@ -226,7 +225,7 @@ public function testSupportsIsNullClause() ); } - public function testSupportsIsNotNullClause() + public function testSupportsIsNotNullClause(): void { $this->assertSqlGeneration( 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name IS NOT NULL', @@ -234,7 +233,7 @@ public function testSupportsIsNotNullClause() ); } - public function testSupportsAtomExpressionAsClause() + public function testSupportsAtomExpressionAsClause(): void { $this->assertSqlGeneration( 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE 1 = 1', @@ -242,7 +241,7 @@ public function testSupportsAtomExpressionAsClause() ); } - public function testSupportsParameterizedAtomExpression() + public function testSupportsParameterizedAtomExpression(): void { $this->assertSqlGeneration( 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE ?1 = 1', @@ -250,7 +249,7 @@ public function testSupportsParameterizedAtomExpression() ); } - public function testSupportsInClause() + public function testSupportsInClause(): void { $this->assertSqlGeneration( 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id IN ( ?1, ?2, ?3, ?4 )', @@ -258,7 +257,7 @@ public function testSupportsInClause() ); } - public function testSupportsNotInClause() + public function testSupportsNotInClause(): void { $this->assertSqlGeneration( 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id NOT IN ( ?1, ?2 )', @@ -269,7 +268,7 @@ public function testSupportsNotInClause() /** * @group DDC-980 */ - public function testSubselectTableAliasReferencing() + public function testSubselectTableAliasReferencing(): void { $this->assertSqlGeneration( 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE SIZE(u.groups) = 10', diff --git a/tests/Doctrine/Tests/ORM/Query/ExprTest.php b/tests/Doctrine/Tests/ORM/Query/ExprTest.php index a4f73261708..4c449451d75 100644 --- a/tests/Doctrine/Tests/ORM/Query/ExprTest.php +++ b/tests/Doctrine/Tests/ORM/Query/ExprTest.php @@ -1,5 +1,7 @@ - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link http://www.phpdoctrine.org - * @since 2.0 - * @version $Revision$ */ class ExprTest extends OrmTestCase { private $_em; - /** - * @var Expr - */ + /** @var Expr */ private $_expr; - protected function setUp() : void + protected function setUp(): void { - $this->_em = $this->_getTestEntityManager(); - $this->_expr = new Expr; + $this->_em = $this->_getTestEntityManager(); + $this->_expr = new Expr(); } - public function testAvgExpr() + public function testAvgExpr(): void { $this->assertEquals('AVG(u.id)', (string) $this->_expr->avg('u.id')); } - public function testMaxExpr() + public function testMaxExpr(): void { $this->assertEquals('MAX(u.id)', (string) $this->_expr->max('u.id')); } - public function testMinExpr() + public function testMinExpr(): void { $this->assertEquals('MIN(u.id)', (string) $this->_expr->min('u.id')); } - public function testCountExpr() + public function testCountExpr(): void { $this->assertEquals('MAX(u.id)', (string) $this->_expr->max('u.id')); } - public function testCountDistinctExpr() + public function testCountDistinctExpr(): void { $this->assertEquals('COUNT(DISTINCT u.id)', (string) $this->_expr->countDistinct('u.id')); } - public function testCountDistinctExprMulti() + public function testCountDistinctExprMulti(): void { $this->assertEquals('COUNT(DISTINCT u.id, u.name)', (string) $this->_expr->countDistinct('u.id', 'u.name')); } - public function testExistsExpr() + public function testExistsExpr(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('u')->from('User', 'u')->where('u.name = ?1'); @@ -70,7 +66,7 @@ public function testExistsExpr() $this->assertEquals('EXISTS(SELECT u FROM User u WHERE u.name = ?1)', (string) $this->_expr->exists($qb)); } - public function testAllExpr() + public function testAllExpr(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('u')->from('User', 'u')->where('u.name = ?1'); @@ -78,7 +74,7 @@ public function testAllExpr() $this->assertEquals('ALL(SELECT u FROM User u WHERE u.name = ?1)', (string) $this->_expr->all($qb)); } - public function testSomeExpr() + public function testSomeExpr(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('u')->from('User', 'u')->where('u.name = ?1'); @@ -86,7 +82,7 @@ public function testSomeExpr() $this->assertEquals('SOME(SELECT u FROM User u WHERE u.name = ?1)', (string) $this->_expr->some($qb)); } - public function testAnyExpr() + public function testAnyExpr(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('u')->from('User', 'u')->where('u.name = ?1'); @@ -94,7 +90,7 @@ public function testAnyExpr() $this->assertEquals('ANY(SELECT u FROM User u WHERE u.name = ?1)', (string) $this->_expr->any($qb)); } - public function testNotExpr() + public function testNotExpr(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('u')->from('User', 'u')->where('u.name = ?1'); @@ -102,12 +98,12 @@ public function testNotExpr() $this->assertEquals('NOT(SELECT u FROM User u WHERE u.name = ?1)', (string) $this->_expr->not($qb)); } - public function testAndExpr() + public function testAndExpr(): void { $this->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() + public function testIntelligentParenthesisPreventionAndExpr(): void { $this->assertEquals( '1 = 1 AND 2 = 2', @@ -115,69 +111,69 @@ public function testIntelligentParenthesisPreventionAndExpr() ); } - public function testOrExpr() + public function testOrExpr(): void { $this->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() + public function testAbsExpr(): void { $this->assertEquals('ABS(1)', (string) $this->_expr->abs(1)); } - public function testProdExpr() + public function testProdExpr(): void { $this->assertEquals('1 * 2', (string) $this->_expr->prod(1, 2)); } - public function testDiffExpr() + public function testDiffExpr(): void { $this->assertEquals('1 - 2', (string) $this->_expr->diff(1, 2)); } - public function testSumExpr() + public function testSumExpr(): void { $this->assertEquals('1 + 2', (string) $this->_expr->sum(1, 2)); } - public function testQuotientExpr() + public function testQuotientExpr(): void { $this->assertEquals('10 / 2', (string) $this->_expr->quot(10, 2)); } - public function testScopeInArithmeticExpr() + public function testScopeInArithmeticExpr(): void { $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))); } - public function testSquareRootExpr() + public function testSquareRootExpr(): void { $this->assertEquals('SQRT(1)', (string) $this->_expr->sqrt(1)); } - public function testEqualExpr() + public function testEqualExpr(): void { $this->assertEquals('1 = 1', (string) $this->_expr->eq(1, 1)); } - public function testLikeExpr() + public function testLikeExpr(): void { $this->assertEquals('a.description LIKE :description', (string) $this->_expr->like('a.description', ':description')); } - public function testNotLikeExpr() + public function testNotLikeExpr(): void { $this->assertEquals('a.description NOT LIKE :description', (string) $this->_expr->notLike('a.description', ':description')); } - public function testConcatExpr() + public function testConcatExpr(): void { $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')); } - public function testSubstringExpr() + public function testSubstringExpr(): void { $this->assertEquals('SUBSTRING(a.title, 0, 25)', (string) $this->_expr->substring('a.title', 0, 25)); } @@ -186,42 +182,42 @@ public function testSubstringExpr() * @group regression * @group DDC-612 */ - public function testSubstringExprAcceptsTwoArguments() + public function testSubstringExprAcceptsTwoArguments(): void { $this->assertEquals('SUBSTRING(a.title, 5)', (string) $this->_expr->substring('a.title', 5)); } - public function testLowerExpr() + public function testLowerExpr(): void { $this->assertEquals('LOWER(u.first_name)', (string) $this->_expr->lower('u.first_name')); } - public function testUpperExpr() + public function testUpperExpr(): void { $this->assertEquals('UPPER(u.first_name)', (string) $this->_expr->upper('u.first_name')); } - public function testLengthExpr() + public function testLengthExpr(): void { $this->assertEquals('LENGTH(u.first_name)', (string) $this->_expr->length('u.first_name')); } - public function testGreaterThanExpr() + public function testGreaterThanExpr(): void { $this->assertEquals('5 > 2', (string) $this->_expr->gt(5, 2)); } - public function testLessThanExpr() + public function testLessThanExpr(): void { $this->assertEquals('2 < 5', (string) $this->_expr->lt(2, 5)); } - public function testStringLiteralExpr() + public function testStringLiteralExpr(): void { $this->assertEquals("'word'", (string) $this->_expr->literal('word')); } - public function testNumericLiteralExpr() + public function testNumericLiteralExpr(): void { $this->assertEquals(5, (string) $this->_expr->literal(5)); } @@ -230,50 +226,52 @@ public function testNumericLiteralExpr() * @group regression * @group DDC-610 */ - public function testLiteralExprProperlyQuotesStrings() + public function testLiteralExprProperlyQuotesStrings(): void { - $this->assertEquals("'00010001'", (string) $this->_expr->literal('00010001')); + $this->assertEquals("'00010001'", (string) $this->_expr->literal('00010001')); } - public function testGreaterThanOrEqualToExpr() + public function testGreaterThanOrEqualToExpr(): void { $this->assertEquals('5 >= 2', (string) $this->_expr->gte(5, 2)); } - public function testLessThanOrEqualTo() + public function testLessThanOrEqualTo(): void { $this->assertEquals('2 <= 5', (string) $this->_expr->lte(2, 5)); } - public function testBetweenExpr() + public function testBetweenExpr(): void { $this->assertEquals('u.id BETWEEN 3 AND 6', (string) $this->_expr->between('u.id', 3, 6)); } - public function testTrimExpr() + public function testTrimExpr(): void { $this->assertEquals('TRIM(u.id)', (string) $this->_expr->trim('u.id')); } - public function testIsNullExpr() + public function testIsNullExpr(): void { $this->assertEquals('u.id IS NULL', (string) $this->_expr->isNull('u.id')); } - public function testIsNotNullExpr() + public function testIsNotNullExpr(): void { $this->assertEquals('u.id IS NOT NULL', (string) $this->_expr->isNotNull('u.id')); } - public function testIsInstanceOfExpr() { + public function testIsInstanceOfExpr(): void + { $this->assertEquals('u INSTANCE OF Doctrine\Tests\Models\Company\CompanyEmployee', (string) $this->_expr->isInstanceOf('u', CompanyEmployee::class)); } - public function testIsMemberOfExpr() { + public function testIsMemberOfExpr(): void + { $this->assertEquals(':groupId MEMBER OF u.groups', (string) $this->_expr->isMemberOf(':groupId', 'u.groups')); } - public function provideIterableValue() : Generator + public function provideIterableValue(): Generator { $gen = static function () { yield from [1, 2, 3]; @@ -283,7 +281,7 @@ public function provideIterableValue() : Generator yield 'generator' => [$gen()]; } - public function provideLiteralIterableValue() : Generator + public function provideLiteralIterableValue(): Generator { $gen = static function () { yield from ['foo', 'bar']; @@ -296,7 +294,7 @@ public function provideLiteralIterableValue() : Generator /** * @dataProvider provideIterableValue */ - public function testInExpr(iterable $value) : void + public function testInExpr(iterable $value): void { self::assertEquals('u.id IN(1, 2, 3)', (string) $this->_expr->in('u.id', $value)); } @@ -304,7 +302,7 @@ public function testInExpr(iterable $value) : void /** * @dataProvider provideLiteralIterableValue */ - public function testInLiteralExpr(iterable $value) : void + public function testInLiteralExpr(iterable $value): void { self::assertEquals("u.type IN('foo', 'bar')", (string) $this->_expr->in('u.type', $value)); } @@ -312,7 +310,7 @@ public function testInLiteralExpr(iterable $value) : void /** * @dataProvider provideIterableValue */ - public function testNotInExpr(iterable $value) : void + public function testNotInExpr(iterable $value): void { self::assertEquals('u.id NOT IN(1, 2, 3)', (string) $this->_expr->notIn('u.id', $value)); } @@ -320,12 +318,12 @@ public function testNotInExpr(iterable $value) : void /** * @dataProvider provideLiteralIterableValue */ - public function testNotInLiteralExpr(iterable $value) : void + public function testNotInLiteralExpr(iterable $value): void { self::assertEquals("u.type NOT IN('foo', 'bar')", (string) $this->_expr->notIn('u.type', $value)); } - public function testAndxOrxExpr() + public function testAndxOrxExpr(): void { $andExpr = $this->_expr->andX(); $andExpr->add($this->_expr->eq(1, 1)); @@ -338,7 +336,7 @@ public function testAndxOrxExpr() $this->assertEquals('(1 = 1 AND 1 < 5) OR 1 = 1', (string) $orExpr); } - public function testOrxExpr() + public function testOrxExpr(): void { $orExpr = $this->_expr->orX(); $orExpr->add($this->_expr->eq(1, 1)); @@ -347,7 +345,7 @@ public function testOrxExpr() $this->assertEquals('1 = 1 OR 1 < 5', (string) $orExpr); } - public function testOrderByCountExpr() + public function testOrderByCountExpr(): void { $orderExpr = $this->_expr->desc('u.username'); @@ -355,19 +353,19 @@ public function testOrderByCountExpr() $this->assertEquals('u.username DESC', (string) $orderExpr); } - public function testOrderByOrder() + public function testOrderByOrder(): void { $orderExpr = $this->_expr->desc('u.username'); $this->assertEquals('u.username DESC', (string) $orderExpr); } - public function testOrderByAsc() + public function testOrderByAsc(): void { $orderExpr = $this->_expr->asc('u.username'); $this->assertEquals('u.username ASC', (string) $orderExpr); } - public function testAddThrowsException() + public function testAddThrowsException(): void { $this->expectException('InvalidArgumentException'); $orExpr = $this->_expr->orX(); @@ -377,19 +375,17 @@ public function testAddThrowsException() /** * @group DDC-1683 */ - public function testBooleanLiteral() + public function testBooleanLiteral(): void { $this->assertEquals('true', $this->_expr->literal(true)); $this->assertEquals('false', $this->_expr->literal(false)); } - /** * @group DDC-1686 */ - public function testExpressionGetter() + public function testExpressionGetter(): void { - // Andx $andx = new Expr\Andx(['1 = 1', '2 = 2']); $this->assertEquals(['1 = 1', '2 = 2'], $andx->getParts()); @@ -447,7 +443,7 @@ public function testExpressionGetter() $this->assertEquals(['foo', 'bar'], $select->getParts()); } - public function testAddEmpty() + public function testAddEmpty(): void { $andExpr = $this->_expr->andX(); $andExpr->add($this->_expr->andX()); @@ -455,7 +451,7 @@ public function testAddEmpty() $this->assertEquals(0, $andExpr->count()); } - public function testAddNull() + public function testAddNull(): void { $andExpr = $this->_expr->andX(); $andExpr->add(null); diff --git a/tests/Doctrine/Tests/ORM/Query/FilterCollectionTest.php b/tests/Doctrine/Tests/ORM/Query/FilterCollectionTest.php index 22aec4007a9..323e95990f3 100644 --- a/tests/Doctrine/Tests/ORM/Query/FilterCollectionTest.php +++ b/tests/Doctrine/Tests/ORM/Query/FilterCollectionTest.php @@ -1,30 +1,29 @@ */ class FilterCollectionTest extends OrmTestCase { - /** - * @var \Doctrine\ORM\EntityManager - */ + /** @var EntityManager */ private $em; - protected function setUp() : void + protected function setUp(): void { $this->em = $this->_getTestEntityManager(); $this->em->getConfiguration()->addFilter('testFilter', MyFilter::class); } - public function testEnable() + public function testEnable(): void { $filterCollection = $this->em->getFilters(); @@ -41,7 +40,7 @@ public function testEnable() $this->assertCount(0, $filterCollection->getEnabledFilters()); } - public function testHasFilter() + public function testHasFilter(): void { $filterCollection = $this->em->getFilters(); @@ -52,7 +51,7 @@ public function testHasFilter() /** * @depends testEnable */ - public function testIsEnabled() + public function testIsEnabled(): void { $filterCollection = $this->em->getFilters(); @@ -63,14 +62,14 @@ public function testIsEnabled() $this->assertTrue($filterCollection->isEnabled('testFilter')); } - public function testGetFilterInvalidArgument() + public function testGetFilterInvalidArgument(): void { $this->expectException('InvalidArgumentException'); $filterCollection = $this->em->getFilters(); $filterCollection->getFilter('testFilter'); } - public function testGetFilter() + public function testGetFilter(): void { $filterCollection = $this->em->getFilters(); $filterCollection->enable('testFilter'); diff --git a/tests/Doctrine/Tests/ORM/Query/LanguageRecognitionTest.php b/tests/Doctrine/Tests/ORM/Query/LanguageRecognitionTest.php index 35ad12d051e..9b740bbf221 100644 --- a/tests/Doctrine/Tests/ORM/Query/LanguageRecognitionTest.php +++ b/tests/Doctrine/Tests/ORM/Query/LanguageRecognitionTest.php @@ -1,26 +1,28 @@ _em = $this->_getTestEntityManager(); } - public function assertValidDQL($dql, $debug = false) + public function assertValidDQL($dql, $debug = false): void { try { $parserResult = $this->parseDql($dql); @@ -34,7 +36,7 @@ public function assertValidDQL($dql, $debug = false) } } - public function assertInvalidDQL($dql, $debug = false) + public function assertInvalidDQL($dql, $debug = false): void { try { $parserResult = $this->parseDql($dql); @@ -45,6 +47,7 @@ public function assertInvalidDQL($dql, $debug = false) echo $e->getMessage() . PHP_EOL; echo $e->getTraceAsString() . PHP_EOL; } + $this->addToAssertionCount(1); } } @@ -56,7 +59,7 @@ public function parseDql($dql, $hints = []) $query->setDQL($dql); foreach ($hints as $key => $value) { - $query->setHint($key, $value); + $query->setHint($key, $value); } $parser = new Query\Parser($query); @@ -67,17 +70,17 @@ public function parseDql($dql, $hints = []) return $parser->parse(); } - public function testEmptyQueryString() + public function testEmptyQueryString(): void { $this->assertInvalidDQL(''); } - public function testPlainFromClauseWithAlias() + public function testPlainFromClauseWithAlias(): void { $this->assertValidDQL('SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u'); } - public function testSelectSingleComponentWithAsterisk() + public function testSelectSingleComponentWithAsterisk(): void { $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u'); } @@ -85,14 +88,14 @@ public function testSelectSingleComponentWithAsterisk() /** * @dataProvider invalidDQL */ - public function testRejectsInvalidDQL($dql) + public function testRejectsInvalidDQL($dql): void { $this->expectException(QueryException::class); $this->_em->getConfiguration()->setEntityNamespaces( [ - 'Unknown' => 'Unknown', - 'CMS' => 'Doctrine\Tests\Models\CMS' + 'Unknown' => 'Unknown', + 'CMS' => 'Doctrine\Tests\Models\CMS', ] ); @@ -139,143 +142,143 @@ public function invalidDQL() ]; } - public function testSelectSingleComponentWithMultipleColumns() + public function testSelectSingleComponentWithMultipleColumns(): void { $this->assertValidDQL('SELECT u.name, u.username FROM Doctrine\Tests\Models\CMS\CmsUser u'); } - public function testSelectMultipleComponentsUsingMultipleFrom() + public function testSelectMultipleComponentsUsingMultipleFrom(): void { $this->assertValidDQL('SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE u = p.user'); } - public function testSelectMultipleComponentsWithAsterisk() + public function testSelectMultipleComponentsWithAsterisk(): void { $this->assertValidDQL('SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.phonenumbers p'); } - public function testSelectDistinctIsSupported() + public function testSelectDistinctIsSupported(): void { $this->assertValidDQL('SELECT DISTINCT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u'); } - public function testAggregateFunctionInSelect() + public function testAggregateFunctionInSelect(): void { $this->assertValidDQL('SELECT COUNT(u.id) FROM Doctrine\Tests\Models\CMS\CmsUser u'); } - public function testMultipleParenthesisInSelect() + public function testMultipleParenthesisInSelect(): void { $this->assertValidDQL('SELECT (((u.id))) as v FROM Doctrine\Tests\Models\CMS\CmsUser u'); } - public function testDuplicatedAliasInAggregateFunction() + public function testDuplicatedAliasInAggregateFunction(): void { $this->assertInvalidDQL('SELECT COUNT(u.id) AS num, SUM(u.id) AS num FROM Doctrine\Tests\Models\CMS\CmsUser u'); } - public function testAggregateFunctionWithDistinctInSelect() + public function testAggregateFunctionWithDistinctInSelect(): void { $this->assertValidDQL('SELECT COUNT(DISTINCT u.name) FROM Doctrine\Tests\Models\CMS\CmsUser u'); } - public function testFunctionalExpressionsSupportedInWherePart() + public function testFunctionalExpressionsSupportedInWherePart(): void { $this->assertValidDQL("SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE TRIM(u.name) = 'someone'"); } - public function testArithmeticExpressionsSupportedInWherePart() + public function testArithmeticExpressionsSupportedInWherePart(): void { $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE ((u.id + 5000) * u.id + 3) < 10000000'); } - public function testInExpressionSupportedInWherePart() + public function testInExpressionSupportedInWherePart(): void { $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id IN (1, 2)'); } - public function testInExpressionWithoutSpacesSupportedInWherePart() + public function testInExpressionWithoutSpacesSupportedInWherePart(): void { $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id IN (1,2,3)'); } - public function testNotInExpressionSupportedInWherePart() + public function testNotInExpressionSupportedInWherePart(): void { $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id NOT IN (1)'); } - public function testInExpressionWithSingleValuedAssociationPathExpression() + public function testInExpressionWithSingleValuedAssociationPathExpression(): void { - $this->assertValidDQL("SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u WHERE u.avatar IN (?1, ?2)"); + $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u WHERE u.avatar IN (?1, ?2)'); } - public function testInvalidInExpressionWithCollectionValuedAssociationPathExpression() + public function testInvalidInExpressionWithCollectionValuedAssociationPathExpression(): void { - $this->assertInvalidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.phonenumbers IN (?1, ?2)"); + $this->assertInvalidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.phonenumbers IN (?1, ?2)'); } - public function testInstanceOfExpressionSupportedInWherePart() + public function testInstanceOfExpressionSupportedInWherePart(): void { $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF Doctrine\Tests\Models\Company\CompanyEmployee'); } - public function testInstanceOfExpressionWithInputParamSupportedInWherePart() + public function testInstanceOfExpressionWithInputParamSupportedInWherePart(): void { $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF ?1'); } - public function testNotInstanceOfExpressionSupportedInWherePart() + public function testNotInstanceOfExpressionSupportedInWherePart(): void { $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u NOT INSTANCE OF ?1'); } - public function testExistsExpressionSupportedInWherePart() + public function testExistsExpressionSupportedInWherePart(): void { $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)'); } - public function testNotExistsExpressionSupportedInWherePart() + public function testNotExistsExpressionSupportedInWherePart(): void { $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)'); } - public function testAggregateFunctionInHavingClause() + public function testAggregateFunctionInHavingClause(): void { $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'"); } - public function testLeftJoin() + public function testLeftJoin(): void { $this->assertValidDQL('SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.phonenumbers p'); } - public function testJoin() + public function testJoin(): void { $this->assertValidDQL('SELECT u,p FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.phonenumbers p'); } - public function testInnerJoin() + public function testInnerJoin(): void { $this->assertValidDQL('SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.phonenumbers p'); } - public function testMultipleLeftJoin() + public function testMultipleLeftJoin(): void { $this->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() + public function testMultipleInnerJoin(): void { $this->assertValidDQL('SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.articles a INNER JOIN u.phonenumbers p'); } - public function testMixingOfJoins() + public function testMixingOfJoins(): void { $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'); } - public function testJoinClassPathUsingWITH() + public function testJoinClassPathUsingWITH(): void { $this->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() /** * @group DDC-3701 */ - public function testJoinClassPathUsingWHERE() + public function testJoinClassPathUsingWHERE(): void { $this->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() /** * @group DDC-3701 */ - public function testDDC3701WHEREIsNotWITH() + public function testDDC3701WHEREIsNotWITH(): void { $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'); } - public function testOrderBySingleColumn() + public function testOrderBySingleColumn(): void { $this->assertValidDQL('SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.name'); } - public function testOrderBySingleColumnAscending() + public function testOrderBySingleColumnAscending(): void { $this->assertValidDQL('SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.name ASC'); } - public function testOrderBySingleColumnDescending() + public function testOrderBySingleColumnDescending(): void { $this->assertValidDQL('SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.name DESC'); } - public function testOrderByMultipleColumns() + public function testOrderByMultipleColumns(): void { $this->assertValidDQL('SELECT u.name, u.username FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.username DESC, u.name DESC'); } - public function testSubselectInInExpression() + public function testSubselectInInExpression(): void { $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')"); } - public function testSubselectInSelectPart() + public function testSubselectInSelectPart(): void { $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'"); } - public function testArithmeticExpressionInSelectPart() + public function testArithmeticExpressionInSelectPart(): void { - $this->assertValidDQL("SELECT SUM(u.id) / COUNT(u.id) FROM Doctrine\Tests\Models\CMS\CmsUser u"); + $this->assertValidDQL('SELECT SUM(u.id) / COUNT(u.id) FROM Doctrine\Tests\Models\CMS\CmsUser u'); } - public function testArithmeticExpressionInSubselectPart() + public function testArithmeticExpressionInSubselectPart(): void { $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'"); } - public function testArithmeticExpressionWithParenthesisInSubselectPart() + public function testArithmeticExpressionWithParenthesisInSubselectPart(): void { $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'"); } @@ -344,7 +347,7 @@ public function testArithmeticExpressionWithParenthesisInSubselectPart() /** * @group DDC-1079 */ - public function testSelectLiteralInSubselect() + public function testSelectLiteralInSubselect(): void { $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'); @@ -353,125 +356,125 @@ public function testSelectLiteralInSubselect() /** * @group DDC-1077 */ - public function testConstantValueInSelect() + public function testConstantValueInSelect(): void { $this->assertValidDQL("SELECT u.name, 'foo' AS bar FROM Doctrine\Tests\Models\CMS\CmsUser u", true); } - public function testDuplicateAliasInSubselectPart() + public function testDuplicateAliasInSubselectPart(): void { $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'"); } - public function testPositionalInputParameter() + public function testPositionalInputParameter(): void { $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1'); } - public function testNamedInputParameter() + public function testNamedInputParameter(): void { $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :id'); } - public function testJoinConditionOverrideNotSupported() + public function testJoinConditionOverrideNotSupported(): void { $this->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() + public function testIndexByClauseWithOneComponent(): void { $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u INDEX BY u.id'); } - public function testIndexBySupportsJoins() + public function testIndexBySupportsJoins(): void { $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 } - public function testIndexBySupportsJoins2() + public function testIndexBySupportsJoins2(): void { $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'); } - public function testBetweenExpressionSupported() + public function testBetweenExpressionSupported(): void { $this->assertValidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name BETWEEN 'jepso' AND 'zYne'"); } - public function testNotBetweenExpressionSupported() + public function testNotBetweenExpressionSupported(): void { $this->assertValidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name NOT BETWEEN 'jepso' AND 'zYne'"); } - public function testLikeExpression() + public function testLikeExpression(): void { $this->assertValidDQL("SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name LIKE 'z%'"); } - public function testNotLikeExpression() + public function testNotLikeExpression(): void { $this->assertValidDQL("SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name NOT LIKE 'z%'"); } - public function testLikeExpressionWithCustomEscapeCharacter() + public function testLikeExpressionWithCustomEscapeCharacter(): void { $this->assertValidDQL("SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name LIKE 'z|%' ESCAPE '|'"); } - public function testFieldComparisonWithoutAlias() + public function testFieldComparisonWithoutAlias(): void { - $this->assertInvalidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE id = 1"); + $this->assertInvalidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE id = 1'); } - public function testDuplicatedAliasDeclaration() + public function testDuplicatedAliasDeclaration(): void { - $this->assertInvalidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.articles u WHERE u.id = 1"); + $this->assertInvalidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.articles u WHERE u.id = 1'); } - public function testImplicitJoinInWhereOnSingleValuedAssociationPathExpression() + public function testImplicitJoinInWhereOnSingleValuedAssociationPathExpression(): void { // 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"); + $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u JOIN u.avatar a WHERE a.id = ?1'); } - public function testImplicitJoinInWhereOnCollectionValuedPathExpression() + public function testImplicitJoinInWhereOnCollectionValuedPathExpression(): void { // 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 = ?"); + $this->assertInvalidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.articles a WHERE a.title = ?'); } - public function testInvalidSyntaxIsRejected() + public function testInvalidSyntaxIsRejected(): void { - $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"); + $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'); // Currently UNDEFINED OFFSET error - $this->assertInvalidDQL("SELECT c FROM CmsUser.articles.comments c"); + $this->assertInvalidDQL('SELECT c FROM CmsUser.articles.comments c'); } - public function testUpdateWorksWithOneField() + public function testUpdateWorksWithOneField(): void { $this->assertValidDQL("UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = 'someone'"); } - public function testUpdateWorksWithMultipleFields() + public function testUpdateWorksWithMultipleFields(): void { $this->assertValidDQL("UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = 'someone', u.username = 'some'"); } - public function testUpdateSupportsConditions() + public function testUpdateSupportsConditions(): void { $this->assertValidDQL("UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = 'someone' WHERE u.id = 5"); } - public function testDeleteAll() + public function testDeleteAll(): void { $this->assertValidDQL('DELETE FROM Doctrine\Tests\Models\CMS\CmsUser u'); } - public function testDeleteWithCondition() + public function testDeleteWithCondition(): void { $this->assertValidDQL('DELETE FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = 3'); } @@ -480,94 +483,94 @@ public function testDeleteWithCondition() * The main use case for this generalized style of join is when a join condition * does not involve a foreign key relationship that is mapped to an entity relationship. */ - public function testImplicitJoinWithCartesianProductAndConditionInWhere() + public function testImplicitJoinWithCartesianProductAndConditionInWhere(): void { - $this->assertValidDQL("SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsArticle a WHERE u.name = a.topic"); + $this->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() + public function testAllExpressionWithCorrelatedSubquery(): void { $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)'); } - public function testCustomJoinsAndWithKeywordSupported() + public function testCustomJoinsAndWithKeywordSupported(): void { $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'); } - public function testAnyExpressionWithCorrelatedSubquery() + public function testAnyExpressionWithCorrelatedSubquery(): void { $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)'); } - public function testSomeExpressionWithCorrelatedSubquery() + public function testSomeExpressionWithCorrelatedSubquery(): void { $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)'); } - public function testArithmeticExpressionWithoutParenthesisInWhereClause() + public function testArithmeticExpressionWithoutParenthesisInWhereClause(): void { $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE SIZE(u.phonenumbers) + 1 > 10'); } - public function testMemberOfExpression() + public function testMemberOfExpression(): void { $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"); } - public function testSizeFunction() + public function testSizeFunction(): void { $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE SIZE(u.phonenumbers) > 1'); } - public function testEmptyCollectionComparisonExpression() + public function testEmptyCollectionComparisonExpression(): void { $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.phonenumbers IS EMPTY'); } - public function testSingleValuedAssociationFieldInWhere() + public function testSingleValuedAssociationFieldInWhere(): void { $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'); } - public function testBooleanLiteralInWhere() + public function testBooleanLiteralInWhere(): void { $this->assertValidDQL('SELECT b FROM Doctrine\Tests\Models\Generic\BooleanModel b WHERE b.booleanField = true'); } - public function testSubqueryInSelectExpression() + public function testSubqueryInSelectExpression(): void { $this->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() + public function testUsageOfQComponentOutsideSubquery(): void { $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'); } - public function testUnknownAbstractSchemaName() + public function testUnknownAbstractSchemaName(): void { $this->assertInvalidDQL('SELECT u FROM UnknownClassName u'); } - public function testCorrectPartialObjectLoad() + public function testCorrectPartialObjectLoad(): void { $this->assertValidDQL('SELECT PARTIAL u.{id,name} FROM Doctrine\Tests\Models\CMS\CmsUser u'); } - public function testIncorrectPartialObjectLoadBecauseOfMissingIdentifier() + public function testIncorrectPartialObjectLoadBecauseOfMissingIdentifier(): void { $this->assertInvalidDQL('SELECT PARTIAL u.{name} FROM Doctrine\Tests\Models\CMS\CmsUser u'); } - public function testScalarExpressionInSelect() + public function testScalarExpressionInSelect(): void { $this->assertValidDQL('SELECT u, 42 + u.id AS someNumber FROM Doctrine\Tests\Models\CMS\CmsUser u'); } - public function testInputParameterInSelect() + public function testInputParameterInSelect(): void { $this->assertValidDQL('SELECT u, u.id + ?1 AS someNumber FROM Doctrine\Tests\Models\CMS\CmsUser u'); } @@ -575,7 +578,7 @@ public function testInputParameterInSelect() /** * @group DDC-1091 */ - public function testCustomFunctionsReturningStringInStringPrimary() + public function testCustomFunctionsReturningStringInStringPrimary(): void { $this->_em->getConfiguration()->addCustomStringFunction('CC', Query\AST\Functions\ConcatFunction::class); @@ -585,7 +588,7 @@ public function testCustomFunctionsReturningStringInStringPrimary() /** * @group DDC-505 */ - public function testDQLKeywordInJoinIsAllowed() + public function testDQLKeywordInJoinIsAllowed(): void { $this->assertValidDQL('SELECT u FROM ' . __NAMESPACE__ . '\DQLKeywordsModelUser u JOIN u.group g'); } @@ -593,7 +596,7 @@ public function testDQLKeywordInJoinIsAllowed() /** * @group DDC-505 */ - public function testDQLKeywordInConditionIsAllowed() + public function testDQLKeywordInConditionIsAllowed(): void { $this->assertValidDQL('SELECT g FROM ' . __NAMESPACE__ . '\DQLKeywordsModelGroup g WHERE g.from=0'); } @@ -608,7 +611,7 @@ public function testInverseSideSingleValuedAssociationPathNotAllowed() /** * @group DDC-617 */ - public function testSelectOnlyNonRootEntityAlias() + public function testSelectOnlyNonRootEntityAlias(): void { $this->assertInvalidDQL('SELECT g FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.groups g'); } @@ -616,7 +619,7 @@ public function testSelectOnlyNonRootEntityAlias() /** * @group DDC-1108 */ - public function testInputParameterSingleChar() + public function testInputParameterSingleChar(): void { $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = :q'); } @@ -624,7 +627,7 @@ public function testInputParameterSingleChar() /** * @group DDC-1053 */ - public function testGroupBy() + public function testGroupBy(): void { $this->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() /** * @group DDC-1053 */ - public function testGroupByIdentificationVariable() + public function testGroupByIdentificationVariable(): void { $this->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() /** * @group DDC-1053 */ - public function testGroupByUnknownIdentificationVariable() + public function testGroupByUnknownIdentificationVariable(): void { $this->assertInvalidDQL('SELECT g, count(u.id) FROM Doctrine\Tests\Models\CMS\CmsGroup g JOIN g.users u GROUP BY m'); } @@ -648,25 +651,25 @@ public function testGroupByUnknownIdentificationVariable() /** * @group DDC-117 */ - public function testSizeOfForeignKeyOneToManyPrimaryKeyEntity() + public function testSizeOfForeignKeyOneToManyPrimaryKeyEntity(): void { - $this->assertValidDQL("SELECT a, t FROM Doctrine\Tests\Models\DDC117\DDC117Article a JOIN a.translations t WHERE SIZE(a.translations) > 0"); + $this->assertValidDQL('SELECT a, t FROM Doctrine\Tests\Models\DDC117\DDC117Article a JOIN a.translations t WHERE SIZE(a.translations) > 0'); } /** * @group DDC-117 */ - public function testSizeOfForeignKeyManyToManyPrimaryKeyEntity() + public function testSizeOfForeignKeyManyToManyPrimaryKeyEntity(): void { - $this->assertValidDQL("SELECT e, t FROM Doctrine\Tests\Models\DDC117\DDC117Editor e JOIN e.reviewingTranslations t WHERE SIZE(e.reviewingTranslations) > 0"); + $this->assertValidDQL('SELECT e, t FROM Doctrine\Tests\Models\DDC117\DDC117Editor e JOIN e.reviewingTranslations t WHERE SIZE(e.reviewingTranslations) > 0'); } - public function testCaseSupportContainingNullIfExpression() + public function testCaseSupportContainingNullIfExpression(): void { - $this->assertValidDQL("SELECT u.id, NULLIF(u.name, u.name) AS shouldBeNull FROM Doctrine\Tests\Models\CMS\CmsUser u"); + $this->assertValidDQL('SELECT u.id, NULLIF(u.name, u.name) AS shouldBeNull FROM Doctrine\Tests\Models\CMS\CmsUser u'); } - public function testCaseSupportContainingCoalesceExpression() + public function testCaseSupportContainingCoalesceExpression(): void { $this->assertValidDQL("select COALESCE(NULLIF(u.name, ''), u.username) as Display FROM Doctrine\Tests\Models\CMS\CmsUser u"); } @@ -674,23 +677,23 @@ public function testCaseSupportContainingCoalesceExpression() /** * @group DDC-1858 */ - public function testHavingSupportIsNullExpression() + public function testHavingSupportIsNullExpression(): void { - $this->assertValidDQL("SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u HAVING u.username IS NULL"); + $this->assertValidDQL('SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u HAVING u.username IS NULL'); } /** * @group DDC-3085 */ - public function testHavingSupportResultVariableInNullComparisonExpression() + public function testHavingSupportResultVariableInNullComparisonExpression(): void { - $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"); + $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'); } /** * @group DDC-1858 */ - public function testHavingSupportLikeExpression() + public function testHavingSupportLikeExpression(): void { $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'"); } @@ -698,20 +701,20 @@ public function testHavingSupportLikeExpression() /** * @group DDC-3018 */ - public function testNewLiteralExpression() + public function testNewLiteralExpression(): void { - $this->assertValidDQL("SELECT new " . __NAMESPACE__ . "\\DummyStruct(u.id, 'foo', 1, true) FROM Doctrine\Tests\Models\CMS\CmsUser u"); + $this->assertValidDQL('SELECT new ' . __NAMESPACE__ . "\\DummyStruct(u.id, 'foo', 1, true) FROM Doctrine\Tests\Models\CMS\CmsUser u"); } /** * @group DDC-3075 */ - public function testNewLiteralWithSubselectExpression() + public function testNewLiteralWithSubselectExpression(): void { - $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"); + $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"); } - public function testStringPrimaryAcceptsAggregateExpression() : void + public function testStringPrimaryAcceptsAggregateExpression(): void { $this->assertValidDQL( 'SELECT CONCAT(a.topic, MAX(a.version)) last FROM Doctrine\Tests\Models\CMS\CmsArticle a GROUP BY a' diff --git a/tests/Doctrine/Tests/ORM/Query/LexerTest.php b/tests/Doctrine/Tests/ORM/Query/LexerTest.php index 46f2038c6f5..a23ad8f3581 100644 --- a/tests/Doctrine/Tests/ORM/Query/LexerTest.php +++ b/tests/Doctrine/Tests/ORM/Query/LexerTest.php @@ -1,5 +1,7 @@ assertEquals($value, $token['value']); } - public function testScannerRecognizesTerminalString() + public function testScannerRecognizesTerminalString(): void { /* * "all" looks like an identifier, but in fact it's a reserved word @@ -39,7 +41,7 @@ public function testScannerRecognizesTerminalString() $this->assertEquals(Lexer::T_ALL, $token['type']); } - public function testScannerRecognizesDecimalInteger() + public function testScannerRecognizesDecimalInteger(): void { $lexer = new Lexer('1234'); $lexer->moveNext(); @@ -48,7 +50,7 @@ public function testScannerRecognizesDecimalInteger() $this->assertEquals(1234, $token['value']); } - public function testScannerRecognizesFloat() + public function testScannerRecognizesFloat(): void { $lexer = new Lexer('1.234'); $lexer->moveNext(); @@ -57,7 +59,7 @@ public function testScannerRecognizesFloat() $this->assertEquals(1.234, $token['value']); } - public function testScannerRecognizesFloatWithExponent() + public function testScannerRecognizesFloatWithExponent(): void { $lexer = new Lexer('1.2e3'); $lexer->moveNext(); @@ -66,7 +68,7 @@ public function testScannerRecognizesFloatWithExponent() $this->assertEquals(1.2e3, $token['value']); } - public function testScannerRecognizesFloatWithExponent2() + public function testScannerRecognizesFloatWithExponent2(): void { $lexer = new Lexer('0.2e3'); $lexer->moveNext(); @@ -75,7 +77,7 @@ public function testScannerRecognizesFloatWithExponent2() $this->assertEquals(.2e3, $token['value']); } - public function testScannerRecognizesFloatWithNegativeExponent() + public function testScannerRecognizesFloatWithNegativeExponent(): void { $lexer = new Lexer('7E-10'); $lexer->moveNext(); @@ -84,7 +86,7 @@ public function testScannerRecognizesFloatWithNegativeExponent() $this->assertEquals(7E-10, $token['value']); } - public function testScannerRecognizesFloatBig() + public function testScannerRecognizesFloatBig(): void { $lexer = new Lexer('123456789.01'); $lexer->moveNext(); @@ -93,7 +95,7 @@ public function testScannerRecognizesFloatBig() $this->assertEquals(1.2345678901e8, $token['value']); } - public function testScannerRecognizesFloatContainingWhitespace() + public function testScannerRecognizesFloatContainingWhitespace(): void { $lexer = new Lexer('- 1.234e2'); $lexer->moveNext(); @@ -108,16 +110,16 @@ public function testScannerRecognizesFloatContainingWhitespace() $this->assertEquals(1.234e2, $token['value']); } - public function testScannerRecognizesStringContainingWhitespace() + public function testScannerRecognizesStringContainingWhitespace(): void { $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']); + $this->assertEquals('This is a string.', $token['value']); } - public function testScannerRecognizesStringContainingSingleQuotes() + public function testScannerRecognizesStringContainingSingleQuotes(): void { $lexer = new Lexer("'abc''defg'''"); $lexer->moveNext(); @@ -126,7 +128,7 @@ public function testScannerRecognizesStringContainingSingleQuotes() $this->assertEquals("abc'defg'", $token['value']); } - public function testScannerRecognizesInputParameter() + public function testScannerRecognizesInputParameter(): void { $lexer = new Lexer('?1'); $lexer->moveNext(); @@ -135,7 +137,7 @@ public function testScannerRecognizesInputParameter() $this->assertEquals('?1', $token['value']); } - public function testScannerRecognizesNamedInputParameter() + public function testScannerRecognizesNamedInputParameter(): void { $lexer = new Lexer(':name'); $lexer->moveNext(); @@ -144,7 +146,7 @@ public function testScannerRecognizesNamedInputParameter() $this->assertEquals(':name', $token['value']); } - public function testScannerRecognizesNamedInputParameterStartingWithUnderscore() + public function testScannerRecognizesNamedInputParameterStartingWithUnderscore(): void { $lexer = new Lexer(':_name'); $lexer->moveNext(); @@ -153,67 +155,67 @@ public function testScannerRecognizesNamedInputParameterStartingWithUnderscore() $this->assertEquals(':_name', $token['value']); } - public function testScannerTokenizesASimpleQueryCorrectly() + public function testScannerTokenizesASimpleQueryCorrectly(): void { - $dql = "SELECT u FROM My\Namespace\User u WHERE u.name = 'Jack O''Neil'"; + $dql = "SELECT u FROM My\Namespace\User u WHERE u.name = 'Jack O''Neil'"; $lexer = new Lexer($dql); $tokens = [ [ 'value' => 'SELECT', 'type' => Lexer::T_SELECT, - 'position' => 0 + 'position' => 0, ], [ 'value' => 'u', 'type' => Lexer::T_IDENTIFIER, - 'position' => 7 + 'position' => 7, ], [ 'value' => 'FROM', 'type' => Lexer::T_FROM, - 'position' => 9 + 'position' => 9, ], [ 'value' => 'My\Namespace\User', 'type' => Lexer::T_FULLY_QUALIFIED_NAME, - 'position' => 14 + 'position' => 14, ], [ 'value' => 'u', 'type' => Lexer::T_IDENTIFIER, - 'position' => 32 + 'position' => 32, ], [ 'value' => 'WHERE', 'type' => Lexer::T_WHERE, - 'position' => 34 + 'position' => 34, ], [ 'value' => 'u', 'type' => Lexer::T_IDENTIFIER, - 'position' => 40 + 'position' => 40, ], [ 'value' => '.', 'type' => Lexer::T_DOT, - 'position' => 41 + 'position' => 41, ], [ 'value' => 'name', 'type' => Lexer::T_IDENTIFIER, - 'position' => 42 + 'position' => 42, ], [ 'value' => '=', 'type' => Lexer::T_EQUALS, - 'position' => 47 + 'position' => 47, ], [ 'value' => "Jack O'Neil", 'type' => Lexer::T_STRING, - 'position' => 49 - ] + 'position' => 49, + ], ]; foreach ($tokens as $expected) { @@ -238,7 +240,7 @@ public function provideTokens() [Lexer::T_IDENTIFIER, 'comma'], // name of a token class with value < 100 (whitebox test) [Lexer::T_FULLY_QUALIFIED_NAME, 'Some\Class'], // DQL class reference [Lexer::T_ALIASED_NAME, 'Some:Name'], - [Lexer::T_ALIASED_NAME, 'Some:Subclassed\Name'] + [Lexer::T_ALIASED_NAME, 'Some:Subclassed\Name'], ]; } } diff --git a/tests/Doctrine/Tests/ORM/Query/ParameterTypeInfererTest.php b/tests/Doctrine/Tests/ORM/Query/ParameterTypeInfererTest.php index 5a1ac5fe3ee..2eb4e8eed0a 100644 --- a/tests/Doctrine/Tests/ORM/Query/ParameterTypeInfererTest.php +++ b/tests/Doctrine/Tests/ORM/Query/ParameterTypeInfererTest.php @@ -1,41 +1,42 @@ assertEquals($expected, ParameterTypeInferer::inferType($value)); } diff --git a/tests/Doctrine/Tests/ORM/Query/ParserResultTest.php b/tests/Doctrine/Tests/ORM/Query/ParserResultTest.php index c0b33bbc0dd..a7cc5e40c90 100644 --- a/tests/Doctrine/Tests/ORM/Query/ParserResultTest.php +++ b/tests/Doctrine/Tests/ORM/Query/ParserResultTest.php @@ -1,5 +1,7 @@ parserResult = new ParserResult(); } - public function testGetRsm() + public function testGetRsm(): void { $this->assertInstanceOf(ResultSetMapping::class, $this->parserResult->getResultSetMapping()); } - public function testSetGetSqlExecutor() + public function testSetGetSqlExecutor(): void { $this->assertNull($this->parserResult->getSqlExecutor()); @@ -30,14 +32,14 @@ public function testSetGetSqlExecutor() $this->assertSame($executor, $this->parserResult->getSqlExecutor()); } - public function testGetSqlParameterPosition() + public function testGetSqlParameterPosition(): void { $this->parserResult->addParameterMapping(1, 1); $this->parserResult->addParameterMapping(1, 2); $this->assertEquals([1, 2], $this->parserResult->getSqlParameterPositions(1)); } - public function testGetParameterMappings() + public function testGetParameterMappings(): void { $this->assertIsArray($this->parserResult->getParameterMappings()); diff --git a/tests/Doctrine/Tests/ORM/Query/ParserTest.php b/tests/Doctrine/Tests/ORM/Query/ParserTest.php index 65937a0942e..bc2a277d56b 100644 --- a/tests/Doctrine/Tests/ORM/Query/ParserTest.php +++ b/tests/Doctrine/Tests/ORM/Query/ParserTest.php @@ -1,5 +1,7 @@ createParser(CmsUser::class); @@ -27,7 +29,7 @@ public function testAbstractSchemaNameSupportsFQCN() * @covers Doctrine\ORM\Query\Parser::AbstractSchemaName * @group DDC-3715 */ - public function testAbstractSchemaNameSupportsClassnamesWithLeadingBackslash() + public function testAbstractSchemaNameSupportsClassnamesWithLeadingBackslash(): void { $parser = $this->createParser('\\' . CmsUser::class); @@ -38,18 +40,18 @@ public function testAbstractSchemaNameSupportsClassnamesWithLeadingBackslash() * @covers \Doctrine\ORM\Query\Parser::AbstractSchemaName * @group DDC-3715 */ - public function testAbstractSchemaNameSupportsIdentifier() + public function testAbstractSchemaNameSupportsIdentifier(): void { - $parser = $this->createParser(\stdClass::class); + $parser = $this->createParser(stdClass::class); - $this->assertEquals(\stdClass::class, $parser->AbstractSchemaName()); + $this->assertEquals(stdClass::class, $parser->AbstractSchemaName()); } /** * @covers \Doctrine\ORM\Query\Parser::AbstractSchemaName * @group DDC-3715 */ - public function testAbstractSchemaNameSupportsNamespaceAlias() + public function testAbstractSchemaNameSupportsNamespaceAlias(): void { $parser = $this->createParser('CMS:CmsUser'); @@ -62,7 +64,7 @@ public function testAbstractSchemaNameSupportsNamespaceAlias() * @covers \Doctrine\ORM\Query\Parser::AbstractSchemaName * @group DDC-3715 */ - public function testAbstractSchemaNameSupportsNamespaceAliasWithRelativeClassname() + public function testAbstractSchemaNameSupportsNamespaceAliasWithRelativeClassname(): void { $parser = $this->createParser('Model:CMS\CmsUser'); @@ -76,7 +78,7 @@ public function testAbstractSchemaNameSupportsNamespaceAliasWithRelativeClassnam * @covers Doctrine\ORM\Query\Parser::match * @group DDC-3701 */ - public function testMatch($expectedToken, $inputString) + public function testMatch($expectedToken, $inputString): void { $parser = $this->createParser($inputString); @@ -90,7 +92,7 @@ public function testMatch($expectedToken, $inputString) * @covers Doctrine\ORM\Query\Parser::match * @group DDC-3701 */ - public function testMatchFailure($expectedToken, $inputString) + public function testMatchFailure($expectedToken, $inputString): void { $this->expectException(QueryException::class); @@ -114,7 +116,7 @@ public function validMatches() [Lexer::T_DOT, '.'], // token that cannot be an identifier [Lexer::T_IDENTIFIER, 'someIdentifier'], [Lexer::T_IDENTIFIER, 'from'], // also a terminal string (the "FROM" keyword) as in DDC-505 - [Lexer::T_IDENTIFIER, 'comma'] + [Lexer::T_IDENTIFIER, 'comma'], // not even a terminal string, but the name of a constant in the Lexer (whitebox test) ]; } @@ -141,7 +143,7 @@ public function invalidMatches() * * @group GH7934 */ - public function testNullLookahead() : void + public function testNullLookahead(): void { $query = new Query($this->_getTestEntityManager()); $query->setDQL('SELECT CURRENT_TIMESTAMP()'); diff --git a/tests/Doctrine/Tests/ORM/Query/QueryExpressionVisitorTest.php b/tests/Doctrine/Tests/ORM/Query/QueryExpressionVisitorTest.php index 2a8832f0c49..c7d0e065dae 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 { - /** - * @var QueryExpressionVisitor - */ + /** @var QueryExpressionVisitor */ private $visitor; - /** - * {@inheritDoc} - */ - protected function setUp() : void + protected function setUp(): void { - $this->visitor = new QueryExpressionVisitor(['o','p']); + $this->visitor = new QueryExpressionVisitor(['o', 'p']); } /** - * @param CriteriaComparison $criteriaExpr * @param QueryBuilder\Comparison|string $queryExpr - * @param Parameter $parameter * * @dataProvider comparisonData */ - public function testWalkComparison(CriteriaComparison $criteriaExpr, $queryExpr, Parameter $parameter = null) + public function testWalkComparison(CriteriaComparison $criteriaExpr, $queryExpr, ?Parameter $parameter = null): void { $this->assertEquals($queryExpr, $this->visitor->walkComparison($criteriaExpr)); if ($parameter) { @@ -81,13 +74,13 @@ public function comparisonData() ]; } - public function testWalkAndCompositeExpression() + public function testWalkAndCompositeExpression(): void { - $cb = new CriteriaBuilder(); + $cb = new CriteriaBuilder(); $expr = $this->visitor->walkCompositeExpression( $cb->andX( - $cb->eq("foo", 1), - $cb->eq("bar", 1) + $cb->eq('foo', 1), + $cb->eq('bar', 1) ) ); @@ -95,13 +88,13 @@ public function testWalkAndCompositeExpression() $this->assertCount(2, $expr->getParts()); } - public function testWalkOrCompositeExpression() + public function testWalkOrCompositeExpression(): void { - $cb = new CriteriaBuilder(); + $cb = new CriteriaBuilder(); $expr = $this->visitor->walkCompositeExpression( $cb->orX( - $cb->eq("foo", 1), - $cb->eq("bar", 1) + $cb->eq('foo', 1), + $cb->eq('bar', 1) ) ); @@ -109,12 +102,12 @@ public function testWalkOrCompositeExpression() $this->assertCount(2, $expr->getParts()); } - public function testWalkValue() + public function testWalkValue(): void { $this->assertEquals('value', $this->visitor->walkValue(new Value('value'))); } - public function testClearParameters() + public function testClearParameters(): void { $this->visitor->getParameters()->add(new Parameter('field', 'value')); diff --git a/tests/Doctrine/Tests/ORM/Query/QueryTest.php b/tests/Doctrine/Tests/ORM/Query/QueryTest.php index 6f383a47c63..ddbf151b8c4 100644 --- a/tests/Doctrine/Tests/ORM/Query/QueryTest.php +++ b/tests/Doctrine/Tests/ORM/Query/QueryTest.php @@ -1,5 +1,7 @@ _em = $this->_getTestEntityManager(); } - public function testGetParameters() + public function testGetParameters(): void { - $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()); } - public function testGetParameters_HasSomeAlready() + public function testGetParameters_HasSomeAlready(): void { - $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(); @@ -54,9 +58,9 @@ public function testGetParameters_HasSomeAlready() $this->assertEquals($parameters, $query->getParameters()); } - public function testSetParameters() + public function testSetParameters(): void { - $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')); @@ -67,22 +71,22 @@ public function testSetParameters() $this->assertEquals($parameters, $query->getParameters()); } - public function testFree() + public function testFree(): void { - $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 = $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())); } - public function testClone() + public function testClone(): void { - $dql = "select u from Doctrine\Tests\Models\CMS\CmsUser u where u.username = ?1"; + $dql = 'select u from Doctrine\Tests\Models\CMS\CmsUser u where u.username = ?1'; $query = $this->_em->createQuery($dql); - $query->setParameter(2, 84, \PDO::PARAM_INT); + $query->setParameter(2, 84, PDO::PARAM_INT); $query->setHint('foo', 'bar'); $cloned = clone $query; @@ -92,9 +96,9 @@ public function testClone() $this->assertFalse($cloned->getHint('foo')); } - public function testFluentQueryInterface() + public function testFluentQueryInterface(): void { - $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) @@ -115,9 +119,9 @@ public function testFluentQueryInterface() /** * @group DDC-968 */ - public function testHints() + public function testHints(): void { - $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')); @@ -130,15 +134,15 @@ public function testHints() /** * @group DDC-1588 */ - public function testQueryDefaultResultCache() + public function testQueryDefaultResultCache(): void { $this->_em->getConfiguration()->setResultCacheImpl(new ArrayCache()); - $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->enableResultCache(); $this->assertSame($this->_em->getConfiguration()->getResultCacheImpl(), $q->getQueryCacheProfile()->getResultCacheDriver()); } - public function testIterateWithNoDistinctAndWrongSelectClause() + public function testIterateWithNoDistinctAndWrongSelectClause(): void { $this->expectException(QueryException::class); @@ -146,7 +150,7 @@ public function testIterateWithNoDistinctAndWrongSelectClause() $q->iterate(); } - public function testToIterableWithNoDistinctAndWrongSelectClause() : void + public function testToIterableWithNoDistinctAndWrongSelectClause(): void { $this->expectException(QueryException::class); @@ -154,7 +158,7 @@ public function testToIterableWithNoDistinctAndWrongSelectClause() : void $q->toIterable(); } - public function testIterateWithNoDistinctAndWithValidSelectClause() : void + public function testIterateWithNoDistinctAndWithValidSelectClause(): void { $this->expectException(QueryException::class); @@ -162,7 +166,7 @@ public function testIterateWithNoDistinctAndWithValidSelectClause() : void $q->iterate(); } - public function testToIterableWithNoDistinctAndWithValidSelectClause() : void + public function testToIterableWithNoDistinctAndWithValidSelectClause(): void { $this->expectException(QueryException::class); @@ -170,14 +174,14 @@ public function testToIterableWithNoDistinctAndWithValidSelectClause() : void $q->toIterable(); } - public function testIterateWithDistinct() + public function testIterateWithDistinct(): void { - $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()); } - public function testIterateEmptyResult() : void + public function testIterateEmptyResult(): void { $q = $this->_em->createQuery('SELECT u from Doctrine\Tests\Models\CMS\CmsUser u'); @@ -191,7 +195,7 @@ public function testIterateEmptyResult() : void /** * @group DDC-1697 */ - public function testCollectionParameters() + public function testCollectionParameters(): void { $cities = [ 0 => 'Paris', @@ -199,8 +203,8 @@ public function testCollectionParameters() 9 => 'St Julien', ]; - $query = $this->_em - ->createQuery("SELECT a FROM Doctrine\Tests\Models\CMS\CmsAddress a WHERE a.city IN (:cities)") + $query = $this->_em + ->createQuery('SELECT a FROM Doctrine\Tests\Models\CMS\CmsAddress a WHERE a.city IN (:cities)') ->setParameter('cities', $cities); $parameters = $query->getParameters(); @@ -210,7 +214,7 @@ public function testCollectionParameters() $this->assertEquals($cities, $parameter->getValue()); } - public function provideProcessParameterValueIterable() : Generator + public function provideProcessParameterValueIterable(): Generator { $baseArray = [ 0 => 'Paris', @@ -255,19 +259,19 @@ public function testProcessParameterValueWithIterableEntityShouldNotBeTreatedAsI /** * @group DDC-2224 */ - public function testProcessParameterValueClassMetadata() + public function testProcessParameterValueClassMetadata(): void { - $query = $this->_em->createQuery("SELECT a FROM Doctrine\Tests\Models\CMS\CmsAddress a WHERE a.city IN (:cities)"); + $query = $this->_em->createQuery('SELECT a FROM Doctrine\Tests\Models\CMS\CmsAddress a WHERE a.city IN (:cities)'); $this->assertEquals( CmsAddress::class, $query->processParameterValue($this->_em->getClassMetadata(CmsAddress::class)) ); } - public function testProcessParameterValueObject() : void + public function testProcessParameterValueObject(): void { - $query = $this->_em->createQuery('SELECT a FROM Doctrine\Tests\Models\CMS\CmsAddress a WHERE a.user = :user'); - $user = new CmsUser(); + $query = $this->_em->createQuery('SELECT a FROM Doctrine\Tests\Models\CMS\CmsAddress a WHERE a.user = :user'); + $user = new CmsUser(); $user->id = 12345; self::assertSame( @@ -289,16 +293,16 @@ public function testProcessParameterValueValueObjectWithDriverChain(): void self::assertSame($vo, $query->processParameterValue($vo)); } - public function testProcessParameterValueNull() : void + public function testProcessParameterValueNull(): void { $query = $this->_em->createQuery('SELECT a FROM Doctrine\Tests\Models\CMS\CmsAddress a WHERE a.user = :user'); self::assertNull($query->processParameterValue(null)); } - public function testDefaultQueryHints() + public function testDefaultQueryHints(): void { - $config = $this->_em->getConfiguration(); + $config = $this->_em->getConfiguration(); $defaultHints = [ 'hint_name_1' => 'hint_value_1', 'hint_name_2' => 'hint_value_2', @@ -317,19 +321,17 @@ public function testDefaultQueryHints() /** * @group DDC-3714 */ - public function testResultCacheCaching() + public function testResultCacheCaching(): void { $this->_em->getConfiguration()->setResultCacheImpl(new ArrayCache()); $this->_em->getConfiguration()->setQueryCacheImpl(new ArrayCache()); - /** @var DriverConnectionMock $driverConnectionMock */ $driverConnectionMock = $this->_em->getConnection()->getWrappedConnection(); + assert($driverConnectionMock instanceof DriverConnectionMock); $stmt = new StatementArrayMock([ - [ - 'id_0' => 1, - ] + ['id_0' => 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) ->enableResultCache(60) //let it cache @@ -339,7 +341,7 @@ public function testResultCacheCaching() $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) ->disableResultCache() ->getResult(); @@ -349,7 +351,7 @@ public function testResultCacheCaching() /** * @group DDC-3741 */ - public function testSetHydrationCacheProfileNull() + public function testSetHydrationCacheProfileNull(): void { $query = $this->_em->createQuery(); $query->setHydrationCacheProfile(null); @@ -359,16 +361,16 @@ public function testSetHydrationCacheProfileNull() /** * @group 2947 */ - public function testResultCacheEviction() + public function testResultCacheEviction(): void { $this->_em->getConfiguration()->setResultCacheImpl(new ArrayCache()); - $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') ->enableResultCache(); - /** @var DriverConnectionMock $driverConnectionMock */ $driverConnectionMock = $this->_em->getConnection() ->getWrappedConnection(); + assert($driverConnectionMock instanceof DriverConnectionMock); $driverConnectionMock->setStatementMock(new StatementArrayMock([['id_0' => 1]])); @@ -392,9 +394,9 @@ public function testResultCacheEviction() /** * @group #6162 */ - public function testSelectJoinSubquery() + public function testSelectJoinSubquery(): void { - $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'); @@ -404,9 +406,9 @@ public function testSelectJoinSubquery() /** * @group #6162 */ - public function testSelectFromSubquery() + public function testSelectFromSubquery(): void { - $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'); @@ -416,7 +418,7 @@ public function testSelectFromSubquery() /** * @group 6699 */ - public function testGetParameterTypeJuggling() : void + public function testGetParameterTypeJuggling(): void { $query = $this->_em->createQuery('select u from ' . CmsUser::class . ' u where u.id = ?0'); @@ -430,7 +432,7 @@ public function testGetParameterTypeJuggling() : void /** * @group 6699 */ - public function testSetParameterWithNameZeroIsNotOverridden() : void + public function testSetParameterWithNameZeroIsNotOverridden(): void { $query = $this->_em->createQuery('select u from ' . CmsUser::class . ' u where u.id != ?0 and u.username = :name'); @@ -445,7 +447,7 @@ public function testSetParameterWithNameZeroIsNotOverridden() : void /** * @group 6699 */ - public function testSetParameterWithNameZeroDoesNotOverrideAnotherParameter() : void + public function testSetParameterWithNameZeroDoesNotOverrideAnotherParameter(): void { $query = $this->_em->createQuery('select u from ' . CmsUser::class . ' u where u.id != ?0 and u.username = :name'); @@ -460,7 +462,7 @@ public function testSetParameterWithNameZeroDoesNotOverrideAnotherParameter() : /** * @group 6699 */ - public function testSetParameterWithTypeJugglingWorks() : void + public function testSetParameterWithTypeJugglingWorks(): void { $query = $this->_em->createQuery('select u from ' . CmsUser::class . ' u where u.id != ?0 and u.username = :name'); @@ -478,7 +480,7 @@ public function testSetParameterWithTypeJugglingWorks() : void /** * @group 6748 */ - public function testResultCacheProfileCanBeRemovedViaSetter() : void + public function testResultCacheProfileCanBeRemovedViaSetter(): void { $this->_em->getConfiguration()->setResultCacheImpl(new ArrayCache()); @@ -490,7 +492,7 @@ public function testResultCacheProfileCanBeRemovedViaSetter() : void } /** @group 7527 */ - public function testValuesAreNotBeingResolvedForSpecifiedParameterTypes() : void + public function testValuesAreNotBeingResolvedForSpecifiedParameterTypes(): void { $unitOfWork = $this->createMock(UnitOfWork::class); @@ -508,7 +510,7 @@ public function testValuesAreNotBeingResolvedForSpecifiedParameterTypes() : void } /** @group 7982 */ - public function testNonExistentExecutor() + public function testNonExistentExecutor(): void { $this->expectException(QueryException::class); $this->expectExceptionMessage('[Syntax Error] line 0, col -1: Error: Expected SELECT, UPDATE or DELETE, got end of string.'); @@ -519,7 +521,7 @@ public function testNonExistentExecutor() /** * @group 8106 */ - public function testGetParameterColonNormalize() : void + public function testGetParameterColonNormalize(): void { $query = $this->_em->createQuery('select u from ' . CmsUser::class . ' u where u.name = :name'); diff --git a/tests/Doctrine/Tests/ORM/Query/SelectSqlGenerationTest.php b/tests/Doctrine/Tests/ORM/Query/SelectSqlGenerationTest.php index 8286e29108c..52af63b9beb 100644 --- a/tests/Doctrine/Tests/ORM/Query/SelectSqlGenerationTest.php +++ b/tests/Doctrine/Tests/ORM/Query/SelectSqlGenerationTest.php @@ -1,5 +1,7 @@ _em = $this->_getTestEntityManager(); } @@ -34,24 +40,22 @@ protected function setUp() : void /** * Assert a valid SQL generation. * - * @param string $dqlToBeTested - * @param string $sqlToBeConfirmed * @param array $queryHints * @param array $queryParams */ - public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed, array $queryHints = [], array $queryParams = []) + public function assertSqlGeneration(string $dqlToBeTested, string $sqlToBeConfirmed, array $queryHints = [], array $queryParams = []): void { try { $query = $this->_em->createQuery($dqlToBeTested); - foreach ($queryParams AS $name => $value) { + foreach ($queryParams as $name => $value) { $query->setParameter($name, $value); } $query->setHint(ORMQuery::HINT_FORCE_PARTIAL_LOAD, true) ->useQueryCache(false); - foreach ($queryHints AS $name => $value) { + foreach ($queryHints as $name => $value) { $query->setHint($name, $value); } @@ -64,33 +68,31 @@ public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed, array $qu ); $query->free(); - } catch (\Exception $e) { - $this->fail($e->getMessage() ."\n".$e->getTraceAsString()); + } catch (Exception $e) { + $this->fail($e->getMessage() . "\n" . $e->getTraceAsString()); } } /** * Asser an invalid SQL generation. * - * @param string $dqlToBeTested - * @param string $expectedException * @param array $queryHints * @param array $queryParams */ - public function assertInvalidSqlGeneration($dqlToBeTested, $expectedException, array $queryHints = [], array $queryParams = []) + public function assertInvalidSqlGeneration(string $dqlToBeTested, string $expectedException, array $queryHints = [], array $queryParams = []): void { $this->expectException($expectedException); $query = $this->_em->createQuery($dqlToBeTested); - foreach ($queryParams AS $name => $value) { + foreach ($queryParams as $name => $value) { $query->setParameter($name, $value); } $query->setHint(ORMQuery::HINT_FORCE_PARTIAL_LOAD, true) ->useQueryCache(false); - foreach ($queryHints AS $name => $value) { + foreach ($queryHints as $name => $value) { $query->setHint($name, $value); } @@ -104,7 +106,7 @@ public function assertInvalidSqlGeneration($dqlToBeTested, $expectedException, a /** * @group DDC-3697 */ - public function testJoinWithRangeVariablePutsConditionIntoSqlWhereClause() + public function testJoinWithRangeVariablePutsConditionIntoSqlWhereClause(): void { $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', @@ -116,7 +118,7 @@ public function testJoinWithRangeVariablePutsConditionIntoSqlWhereClause() /** * @group DDC-3697 */ - public function testJoinWithRangeVariableAndInheritancePutsConditionIntoSqlWhereClause() + public function testJoinWithRangeVariableAndInheritancePutsConditionIntoSqlWhereClause(): void { /* * Basically like the previous test, but this time load data for the inherited objects as well. @@ -130,7 +132,7 @@ public function testJoinWithRangeVariableAndInheritancePutsConditionIntoSqlWhere ); } - public function testSupportsSelectForAllFields() + public function testSupportsSelectForAllFields(): void { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', @@ -138,7 +140,7 @@ public function testSupportsSelectForAllFields() ); } - public function testSupportsSelectForOneField() + public function testSupportsSelectForOneField(): void { $this->assertSqlGeneration( 'SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u', @@ -146,7 +148,7 @@ public function testSupportsSelectForOneField() ); } - public function testSupportsSelectForOneNestedField() + public function testSupportsSelectForOneNestedField(): void { $this->assertSqlGeneration( 'SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsArticle a JOIN a.user u', @@ -154,7 +156,7 @@ public function testSupportsSelectForOneNestedField() ); } - public function testSupportsSelectForAllNestedField() + public function testSupportsSelectForAllNestedField(): void { $this->assertSqlGeneration( 'SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a JOIN a.user u ORDER BY u.name ASC', @@ -162,7 +164,7 @@ public function testSupportsSelectForAllNestedField() ); } - public function testNotExistsExpression() + public function testNotExistsExpression(): void { $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)', @@ -170,7 +172,7 @@ public function testNotExistsExpression() ); } - public function testSupportsSelectForMultipleColumnsOfASingleComponent() + public function testSupportsSelectForMultipleColumnsOfASingleComponent(): void { $this->assertSqlGeneration( 'SELECT u.username, u.name FROM Doctrine\Tests\Models\CMS\CmsUser u', @@ -178,7 +180,7 @@ public function testSupportsSelectForMultipleColumnsOfASingleComponent() ); } - public function testSupportsSelectUsingMultipleFromComponents() + public function testSupportsSelectUsingMultipleFromComponents(): void { $this->assertSqlGeneration( 'SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE u = p.user', @@ -186,7 +188,7 @@ public function testSupportsSelectUsingMultipleFromComponents() ); } - public function testSupportsJoinOnMultipleComponents() + public function testSupportsJoinOnMultipleComponents(): void { $this->assertSqlGeneration( 'SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN Doctrine\Tests\Models\CMS\CmsPhonenumber p WITH u = p.user', @@ -194,7 +196,7 @@ public function testSupportsJoinOnMultipleComponents() ); } - public function testSupportsJoinOnMultipleComponentsWithJoinedInheritanceType() + public function testSupportsJoinOnMultipleComponentsWithJoinedInheritanceType(): void { $this->assertSqlGeneration( 'SELECT e FROM Doctrine\Tests\Models\Company\CompanyEmployee e JOIN Doctrine\Tests\Models\Company\CompanyManager m WITH e.id = m.id', @@ -212,7 +214,7 @@ public function testSupportsJoinOnMultipleComponentsWithJoinedInheritanceType() ); } - public function testSupportsSelectWithCollectionAssociationJoin() + public function testSupportsSelectWithCollectionAssociationJoin(): void { $this->assertSqlGeneration( 'SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.phonenumbers p', @@ -220,7 +222,7 @@ public function testSupportsSelectWithCollectionAssociationJoin() ); } - public function testSupportsSelectWithSingleValuedAssociationJoin() + public function testSupportsSelectWithSingleValuedAssociationJoin(): void { $this->assertSqlGeneration( 'SELECT u, a FROM Doctrine\Tests\Models\Forum\ForumUser u JOIN u.avatar a', @@ -228,7 +230,7 @@ public function testSupportsSelectWithSingleValuedAssociationJoin() ); } - public function testSelectCorrelatedSubqueryComplexMathematicalExpression() + public function testSelectCorrelatedSubqueryComplexMathematicalExpression(): void { $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', @@ -236,7 +238,7 @@ public function testSelectCorrelatedSubqueryComplexMathematicalExpression() ); } - public function testSelectComplexMathematicalExpression() + public function testSelectComplexMathematicalExpression(): void { $this->assertSqlGeneration( 'SELECT (count(p.phonenumber)+5)*10 FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p JOIN p.user ui WHERE ui.id = ?1', @@ -258,7 +260,7 @@ public function testSingleAssociationPathExpressionInSubselect() /** * @group DDC-1077 */ - public function testConstantValueInSelect() + public function testConstantValueInSelect(): void { $this->assertSqlGeneration( "SELECT u.name, 'foo' AS bar FROM Doctrine\Tests\Models\CMS\CmsUser u", @@ -266,7 +268,7 @@ public function testConstantValueInSelect() ); } - public function testSupportsOrderByWithAscAsDefault() + public function testSupportsOrderByWithAscAsDefault(): void { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u ORDER BY u.id', @@ -274,7 +276,7 @@ public function testSupportsOrderByWithAscAsDefault() ); } - public function testSupportsOrderByAsc() + public function testSupportsOrderByAsc(): void { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u ORDER BY u.id asc', @@ -282,7 +284,7 @@ public function testSupportsOrderByAsc() ); } - public function testSupportsOrderByDesc() + public function testSupportsOrderByDesc(): void { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u ORDER BY u.id desc', @@ -290,7 +292,7 @@ public function testSupportsOrderByDesc() ); } - public function testSupportsOrderByWithSimpleArithmeticExpression() : void + public function testSupportsOrderByWithSimpleArithmeticExpression(): void { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u ORDER BY LENGTH(u.username) + LENGTH(u.username) asc', @@ -298,7 +300,7 @@ public function testSupportsOrderByWithSimpleArithmeticExpression() : void ); } - public function testSupportsSelectDistinct() + public function testSupportsSelectDistinct(): void { $this->assertSqlGeneration( 'SELECT DISTINCT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u', @@ -306,7 +308,7 @@ public function testSupportsSelectDistinct() ); } - public function testSupportsAggregateFunctionInSelectedFields() + public function testSupportsAggregateFunctionInSelectedFields(): void { $this->assertSqlGeneration( 'SELECT COUNT(u.id) FROM Doctrine\Tests\Models\CMS\CmsUser u GROUP BY u.id', @@ -314,7 +316,7 @@ public function testSupportsAggregateFunctionInSelectedFields() ); } - public function testSupportsAggregateFunctionWithSimpleArithmetic() + public function testSupportsAggregateFunctionWithSimpleArithmetic(): void { $this->assertSqlGeneration( 'SELECT MAX(u.id + 4) * 2 FROM Doctrine\Tests\Models\CMS\CmsUser u', @@ -325,9 +327,9 @@ public function testSupportsAggregateFunctionWithSimpleArithmetic() /** * @group DDC-3276 */ - public function testSupportsAggregateCountFunctionWithSimpleArithmetic() + public function testSupportsAggregateCountFunctionWithSimpleArithmetic(): void { - $connMock = $this->_em->getConnection(); + $connMock = $this->_em->getConnection(); $orgPlatform = $connMock->getDatabasePlatform(); $connMock->setDatabasePlatform(new MySqlPlatform()); @@ -340,7 +342,7 @@ public function testSupportsAggregateCountFunctionWithSimpleArithmetic() $connMock->setDatabasePlatform($orgPlatform); } - public function testSupportsWhereClauseWithPositionalParameter() + public function testSupportsWhereClauseWithPositionalParameter(): void { $this->assertSqlGeneration( 'select u from Doctrine\Tests\Models\Forum\ForumUser u where u.id = ?1', @@ -348,7 +350,7 @@ public function testSupportsWhereClauseWithPositionalParameter() ); } - public function testSupportsWhereClauseWithNamedParameter() + public function testSupportsWhereClauseWithNamedParameter(): void { $this->assertSqlGeneration( 'select u from Doctrine\Tests\Models\Forum\ForumUser u where u.username = :name', @@ -356,7 +358,7 @@ public function testSupportsWhereClauseWithNamedParameter() ); } - public function testSupportsWhereAndClauseWithNamedParameters() + public function testSupportsWhereAndClauseWithNamedParameters(): void { $this->assertSqlGeneration( 'select u from Doctrine\Tests\Models\Forum\ForumUser u where u.username = :name and u.username = :name2', @@ -364,7 +366,7 @@ public function testSupportsWhereAndClauseWithNamedParameters() ); } - public function testSupportsCombinedWhereClauseWithNamedParameter() + public function testSupportsCombinedWhereClauseWithNamedParameter(): void { $this->assertSqlGeneration( 'select u from Doctrine\Tests\Models\Forum\ForumUser u where (u.username = :name OR u.username = :name2) AND u.id = :id', @@ -372,7 +374,7 @@ public function testSupportsCombinedWhereClauseWithNamedParameter() ); } - public function testSupportsAggregateFunctionInASelectDistinct() + public function testSupportsAggregateFunctionInASelectDistinct(): void { $this->assertSqlGeneration( 'SELECT COUNT(DISTINCT u.name) FROM Doctrine\Tests\Models\CMS\CmsUser u', @@ -381,7 +383,7 @@ public function testSupportsAggregateFunctionInASelectDistinct() } // Ticket #668 - public function testSupportsASqlKeywordInAStringLiteralParam() + public function testSupportsASqlKeywordInAStringLiteralParam(): void { $this->assertSqlGeneration( "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name LIKE '%foo OR bar%'", @@ -389,7 +391,7 @@ public function testSupportsASqlKeywordInAStringLiteralParam() ); } - public function testSupportsArithmeticExpressionsInWherePart() + public function testSupportsArithmeticExpressionsInWherePart(): void { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE ((u.id + 5000) * u.id + 3) < 10000000', @@ -397,7 +399,7 @@ public function testSupportsArithmeticExpressionsInWherePart() ); } - public function testSupportsMultipleEntitiesInFromClause() + public function testSupportsMultipleEntitiesInFromClause(): void { $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', @@ -405,7 +407,7 @@ public function testSupportsMultipleEntitiesInFromClause() ); } - public function testSupportsMultipleEntitiesInFromClauseUsingPathExpression() + public function testSupportsMultipleEntitiesInFromClauseUsingPathExpression(): void { $this->assertSqlGeneration( 'SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsArticle a WHERE u.id = a.user', @@ -413,7 +415,7 @@ public function testSupportsMultipleEntitiesInFromClauseUsingPathExpression() ); } - public function testSupportsPlainJoinWithoutClause() + public function testSupportsPlainJoinWithoutClause(): void { $this->assertSqlGeneration( 'SELECT u.id, a.id from Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a', @@ -428,7 +430,7 @@ public function testSupportsPlainJoinWithoutClause() /** * @group DDC-135 */ - public function testSupportsJoinAndWithClauseRestriction() + public function testSupportsJoinAndWithClauseRestriction(): void { $this->assertSqlGeneration( "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a WITH a.topic LIKE '%foo%'", @@ -444,7 +446,7 @@ public function testSupportsJoinAndWithClauseRestriction() * @group DDC-135 * @group DDC-177 */ - public function testJoinOnClause_NotYetSupported_ThrowsException() + public function testJoinOnClause_NotYetSupported_ThrowsException(): void { $this->expectException(QueryException::class); @@ -453,7 +455,7 @@ public function testJoinOnClause_NotYetSupported_ThrowsException() )->getSql(); } - public function testSupportsMultipleJoins() + public function testSupportsMultipleJoins(): void { $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', @@ -461,7 +463,7 @@ public function testSupportsMultipleJoins() ); } - public function testSupportsTrimFunction() + public function testSupportsTrimFunction(): void { $this->assertSqlGeneration( "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE TRIM(TRAILING ' ' FROM u.name) = 'someone'", @@ -472,7 +474,7 @@ public function testSupportsTrimFunction() /** * @group DDC-2668 */ - public function testSupportsTrimLeadingZeroString() + public function testSupportsTrimLeadingZeroString(): void { $this->assertSqlGeneration( "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE TRIM(TRAILING '0' FROM u.name) != ''", @@ -481,26 +483,26 @@ public function testSupportsTrimLeadingZeroString() } // Ticket 894 - public function testSupportsBetweenClauseWithPositionalParameters() + public function testSupportsBetweenClauseWithPositionalParameters(): void { $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 c0_.name AS name_0 FROM cms_users c0_ WHERE c0_.id BETWEEN ? AND ?' ); } /** * @group DDC-1802 */ - public function testSupportsNotBetweenForSizeFunction() + public function testSupportsNotBetweenForSizeFunction(): void { $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 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 ?' ); } - public function testSupportsFunctionalExpressionsInWherePart() + public function testSupportsFunctionalExpressionsInWherePart(): void { $this->assertSqlGeneration( "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE TRIM(u.name) = 'someone'", @@ -510,19 +512,19 @@ public function testSupportsFunctionalExpressionsInWherePart() ); } - public function testSupportsInstanceOfExpressionsInWherePart() + public function testSupportsInstanceOfExpressionsInWherePart(): void { $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF Doctrine\Tests\Models\Company\CompanyEmployee", + '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 ('manager', 'employee')" ); } - public function testSupportsInstanceOfExpressionInWherePartWithMultipleValues() + public function testSupportsInstanceOfExpressionInWherePartWithMultipleValues(): void { // 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 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 ('manager', 'employee')" ); } @@ -530,10 +532,10 @@ public function testSupportsInstanceOfExpressionInWherePartWithMultipleValues() /** * @group DDC-1194 */ - public function testSupportsInstanceOfExpressionsInWherePartPrefixedSlash() + public function testSupportsInstanceOfExpressionsInWherePartPrefixedSlash(): void { $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF \Doctrine\Tests\Models\Company\CompanyEmployee", + '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 ('manager', 'employee')" ); } @@ -541,49 +543,50 @@ public function testSupportsInstanceOfExpressionsInWherePartPrefixedSlash() /** * @group DDC-1194 */ - public function testSupportsInstanceOfExpressionsInWherePartWithUnrelatedClass() + public function testSupportsInstanceOfExpressionsInWherePartWithUnrelatedClass(): void { $this->assertInvalidSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF \Doctrine\Tests\Models\CMS\CmsUser", + 'SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF \Doctrine\Tests\Models\CMS\CmsUser', QueryException::class ); } - public function testSupportsInstanceOfExpressionsInWherePartInDeeperLevel() + public function testSupportsInstanceOfExpressionsInWherePartInDeeperLevel(): void { $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\Company\CompanyEmployee u WHERE u INSTANCE OF Doctrine\Tests\Models\Company\CompanyManager", + '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')" ); } - public function testSupportsInstanceOfExpressionsInWherePartInDeepestLevel() + public function testSupportsInstanceOfExpressionsInWherePartInDeepestLevel(): void { $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\Company\CompanyManager u WHERE u INSTANCE OF Doctrine\Tests\Models\Company\CompanyManager", + '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')" ); } - public function testSupportsInstanceOfExpressionsUsingInputParameterInWherePart() + public function testSupportsInstanceOfExpressionsUsingInputParameterInWherePart(): void { $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 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)] ); } // Ticket #973 - public function testSupportsSingleValuedInExpressionWithoutSpacesInWherePart() + public function testSupportsSingleValuedInExpressionWithoutSpacesInWherePart(): void { $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 c0_.name AS name_0 FROM cms_users c0_ WHERE c0_.email_id IN (46)' ); } - public function testSupportsMultipleValuedInExpressionInWherePart() + public function testSupportsMultipleValuedInExpressionInWherePart(): void { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id IN (1, 2)', @@ -591,7 +594,7 @@ public function testSupportsMultipleValuedInExpressionInWherePart() ); } - public function testSupportsNotInExpressionInWherePart() + public function testSupportsNotInExpressionInWherePart(): void { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE :id NOT IN (1)', @@ -602,15 +605,15 @@ public function testSupportsNotInExpressionInWherePart() /** * @group DDC-1802 */ - public function testSupportsNotInExpressionForModFunction() + public function testSupportsNotInExpressionForModFunction(): void { $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 c0_.name AS name_0 FROM cms_users c0_ WHERE MOD(c0_.id, 5) NOT IN (1, 3, 4)' ); } - public function testInExpressionWithSingleValuedAssociationPathExpressionInWherePart() + public function testInExpressionWithSingleValuedAssociationPathExpressionInWherePart(): void { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u WHERE u.avatar IN (?1, ?2)', @@ -618,18 +621,18 @@ public function testInExpressionWithSingleValuedAssociationPathExpressionInWhere ); } - public function testInvalidInExpressionWithSingleValuedAssociationPathExpressionOnInverseSide() + public function testInvalidInExpressionWithSingleValuedAssociationPathExpressionOnInverseSide(): void { // 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)", + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.address IN (?1, ?2)', QueryException::class ); } - public function testSupportsConcatFunctionForMysqlAndPostgresql() + public function testSupportsConcatFunctionForMysqlAndPostgresql(): void { - $connMock = $this->_em->getConnection(); + $connMock = $this->_em->getConnection(); $orgPlatform = $connMock->getDatabasePlatform(); $connMock->setDatabasePlatform(new MySqlPlatform()); @@ -638,8 +641,8 @@ public function testSupportsConcatFunctionForMysqlAndPostgresql() "SELECT c0_.id AS id_0 FROM cms_users c0_ WHERE CONCAT(c0_.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(c0_.id, c0_.name) AS sclr_0 FROM cms_users c0_ WHERE c0_.id = ?' ); $connMock->setDatabasePlatform(new PostgreSqlPlatform()); @@ -648,14 +651,14 @@ public function testSupportsConcatFunctionForMysqlAndPostgresql() "SELECT c0_.id AS id_0 FROM cms_users c0_ WHERE c0_.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 c0_.id || c0_.name AS sclr_0 FROM cms_users c0_ WHERE c0_.id = ?' ); $connMock->setDatabasePlatform($orgPlatform); } - public function testSupportsExistsExpressionInWherePartWithCorrelatedSubquery() + public function testSupportsExistsExpressionInWherePartWithCorrelatedSubquery(): void { $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)', @@ -666,7 +669,7 @@ public function testSupportsExistsExpressionInWherePartWithCorrelatedSubquery() /** * @group DDC-593 */ - public function testSubqueriesInComparisonExpression() + public function testSubqueriesInComparisonExpression(): void { $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))', @@ -674,13 +677,13 @@ public function testSubqueriesInComparisonExpression() ); } - public function testSupportsMemberOfExpressionOneToMany() + public function testSupportsMemberOfExpressionOneToMany(): void { // "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->setHint(ORMQuery::HINT_FORCE_PARTIAL_LOAD, true); - $phone = new CmsPhonenumber(); + $phone = new CmsPhonenumber(); $phone->phonenumber = 101; $q->setParameter('param', $phone); @@ -690,13 +693,13 @@ public function testSupportsMemberOfExpressionOneToMany() ); } - public function testSupportsMemberOfExpressionManyToMany() + public function testSupportsMemberOfExpressionManyToMany(): void { // "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->setHint(ORMQuery::HINT_FORCE_PARTIAL_LOAD, true); - $group = new CmsGroup(); + $group = new CmsGroup(); $group->id = 101; $q->setParameter('param', $group); @@ -706,14 +709,14 @@ public function testSupportsMemberOfExpressionManyToMany() ); } - public function testSupportsMemberOfExpressionManyToManyParameterArray() + public function testSupportsMemberOfExpressionManyToManyParameterArray(): void { $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; - $group2 = new CmsGroup(); + $group = new CmsGroup(); + $group->id = 101; + $group2 = new CmsGroup(); $group2->id = 105; $q->setParameter('param', [$group, $group2]); @@ -723,11 +726,11 @@ public function testSupportsMemberOfExpressionManyToManyParameterArray() ); } - public function testSupportsMemberOfExpressionSelfReferencing() + public function testSupportsMemberOfExpressionSelfReferencing(): void { // "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]); $q->setParameter('param', $person); @@ -737,7 +740,7 @@ public function testSupportsMemberOfExpressionSelfReferencing() ); } - public function testSupportsMemberOfWithSingleValuedAssociation() + public function testSupportsMemberOfWithSingleValuedAssociation(): void { // 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'); @@ -748,7 +751,7 @@ public function testSupportsMemberOfWithSingleValuedAssociation() ); } - public function testSupportsMemberOfWithIdentificationVariable() + public function testSupportsMemberOfWithIdentificationVariable(): void { // 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'); @@ -759,28 +762,28 @@ public function testSupportsMemberOfWithIdentificationVariable() ); } - public function testSupportsCurrentDateFunction() + public function testSupportsCurrentDateFunction(): void { $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()); } - public function testSupportsCurrentTimeFunction() + public function testSupportsCurrentTimeFunction(): void { $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()); } - public function testSupportsCurrentTimestampFunction() + public function testSupportsCurrentTimestampFunction(): void { $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()); } - public function testExistsExpressionInWhereCorrelatedSubqueryAssocCondition() + public function testExistsExpressionInWhereCorrelatedSubqueryAssocCondition(): void { $this->assertSqlGeneration( // DQL @@ -798,7 +801,7 @@ public function testExistsExpressionInWhereCorrelatedSubqueryAssocCondition() ); } - public function testExistsExpressionWithSimpleSelectReturningScalar() + public function testExistsExpressionWithSimpleSelectReturningScalar(): void { $this->assertSqlGeneration( // DQL @@ -816,7 +819,7 @@ public function testExistsExpressionWithSimpleSelectReturningScalar() ); } - public function testLimitFromQueryClass() + public function testLimitFromQueryClass(): void { $q = $this->_em ->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u') @@ -825,7 +828,7 @@ public function testLimitFromQueryClass() $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()); } - public function testLimitAndOffsetFromQueryClass() + public function testLimitAndOffsetFromQueryClass(): void { $q = $this->_em ->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u') @@ -842,141 +845,141 @@ public function testLimitAndOffsetFromQueryClass() ); } - public function testSizeFunction() + public function testSizeFunction(): void { $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 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' ); } - public function testSizeFunctionSupportsManyToMany() + public function testSizeFunctionSupportsManyToMany(): void { $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 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' ); } - public function testEmptyCollectionComparisonExpression() + public function testEmptyCollectionComparisonExpression(): void { $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 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' ); $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 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' ); } - public function testNestedExpressions() + public function testNestedExpressions(): void { $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 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)' ); } - public function testNestedExpressions2() + public function testNestedExpressions2(): void { $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 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' ); } - public function testNestedExpressions3() + public function testNestedExpressions3(): void { $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 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))' ); } - public function testOrderByCollectionAssociationSize() + public function testOrderByCollectionAssociationSize(): void { $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 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' ); } - public function testOrderBySupportsSingleValuedPathExpressionOwningSide() + public function testOrderBySupportsSingleValuedPathExpressionOwningSide(): void { $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 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' ); } - public function testOrderBySupportsSingleValuedPathExpressionInverseSide() + public function testOrderBySupportsSingleValuedPathExpressionInverseSide(): void { $this->expectException('\Doctrine\ORM\Query\QueryException'); - $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() + public function testBooleanLiteralInWhereOnSqlite(): void { $oldPlat = $this->_em->getConnection()->getDatabasePlatform(); $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 b0_.id AS id_0, b0_.booleanField AS booleanField_1 FROM boolean_model b0_ WHERE b0_.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 b0_.id AS id_0, b0_.booleanField AS booleanField_1 FROM boolean_model b0_ WHERE b0_.booleanField = 0' ); $this->_em->getConnection()->setDatabasePlatform($oldPlat); } - public function testBooleanLiteralInWhereOnPostgres() + public function testBooleanLiteralInWhereOnPostgres(): void { $oldPlat = $this->_em->getConnection()->getDatabasePlatform(); $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 b0_.id AS id_0, b0_.booleanField AS booleanfield_1 FROM boolean_model b0_ WHERE b0_.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 b0_.id AS id_0, b0_.booleanField AS booleanfield_1 FROM boolean_model b0_ WHERE b0_.booleanField = false' ); $this->_em->getConnection()->setDatabasePlatform($oldPlat); } - public function testSingleValuedAssociationFieldInWhere() + public function testSingleValuedAssociationFieldInWhere(): void { $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 c0_.phonenumber AS phonenumber_0 FROM cms_phonenumbers c0_ WHERE c0_.user_id = ?' ); } - public function testSingleValuedAssociationNullCheckOnOwningSide() + public function testSingleValuedAssociationNullCheckOnOwningSide(): void { $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 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' ); } // 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" // where the CmsUser is the inverse side is not supported. - public function testSingleValuedAssociationNullCheckOnInverseSide() + public function testSingleValuedAssociationNullCheckOnInverseSide(): void { $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 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' ); } @@ -984,15 +987,15 @@ public function testSingleValuedAssociationNullCheckOnInverseSide() * @group DDC-339 * @group DDC-1572 */ - public function testStringFunctionLikeExpression() + public function testStringFunctionLikeExpression(): void { $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%'" ); $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 c0_.name AS name_0 FROM cms_users c0_ WHERE LOWER(c0_.name) LIKE ?' ); $this->assertSqlGeneration( "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE CONCAT(UPPER(u.name), '_moo') LIKE :str", @@ -1001,52 +1004,52 @@ public function testStringFunctionLikeExpression() // 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 c0_.name AS name_0 FROM cms_users c0_ WHERE UPPER(c0_.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 c0_.name AS name_0 FROM cms_users c0_ WHERE UPPER(LOWER(c0_.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 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)' ); } /** * @group DDC-1802 */ - public function testStringFunctionNotLikeExpression() + public function testStringFunctionNotLikeExpression(): void { $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 c0_.name AS name_0 FROM cms_users c0_ WHERE LOWER(c0_.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 c0_.name AS name_0 FROM cms_users c0_ WHERE UPPER(LOWER(c0_.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 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)' ); } /** * @group DDC-338 */ - public function testOrderedCollectionFetchJoined() + public function testOrderedCollectionFetchJoined(): void { $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 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' ); } - public function testSubselectInSelect() + public function testSubselectInSelect(): void { $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'", @@ -1058,7 +1061,7 @@ public function testSubselectInSelect() * @group locking * @group DDC-178 */ - public function testPessimisticWriteLockQueryHint() + public function testPessimisticWriteLockQueryHint(): void { if ($this->_em->getConnection()->getDatabasePlatform() instanceof SqlitePlatform) { $this->markTestSkipped('SqLite does not support Row locking at all.'); @@ -1066,7 +1069,7 @@ public function testPessimisticWriteLockQueryHint() $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 ". + '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", [ORMQuery::HINT_LOCK_MODE => LockMode::PESSIMISTIC_WRITE] ); @@ -1076,13 +1079,13 @@ public function testPessimisticWriteLockQueryHint() * @group locking * @group DDC-178 */ - public function testPessimisticReadLockQueryHintPostgreSql() + public function testPessimisticReadLockQueryHintPostgreSql(): void { $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 ". + '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", [ORMQuery::HINT_LOCK_MODE => LockMode::PESSIMISTIC_READ] ); @@ -1092,11 +1095,11 @@ public function testPessimisticReadLockQueryHintPostgreSql() * @group DDC-1693 * @group locking */ - public function testLockModeNoneQueryHint() + public function testLockModeNoneQueryHint(): void { $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 ". + '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'", [ORMQuery::HINT_LOCK_MODE => LockMode::NONE] ); @@ -1105,11 +1108,11 @@ public function testLockModeNoneQueryHint() /** * @group DDC-430 */ - public function testSupportSelectWithMoreThan10InputParameters() + public function testSupportSelectWithMoreThan10InputParameters(): void { $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 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 = ?' ); } @@ -1117,13 +1120,13 @@ public function testSupportSelectWithMoreThan10InputParameters() * @group locking * @group DDC-178 */ - public function testPessimisticReadLockQueryHintMySql() + public function testPessimisticReadLockQueryHintMySql(): void { $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 ". + '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", [ORMQuery::HINT_LOCK_MODE => LockMode::PESSIMISTIC_READ] ); @@ -1133,13 +1136,13 @@ public function testPessimisticReadLockQueryHintMySql() * @group locking * @group DDC-178 */ - public function testPessimisticReadLockQueryHintOracle() + public function testPessimisticReadLockQueryHintOracle(): void { $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 ". + '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", [ORMQuery::HINT_LOCK_MODE => LockMode::PESSIMISTIC_READ] ); @@ -1148,7 +1151,7 @@ public function testPessimisticReadLockQueryHintOracle() /** * @group DDC-431 */ - public function testSupportToCustomDQLFunctions() + public function testSupportToCustomDQLFunctions(): void { $config = $this->_em->getConfiguration(); $config->addCustomNumericFunction('MYABS', MyAbsFunction::class); @@ -1164,7 +1167,7 @@ public function testSupportToCustomDQLFunctions() /** * @group DDC-826 */ - public function testMappedSuperclassAssociationJoin() + public function testMappedSuperclassAssociationJoin(): void { $this->assertSqlGeneration( 'SELECT f FROM Doctrine\Tests\Models\DirectoryTree\File f JOIN f.parentDirectory d WHERE f.id = ?1', @@ -1175,7 +1178,7 @@ public function testMappedSuperclassAssociationJoin() /** * @group DDC-1053 */ - public function testGroupBy() + public function testGroupBy(): void { $this->assertSqlGeneration( 'SELECT g.id, count(u.id) FROM Doctrine\Tests\Models\CMS\CmsGroup g JOIN g.users u GROUP BY g.id', @@ -1186,7 +1189,7 @@ public function testGroupBy() /** * @group DDC-1053 */ - public function testGroupByIdentificationVariable() + public function testGroupByIdentificationVariable(): void { $this->assertSqlGeneration( 'SELECT g, count(u.id) FROM Doctrine\Tests\Models\CMS\CmsGroup g JOIN g.users u GROUP BY g', @@ -1194,15 +1197,15 @@ public function testGroupByIdentificationVariable() ); } - public function testCaseContainingNullIf() + public function testCaseContainingNullIf(): void { $this->assertSqlGeneration( - "SELECT NULLIF(g.id, g.name) AS NullIfEqual FROM Doctrine\Tests\Models\CMS\CmsGroup g", + '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_' ); } - public function testCaseContainingCoalesce() + public function testCaseContainingCoalesce(): void { $this->assertSqlGeneration( "SELECT COALESCE(NULLIF(u.name, ''), u.username) as Display FROM Doctrine\Tests\Models\CMS\CmsUser u", @@ -1213,82 +1216,81 @@ public function testCaseContainingCoalesce() /** * Test that the right discriminator data is inserted in a subquery. */ - public function testSubSelectDiscriminator() + public function testSubSelectDiscriminator(): void { $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 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_" ); } - public function testIdVariableResultVariableReuse() + public function testIdVariableResultVariableReuse(): void { $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(); - } catch (\Exception $e) { + } catch (Exception $e) { $exceptionThrown = true; } $this->assertTrue($exceptionThrown); - } - public function testSubSelectAliasesFromOuterQuery() + public function testSubSelectAliasesFromOuterQuery(): void { $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 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_' ); } - public function testSubSelectAliasesFromOuterQueryWithSubquery() + public function testSubSelectAliasesFromOuterQueryWithSubquery(): void { $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 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_' ); } - public function testSubSelectAliasesFromOuterQueryReuseInWhereClause() + public function testSubSelectAliasesFromOuterQueryReuseInWhereClause(): void { $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 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 = ?' ); } /** * @group DDC-1298 */ - public function testSelectForeignKeyPKWithoutFields() + public function testSelectForeignKeyPKWithoutFields(): void { $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 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' ); } - public function testGeneralCaseWithSingleWhenClause() + public function testGeneralCaseWithSingleWhenClause(): void { $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 c0_.id AS id_0, CASE WHEN ((c0_.id / 2) > 18) THEN 1 ELSE 0 END AS sclr_1 FROM cms_groups c0_' ); } - public function testGeneralCaseWithMultipleWhenClause() + public function testGeneralCaseWithMultipleWhenClause(): void { $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 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_' ); } - public function testSimpleCaseWithSingleWhenClause() + public function testSimpleCaseWithSingleWhenClause(): void { $this->assertSqlGeneration( "SELECT g FROM Doctrine\Tests\Models\CMS\CmsGroup g WHERE g.id = CASE g.name WHEN 'admin' THEN 1 ELSE 2 END", @@ -1296,7 +1298,7 @@ public function testSimpleCaseWithSingleWhenClause() ); } - public function testSimpleCaseWithMultipleWhenClause() + public function testSimpleCaseWithMultipleWhenClause(): void { $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)", @@ -1304,23 +1306,23 @@ public function testSimpleCaseWithMultipleWhenClause() ); } - public function testGeneralCaseWithSingleWhenClauseInSubselect() + public function testGeneralCaseWithSingleWhenClauseInSubselect(): void { $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 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_)' ); } - public function testGeneralCaseWithMultipleWhenClauseInSubselect() + public function testGeneralCaseWithMultipleWhenClauseInSubselect(): void { $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 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_)' ); } - public function testSimpleCaseWithSingleWhenClauseInSubselect() + public function testSimpleCaseWithSingleWhenClauseInSubselect(): void { $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)", @@ -1328,7 +1330,7 @@ public function testSimpleCaseWithSingleWhenClauseInSubselect() ); } - public function testSimpleCaseWithMultipleWhenClauseInSubselect() + public function testSimpleCaseWithMultipleWhenClauseInSubselect(): void { $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)", @@ -1339,7 +1341,7 @@ public function testSimpleCaseWithMultipleWhenClauseInSubselect() /** * @group DDC-1696 */ - public function testSimpleCaseWithStringPrimary() + public function testSimpleCaseWithStringPrimary(): void { $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", @@ -1350,7 +1352,7 @@ public function testSimpleCaseWithStringPrimary() /** * @group DDC-2205 */ - public function testCaseNegativeValuesInThenExpression() + public function testCaseNegativeValuesInThenExpression(): void { $this->assertSqlGeneration( "SELECT CASE g.name WHEN 'admin' THEN - 1 ELSE - 2 END FROM Doctrine\Tests\Models\CMS\CmsGroup g", @@ -1378,21 +1380,21 @@ public function testCaseNegativeValuesInThenExpression() ); } - public function testIdentityFunctionWithCompositePrimaryKey() + public function testIdentityFunctionWithCompositePrimaryKey(): void { $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 n0_.poi_long AS sclr_0 FROM navigation_photos n0_' ); $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 n0_.poi_lat AS sclr_0 FROM navigation_photos n0_' ); $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 n0_.poi_long AS sclr_0, n0_.poi_lat AS sclr_1 FROM navigation_photos n0_' ); $this->assertInvalidSqlGeneration( @@ -1404,15 +1406,15 @@ public function testIdentityFunctionWithCompositePrimaryKey() /** * @group DDC-2519 */ - public function testPartialWithAssociationIdentifier() + public function testPartialWithAssociationIdentifier(): void { $this->assertSqlGeneration( - "SELECT PARTIAL l.{_source, _target} FROM Doctrine\Tests\Models\Legacy\LegacyUserReference l", + '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_' ); $this->assertSqlGeneration( - "SELECT PARTIAL l.{_description, _source, _target} FROM Doctrine\Tests\Models\Legacy\LegacyUserReference l", + '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_' ); } @@ -1420,15 +1422,15 @@ public function testPartialWithAssociationIdentifier() /** * @group DDC-1339 */ - public function testIdentityFunctionInSelectClause() + public function testIdentityFunctionInSelectClause(): void { $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 c0_.email_id AS sclr_0 FROM cms_users c0_' ); } - public function testIdentityFunctionInJoinedSubclass() + public function testIdentityFunctionInJoinedSubclass(): void { //relation is in the subclass (CompanyManager) we are querying $this->assertSqlGeneration( @@ -1446,10 +1448,10 @@ public function testIdentityFunctionInJoinedSubclass() /** * @group DDC-1339 */ - public function testIdentityFunctionDoesNotAcceptStateField() + public function testIdentityFunctionDoesNotAcceptStateField(): void { $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 ); } @@ -1457,7 +1459,7 @@ public function testIdentityFunctionDoesNotAcceptStateField() /** * @group DDC-1389 */ - public function testInheritanceTypeJoinInRootClassWithDisabledForcePartialLoad() + public function testInheritanceTypeJoinInRootClassWithDisabledForcePartialLoad(): void { $this->assertSqlGeneration( 'SELECT p FROM Doctrine\Tests\Models\Company\CompanyPerson p', @@ -1469,7 +1471,7 @@ public function testInheritanceTypeJoinInRootClassWithDisabledForcePartialLoad() /** * @group DDC-1389 */ - public function testInheritanceTypeJoinInRootClassWithEnabledForcePartialLoad() + public function testInheritanceTypeJoinInRootClassWithEnabledForcePartialLoad(): void { $this->assertSqlGeneration( 'SELECT p FROM Doctrine\Tests\Models\Company\CompanyPerson p', @@ -1481,7 +1483,7 @@ public function testInheritanceTypeJoinInRootClassWithEnabledForcePartialLoad() /** * @group DDC-1389 */ - public function testInheritanceTypeJoinInChildClassWithDisabledForcePartialLoad() + public function testInheritanceTypeJoinInChildClassWithDisabledForcePartialLoad(): void { $this->assertSqlGeneration( 'SELECT e FROM Doctrine\Tests\Models\Company\CompanyEmployee e', @@ -1493,7 +1495,7 @@ public function testInheritanceTypeJoinInChildClassWithDisabledForcePartialLoad( /** * @group DDC-1389 */ - public function testInheritanceTypeJoinInChildClassWithEnabledForcePartialLoad() + public function testInheritanceTypeJoinInChildClassWithEnabledForcePartialLoad(): void { $this->assertSqlGeneration( 'SELECT e FROM Doctrine\Tests\Models\Company\CompanyEmployee e', @@ -1505,7 +1507,7 @@ public function testInheritanceTypeJoinInChildClassWithEnabledForcePartialLoad() /** * @group DDC-1389 */ - public function testInheritanceTypeJoinInLeafClassWithDisabledForcePartialLoad() + public function testInheritanceTypeJoinInLeafClassWithDisabledForcePartialLoad(): void { $this->assertSqlGeneration( 'SELECT m FROM Doctrine\Tests\Models\Company\CompanyManager m', @@ -1517,7 +1519,7 @@ public function testInheritanceTypeJoinInLeafClassWithDisabledForcePartialLoad() /** * @group DDC-1389 */ - public function testInheritanceTypeJoinInLeafClassWithEnabledForcePartialLoad() + public function testInheritanceTypeJoinInLeafClassWithEnabledForcePartialLoad(): void { $this->assertSqlGeneration( 'SELECT m FROM Doctrine\Tests\Models\Company\CompanyManager m', @@ -1529,7 +1531,7 @@ public function testInheritanceTypeJoinInLeafClassWithEnabledForcePartialLoad() /** * @group DDC-1389 */ - public function testInheritanceTypeSingleTableInRootClassWithDisabledForcePartialLoad() + public function testInheritanceTypeSingleTableInRootClassWithDisabledForcePartialLoad(): void { $this->assertSqlGeneration( 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c', @@ -1541,7 +1543,7 @@ public function testInheritanceTypeSingleTableInRootClassWithDisabledForcePartia /** * @group DDC-1389 */ - public function testInheritanceTypeSingleTableInRootClassWithEnabledForcePartialLoad() + public function testInheritanceTypeSingleTableInRootClassWithEnabledForcePartialLoad(): void { $this->assertSqlGeneration( 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c', @@ -1553,7 +1555,7 @@ public function testInheritanceTypeSingleTableInRootClassWithEnabledForcePartial /** * @group DDC-1389 */ - public function testInheritanceTypeSingleTableInChildClassWithDisabledForcePartialLoad() + public function testInheritanceTypeSingleTableInChildClassWithDisabledForcePartialLoad(): void { $this->assertSqlGeneration( 'SELECT fc FROM Doctrine\Tests\Models\Company\CompanyFlexContract fc', @@ -1565,7 +1567,7 @@ public function testInheritanceTypeSingleTableInChildClassWithDisabledForceParti /** * @group DDC-1389 */ - public function testInheritanceTypeSingleTableInChildClassWithEnabledForcePartialLoad() + public function testInheritanceTypeSingleTableInChildClassWithEnabledForcePartialLoad(): void { $this->assertSqlGeneration( 'SELECT fc FROM Doctrine\Tests\Models\Company\CompanyFlexContract fc', @@ -1577,7 +1579,7 @@ public function testInheritanceTypeSingleTableInChildClassWithEnabledForcePartia /** * @group DDC-1389 */ - public function testInheritanceTypeSingleTableInLeafClassWithDisabledForcePartialLoad() + public function testInheritanceTypeSingleTableInLeafClassWithDisabledForcePartialLoad(): void { $this->assertSqlGeneration( 'SELECT fuc FROM Doctrine\Tests\Models\Company\CompanyFlexUltraContract fuc', @@ -1589,7 +1591,7 @@ public function testInheritanceTypeSingleTableInLeafClassWithDisabledForcePartia /** * @group DDC-1389 */ - public function testInheritanceTypeSingleTableInLeafClassWithEnabledForcePartialLoad() + public function testInheritanceTypeSingleTableInLeafClassWithEnabledForcePartialLoad(): void { $this->assertSqlGeneration( 'SELECT fuc FROM Doctrine\Tests\Models\Company\CompanyFlexUltraContract fuc', @@ -1601,11 +1603,11 @@ public function testInheritanceTypeSingleTableInLeafClassWithEnabledForcePartial /** * @group DDC-1161 */ - public function testSelfReferenceWithOneToOneDoesNotDuplicateAlias() + public function testSelfReferenceWithOneToOneDoesNotDuplicateAlias(): void { $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 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', [ORMQuery::HINT_FORCE_PARTIAL_LOAD => false] ); } @@ -1613,11 +1615,11 @@ public function testSelfReferenceWithOneToOneDoesNotDuplicateAlias() /** * @group DDC-1384 */ - public function testAliasDoesNotExceedPlatformDefinedLength() + public function testAliasDoesNotExceedPlatformDefinedLength(): void { $this->assertSqlGeneration( - 'SELECT m FROM ' . __NAMESPACE__ . '\\DDC1384Model m', - "SELECT d0_.aVeryLongIdentifierThatShouldBeShortenedByTheSQLWalker_fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo AS ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo_0 FROM DDC1384Model d0_" + 'SELECT m FROM ' . __NAMESPACE__ . '\\DDC1384Model m', + 'SELECT d0_.aVeryLongIdentifierThatShouldBeShortenedByTheSQLWalker_fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo AS ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo_0 FROM DDC1384Model d0_' ); } @@ -1625,28 +1627,29 @@ public function testAliasDoesNotExceedPlatformDefinedLength() * @group DDC-331 * @group DDC-1384 */ - public function testIssue331() + public function testIssue331(): void { $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' ); } + /** * @group DDC-1435 */ - public function testForeignKeyAsPrimaryKeySubselect() + public function testForeignKeyAsPrimaryKeySubselect(): void { $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 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)' ); } /** * @group DDC-1474 */ - public function testSelectWithArithmeticExpressionBeforeField() + public function testSelectWithArithmeticExpressionBeforeField(): void { $this->assertSqlGeneration( 'SELECT - e.value AS value, e.id FROM ' . __NAMESPACE__ . '\DDC1474Entity e', @@ -1660,9 +1663,9 @@ public function testSelectWithArithmeticExpressionBeforeField() } /** - * @group DDC-1430 - */ - public function testGroupByAllFieldsWhenObjectHasForeignKeys() + * @group DDC-1430 + */ + public function testGroupByAllFieldsWhenObjectHasForeignKeys(): void { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u GROUP BY u', @@ -1678,7 +1681,7 @@ public function testGroupByAllFieldsWhenObjectHasForeignKeys() /** * @group DDC-1236 */ - public function testGroupBySupportsResultVariable() + public function testGroupBySupportsResultVariable(): void { $this->assertSqlGeneration( 'SELECT u, u.status AS st FROM Doctrine\Tests\Models\CMS\CmsUser u GROUP BY st', @@ -1689,7 +1692,7 @@ public function testGroupBySupportsResultVariable() /** * @group DDC-1236 */ - public function testGroupBySupportsIdentificationVariable() + public function testGroupBySupportsIdentificationVariable(): void { $this->assertSqlGeneration( 'SELECT u AS user FROM Doctrine\Tests\Models\CMS\CmsUser u GROUP BY user', @@ -1700,7 +1703,7 @@ public function testGroupBySupportsIdentificationVariable() /** * @group DDC-1213 */ - public function testSupportsBitComparison() + public function testSupportsBitComparison(): void { $this->assertSqlGeneration( 'SELECT BIT_OR(4,2), BIT_AND(4,2), u FROM Doctrine\Tests\Models\CMS\CmsUser u', @@ -1723,7 +1726,7 @@ public function testSupportsBitComparison() /** * @group DDC-1539 */ - public function testParenthesesOnTheLeftHandOfComparison() + public function testParenthesesOnTheLeftHandOfComparison(): void { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u where ( (u.id + u.id) * u.id ) > 100', @@ -1739,7 +1742,8 @@ public function testParenthesesOnTheLeftHandOfComparison() ); } - public function testSupportsParenthesisExpressionInSubSelect() { + public function testSupportsParenthesisExpressionInSubSelect(): void + { $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_' @@ -1749,7 +1753,7 @@ public function testSupportsParenthesisExpressionInSubSelect() { /** * @group DDC-1557 */ - public function testSupportsSubSqlFunction() + public function testSupportsSubSqlFunction(): void { $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 )', @@ -1780,47 +1784,47 @@ public function testSupportsSubSqlFunction() /** * @group DDC-1574 */ - public function testSupportsNewOperator() + public function testSupportsNewOperator(): void { $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 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' ); $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 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' ); $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 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' ); $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 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' ); $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 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' ); $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 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' ); } /** * @group DDC-2234 */ - public function testWhereFunctionIsNullComparisonExpression() + public function testWhereFunctionIsNullComparisonExpression(): void { $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 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' ); $this->assertSqlGeneration( @@ -1829,8 +1833,8 @@ public function testWhereFunctionIsNullComparisonExpression() ); $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 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' ); $this->assertSqlGeneration( @@ -1839,13 +1843,13 @@ public function testWhereFunctionIsNullComparisonExpression() ); $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 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' ); $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 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' ); $this->assertSqlGeneration( @@ -1854,7 +1858,7 @@ public function testWhereFunctionIsNullComparisonExpression() ); } - public function testCustomTypeValueSql() + public function testCustomTypeValueSql(): void { if (DBALType::hasType('negative_to_positive')) { DBALType::overrideType('negative_to_positive', NegativeToPositiveType::class); @@ -1868,7 +1872,7 @@ public function testCustomTypeValueSql() ); } - public function testCustomTypeValueSqlIgnoresIdentifierColumn() + public function testCustomTypeValueSqlIgnoresIdentifierColumn(): void { if (DBALType::hasType('negative_to_positive')) { DBALType::overrideType('negative_to_positive', NegativeToPositiveType::class); @@ -1882,7 +1886,7 @@ public function testCustomTypeValueSqlIgnoresIdentifierColumn() ); } - public function testCustomTypeValueSqlForAllFields() + public function testCustomTypeValueSqlForAllFields(): void { if (DBALType::hasType('negative_to_positive')) { DBALType::overrideType('negative_to_positive', NegativeToPositiveType::class); @@ -1896,7 +1900,7 @@ public function testCustomTypeValueSqlForAllFields() ); } - public function testCustomTypeValueSqlForPartialObject() + public function testCustomTypeValueSqlForPartialObject(): void { if (DBALType::hasType('negative_to_positive')) { DBALType::overrideType('negative_to_positive', NegativeToPositiveType::class); @@ -1913,7 +1917,7 @@ public function testCustomTypeValueSqlForPartialObject() /** * @group DDC-1529 */ - public function testMultipleFromAndInheritanceCondition() + public function testMultipleFromAndInheritanceCondition(): void { $this->assertSqlGeneration( 'SELECT fix, flex FROM Doctrine\Tests\Models\Company\CompanyFixContract fix, Doctrine\Tests\Models\Company\CompanyFlexContract flex', @@ -1924,7 +1928,7 @@ public function testMultipleFromAndInheritanceCondition() /** * @group DDC-775 */ - public function testOrderByClauseSupportsSimpleArithmeticExpression() + public function testOrderByClauseSupportsSimpleArithmeticExpression(): void { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.id + 1 ', @@ -1940,7 +1944,7 @@ public function testOrderByClauseSupportsSimpleArithmeticExpression() ); } - public function testOrderByClauseSupportsFunction() + public function testOrderByClauseSupportsFunction(): void { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY CONCAT(u.username, u.name) ', @@ -1951,7 +1955,7 @@ public function testOrderByClauseSupportsFunction() /** * @group DDC-1719 */ - public function testStripNonAlphanumericCharactersFromAlias() + public function testStripNonAlphanumericCharactersFromAlias(): void { $this->assertSqlGeneration( 'SELECT e FROM Doctrine\Tests\Models\Generic\NonAlphaColumnsEntity e', @@ -1972,7 +1976,7 @@ public function testStripNonAlphanumericCharactersFromAlias() /** * @group DDC-2435 */ - public function testColumnNameWithNumbersAndNonAlphanumericCharacters() + public function testColumnNameWithNumbersAndNonAlphanumericCharacters(): void { $this->assertSqlGeneration( 'SELECT e FROM Doctrine\Tests\Models\Quote\NumericEntity e', @@ -1993,7 +1997,7 @@ public function testColumnNameWithNumbersAndNonAlphanumericCharacters() /** * @group DDC-1845 */ - public function testQuotedTableDeclaration() + public function testQuotedTableDeclaration(): void { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\Quote\User u', @@ -2004,7 +2008,7 @@ public function testQuotedTableDeclaration() /** * @group DDC-1845 */ - public function testQuotedWalkJoinVariableDeclaration() + public function testQuotedWalkJoinVariableDeclaration(): void { $this->assertSqlGeneration( 'SELECT u, a FROM Doctrine\Tests\Models\Quote\User u JOIN u.address a', @@ -2040,7 +2044,7 @@ public function testQuotedWalkJoinVariableDeclaration() /** * @group DDC-2208 */ - public function testCaseThenParameterArithmeticExpression() + public function testCaseThenParameterArithmeticExpression(): void { $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', @@ -2059,9 +2063,9 @@ public function testCaseThenParameterArithmeticExpression() } /** - * @group DDC-2268 - */ - public function testCaseThenFunction() + * @group DDC-2268 + */ + public function testCaseThenFunction(): void { $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', @@ -2082,48 +2086,48 @@ public function testCaseThenFunction() /** * @group DDC-2268 */ - public function testSupportsMoreThanTwoParametersInConcatFunction() + public function testSupportsMoreThanTwoParametersInConcatFunction(): void { - $connMock = $this->_em->getConnection(); - $orgPlatform = $connMock->getDatabasePlatform(); + $connMock = $this->_em->getConnection(); + $orgPlatform = $connMock->getDatabasePlatform(); - $connMock->setDatabasePlatform(new MySqlPlatform()); - $this->assertSqlGeneration( + $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 = ?" - ); - - $connMock->setDatabasePlatform(new PostgreSqlPlatform()); - $this->assertSqlGeneration( + ); + $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 = ?' + ); + + $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 = ?" - ); - - $connMock->setDatabasePlatform(new SQLServerPlatform()); - $this->assertSqlGeneration( + ); + $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 = ?' + ); + + $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') = ?" - ); - $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 (c0_.id + c0_.name + c0_.status) AS sclr_0 FROM cms_users c0_ WHERE c0_.id = ?' + ); - $connMock->setDatabasePlatform($orgPlatform); + $connMock->setDatabasePlatform($orgPlatform); } /** - * @group DDC-2188 - */ - public function testArithmeticPriority() + * @group DDC-2188 + */ + public function testArithmeticPriority(): void { $this->assertSqlGeneration( 'SELECT 100/(2*2) FROM Doctrine\Tests\Models\CMS\CmsUser u', @@ -2142,9 +2146,9 @@ public function testArithmeticPriority() } /** - * @group DDC-2475 - */ - public function testOrderByClauseShouldReplaceOrderByRelationMapping() + * @group DDC-2475 + */ + public function testOrderByClauseShouldReplaceOrderByRelationMapping(): void { $this->assertSqlGeneration( 'SELECT r, b FROM Doctrine\Tests\Models\Routing\RoutingRoute r JOIN r.bookings b', @@ -2160,7 +2164,7 @@ public function testOrderByClauseShouldReplaceOrderByRelationMapping() /** * @group DDC-1858 */ - public function testHavingSupportIsNullExpression() + public function testHavingSupportIsNullExpression(): void { $this->assertSqlGeneration( 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u HAVING u.username IS NULL', @@ -2176,7 +2180,7 @@ public function testHavingSupportIsNullExpression() /** * @group DDC-2506 */ - public function testClassTableInheritanceJoinWithConditionAppliesToBaseTable() + public function testClassTableInheritanceJoinWithConditionAppliesToBaseTable(): void { $this->assertSqlGeneration( 'SELECT e.id FROM Doctrine\Tests\Models\Company\CompanyOrganization o JOIN o.events e WITH e.id = ?1', @@ -2188,7 +2192,7 @@ public function testClassTableInheritanceJoinWithConditionAppliesToBaseTable() /** * @group DDC-2235 */ - public function testSingleTableInheritanceLeftJoinWithCondition() + public function testSingleTableInheritanceLeftJoinWithCondition(): void { // Regression test for the bug $this->assertSqlGeneration( @@ -2200,7 +2204,7 @@ public function testSingleTableInheritanceLeftJoinWithCondition() /** * @group DDC-2235 */ - public function testSingleTableInheritanceLeftJoinWithConditionAndWhere() + public function testSingleTableInheritanceLeftJoinWithConditionAndWhere(): void { // Ensure other WHERE predicates are passed through to the main WHERE clause $this->assertSqlGeneration( @@ -2212,7 +2216,7 @@ public function testSingleTableInheritanceLeftJoinWithConditionAndWhere() /** * @group DDC-2235 */ - public function testSingleTableInheritanceInnerJoinWithCondition() + public function testSingleTableInheritanceInnerJoinWithCondition(): void { // Test inner joins too $this->assertSqlGeneration( @@ -2224,7 +2228,7 @@ public function testSingleTableInheritanceInnerJoinWithCondition() /** * @group DDC-2235 */ - public function testSingleTableInheritanceLeftJoinNonAssociationWithConditionAndWhere() + public function testSingleTableInheritanceLeftJoinNonAssociationWithConditionAndWhere(): void { // Test that the discriminator IN() predicate is still added into // the where clause when not joining onto that table @@ -2237,7 +2241,7 @@ public function testSingleTableInheritanceLeftJoinNonAssociationWithConditionAnd /** * @group DDC-2235 */ - public function testSingleTableInheritanceJoinCreatesOnCondition() + public function testSingleTableInheritanceJoinCreatesOnCondition(): void { // Test that the discriminator IN() predicate is still added // into the where clause when not joining onto a single table inheritance entity @@ -2251,7 +2255,7 @@ public function testSingleTableInheritanceJoinCreatesOnCondition() /** * @group DDC-2235 */ - public function testSingleTableInheritanceCreatesOnConditionAndWhere() + public function testSingleTableInheritanceCreatesOnConditionAndWhere(): void { // Test that when joining onto an entity using single table inheritance via // a join association that the discriminator IN() predicate is placed @@ -2267,7 +2271,7 @@ public function testSingleTableInheritanceCreatesOnConditionAndWhere() /** * @group DDC-1858 */ - public function testHavingSupportResultVariableInExpression() + public function testHavingSupportResultVariableInExpression(): void { $this->assertSqlGeneration( 'SELECT u.name AS foo FROM Doctrine\Tests\Models\CMS\CmsUser u HAVING foo IN (?1)', @@ -2278,7 +2282,7 @@ public function testHavingSupportResultVariableInExpression() /** * @group DDC-1858 */ - public function testHavingSupportResultVariableLikeExpression() + public function testHavingSupportResultVariableLikeExpression(): void { $this->assertSqlGeneration( "SELECT u.name AS foo FROM Doctrine\Tests\Models\CMS\CmsUser u HAVING foo LIKE '3'", @@ -2289,18 +2293,18 @@ public function testHavingSupportResultVariableLikeExpression() /** * @group DDC-3085 */ - public function testHavingSupportResultVariableNullComparisonExpression() + public function testHavingSupportResultVariableNullComparisonExpression(): void { $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 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' ); } /** * @group DDC-1858 */ - public function testHavingSupportResultVariableInAggregateFunction() + public function testHavingSupportResultVariableInAggregateFunction(): void { $this->assertSqlGeneration( 'SELECT COUNT(u.name) AS countName FROM Doctrine\Tests\Models\CMS\CmsUser u HAVING countName IS NULL', @@ -2310,10 +2314,11 @@ public function testHavingSupportResultVariableInAggregateFunction() /** * GitHub issue #4764: https://github.com/doctrine/orm/issues/4764 + * * @group DDC-3907 * @dataProvider mathematicOperatorsProvider */ - public function testHavingRegressionUsingVariableWithMathOperatorsExpression($operator) + public function testHavingRegressionUsingVariableWithMathOperatorsExpression($operator): void { $this->assertSqlGeneration( 'SELECT COUNT(u.name) AS countName FROM Doctrine\Tests\Models\CMS\CmsUser u HAVING 1 ' . $operator . ' countName > 0', @@ -2324,7 +2329,7 @@ public function testHavingRegressionUsingVariableWithMathOperatorsExpression($op /** * @return array */ - public function mathematicOperatorsProvider() + public function mathematicOperatorsProvider(): array { return [['+'], ['-'], ['*'], ['/']]; } @@ -2345,7 +2350,7 @@ public function getSql(SqlWalker $sqlWalker) /** * @override */ - public function parse(Parser $parser) + public function parse(Parser $parser): void { $lexer = $parser->getLexer(); @@ -2376,7 +2381,6 @@ class DDC1384Model */ class DDC1474Entity { - /** * @Id * @Column(type="integer") @@ -2384,41 +2388,26 @@ class DDC1474Entity */ protected $id; - /** - * @column(type="float") - */ + /** @column(type="float") */ private $value; - /** - * @param string $float - */ - public function __construct($float) + public function __construct(string $float) { $this->value = $float; } - /** - * @return int - */ - public function getId() + public function getId(): int { return $this->id; } - /** - * @return float - */ - public function getValue() + public function getValue(): float { return $this->value; } - /** - * @param float $value - */ - public function setValue($value) + public function setValue(float $value): void { $this->value = $value; } - } diff --git a/tests/Doctrine/Tests/ORM/Query/SqlWalkerTest.php b/tests/Doctrine/Tests/ORM/Query/SqlWalkerTest.php index e2f924f2560..67ede42a486 100644 --- a/tests/Doctrine/Tests/ORM/Query/SqlWalkerTest.php +++ b/tests/Doctrine/Tests/ORM/Query/SqlWalkerTest.php @@ -1,11 +1,13 @@ sqlWalker = new SqlWalker(new Query($this->_getTestEntityManager()), new ParserResult(), []); } @@ -30,7 +27,7 @@ protected function setUp() : void /** * @dataProvider getColumnNamesAndSqlAliases */ - public function testGetSQLTableAlias($tableName, $expectedAlias) + public function testGetSQLTableAlias($tableName, $expectedAlias): void { $this->assertSame($expectedAlias, $this->sqlWalker->getSQLTableAlias($tableName)); } @@ -38,7 +35,7 @@ public function testGetSQLTableAlias($tableName, $expectedAlias) /** * @dataProvider getColumnNamesAndSqlAliases */ - public function testGetSQLTableAliasIsSameForMultipleCalls($tableName) + public function testGetSQLTableAliasIsSameForMultipleCalls($tableName): void { $this->assertSame( $this->sqlWalker->getSQLTableAlias($tableName), @@ -47,11 +44,11 @@ public function testGetSQLTableAliasIsSameForMultipleCalls($tableName) } /** - * @private data provider - * * @return string[][] + * + * @private data provider */ - public function getColumnNamesAndSqlAliases() + public function getColumnNamesAndSqlAliases(): array { return [ ['aaaaa', 'a0_'], diff --git a/tests/Doctrine/Tests/ORM/Query/UpdateSqlGenerationTest.php b/tests/Doctrine/Tests/ORM/Query/UpdateSqlGenerationTest.php index 5fd200c26fd..e0ac0620358 100644 --- a/tests/Doctrine/Tests/ORM/Query/UpdateSqlGenerationTest.php +++ b/tests/Doctrine/Tests/ORM/Query/UpdateSqlGenerationTest.php @@ -1,21 +1,19 @@ - * @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. @@ -24,7 +22,7 @@ class UpdateSqlGenerationTest extends OrmTestCase { private $_em; - protected function setUp() : void + protected function setUp(): void { if (DBALType::hasType('negative_to_positive')) { DBALType::overrideType('negative_to_positive', NegativeToPositiveType::class); @@ -35,18 +33,18 @@ protected function setUp() : void $this->_em = $this->_getTestEntityManager(); } - public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed) + public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed): void { try { $query = $this->_em->createQuery($dqlToBeTested); parent::assertEquals($sqlToBeConfirmed, $query->getSql()); $query->free(); - } catch (\Exception $e) { + } catch (Exception $e) { $this->fail($e->getMessage()); } } - public function testSupportsQueriesWithoutWhere() + public function testSupportsQueriesWithoutWhere(): void { $this->assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = ?1', @@ -54,7 +52,7 @@ public function testSupportsQueriesWithoutWhere() ); } - public function testSupportsMultipleFieldsWithoutWhere() + public function testSupportsMultipleFieldsWithoutWhere(): void { $this->assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = ?1, u.username = ?2', @@ -62,7 +60,7 @@ public function testSupportsMultipleFieldsWithoutWhere() ); } - public function testSupportsWhereClauses() + public function testSupportsWhereClauses(): void { $this->assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = ?1 WHERE u.id = ?2', @@ -70,7 +68,7 @@ public function testSupportsWhereClauses() ); } - public function testSupportsWhereClausesOnTheUpdatedField() + public function testSupportsWhereClausesOnTheUpdatedField(): void { $this->assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = ?1 WHERE u.name = ?2', @@ -78,7 +76,7 @@ public function testSupportsWhereClausesOnTheUpdatedField() ); } - public function testSupportsMultipleWhereClause() + public function testSupportsMultipleWhereClause(): void { $this->assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = ?1 WHERE u.name = ?2 AND u.status = ?3', @@ -86,7 +84,7 @@ public function testSupportsMultipleWhereClause() ); } - public function testSupportsInClause() + public function testSupportsInClause(): void { $this->assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = ?1 WHERE u.id IN (1, 3, 4)', @@ -94,7 +92,7 @@ public function testSupportsInClause() ); } - public function testSupportsParametrizedInClause() + public function testSupportsParametrizedInClause(): void { $this->assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = ?1 WHERE u.id IN (?2, ?3, ?4)', @@ -102,7 +100,7 @@ public function testSupportsParametrizedInClause() ); } - public function testSupportsNotInClause() + public function testSupportsNotInClause(): void { $this->assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = ?1 WHERE u.id NOT IN (1, 3, 4)', @@ -110,7 +108,7 @@ public function testSupportsNotInClause() ); } - public function testSupportsGreaterThanClause() + public function testSupportsGreaterThanClause(): void { $this->assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.status = ?1 WHERE u.id > ?2', @@ -118,7 +116,7 @@ public function testSupportsGreaterThanClause() ); } - public function testSupportsGreaterThanOrEqualToClause() + public function testSupportsGreaterThanOrEqualToClause(): void { $this->assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.status = ?1 WHERE u.id >= ?2', @@ -126,7 +124,7 @@ public function testSupportsGreaterThanOrEqualToClause() ); } - public function testSupportsLessThanClause() + public function testSupportsLessThanClause(): void { $this->assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.status = ?1 WHERE u.id < ?2', @@ -134,7 +132,7 @@ public function testSupportsLessThanClause() ); } - public function testSupportsLessThanOrEqualToClause() + public function testSupportsLessThanOrEqualToClause(): void { $this->assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.status = ?1 WHERE u.id <= ?2', @@ -142,7 +140,7 @@ public function testSupportsLessThanOrEqualToClause() ); } - public function testSupportsBetweenClause() + public function testSupportsBetweenClause(): void { $this->assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.status = ?1 WHERE u.id BETWEEN :from AND :to', @@ -150,26 +148,26 @@ public function testSupportsBetweenClause() ); } - public function testSingleValuedAssociationFieldInWhere() + public function testSingleValuedAssociationFieldInWhere(): void { $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 = ?" + '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() + public function testSingleValuedAssociationFieldInSetClause(): void { $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 = ?" + '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 = ?' ); } /** * @group DDC-980 */ - public function testSubselectTableAliasReferencing() + public function testSubselectTableAliasReferencing(): void { $this->assertSqlGeneration( "UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.status = 'inactive' WHERE SIZE(u.groups) = 10", @@ -177,7 +175,7 @@ public function testSubselectTableAliasReferencing() ); } - public function testCustomTypeValueSqlCompletelyIgnoredInUpdateStatements() + public function testCustomTypeValueSqlCompletelyIgnoredInUpdateStatements(): void { $this->assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CustomType\CustomTypeParent p SET p.customInteger = 1 WHERE p.id = 1', @@ -185,10 +183,10 @@ public function testCustomTypeValueSqlCompletelyIgnoredInUpdateStatements() ); } - public function testUpdateWithSubselectAsNewValue() + public function testUpdateWithSubselectAsNewValue(): void { $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 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')" ); } diff --git a/tests/Doctrine/Tests/ORM/QueryBuilderTest.php b/tests/Doctrine/Tests/ORM/QueryBuilderTest.php index e2f10e3f624..b6d6527f4f4 100644 --- a/tests/Doctrine/Tests/ORM/QueryBuilderTest.php +++ b/tests/Doctrine/Tests/ORM/QueryBuilderTest.php @@ -1,10 +1,13 @@ - * @author Roman Borschel _em = $this->_getTestEntityManager(); } - protected function assertValidQueryBuilder(QueryBuilder $qb, $expectedDql) + protected function assertValidQueryBuilder(QueryBuilder $qb, $expectedDql): void { $dql = $qb->getDQL(); - $q = $qb->getQuery(); + $q = $qb->getQuery(); $this->assertEquals($expectedDql, $dql); } - public function testSelectSetsType() + public function testSelectSetsType(): void { $qb = $this->_em->createQueryBuilder() ->delete(CmsUser::class, 'u') @@ -52,7 +54,7 @@ public function testSelectSetsType() $this->assertEquals($qb->getType(), QueryBuilder::SELECT); } - public function testEmptySelectSetsType() + public function testEmptySelectSetsType(): void { $qb = $this->_em->createQueryBuilder() ->delete(CmsUser::class, 'u') @@ -61,7 +63,7 @@ public function testEmptySelectSetsType() $this->assertEquals($qb->getType(), QueryBuilder::SELECT); } - public function testDeleteSetsType() + public function testDeleteSetsType(): void { $qb = $this->_em->createQueryBuilder() ->from(CmsUser::class, 'u') @@ -70,7 +72,7 @@ public function testDeleteSetsType() $this->assertEquals($qb->getType(), QueryBuilder::DELETE); } - public function testUpdateSetsType() + public function testUpdateSetsType(): void { $qb = $this->_em->createQueryBuilder() ->from(CmsUser::class, 'u') @@ -79,7 +81,7 @@ public function testUpdateSetsType() $this->assertEquals($qb->getType(), QueryBuilder::UPDATE); } - public function testSimpleSelect() + public function testSimpleSelect(): void { $qb = $this->_em->createQueryBuilder() ->from(CmsUser::class, 'u') @@ -88,7 +90,7 @@ public function testSimpleSelect() $this->assertValidQueryBuilder($qb, 'SELECT u.id, u.username FROM Doctrine\Tests\Models\CMS\CmsUser u'); } - public function testSimpleDelete() + public function testSimpleDelete(): void { $qb = $this->_em->createQueryBuilder() ->delete(CmsUser::class, 'u'); @@ -96,7 +98,7 @@ public function testSimpleDelete() $this->assertValidQueryBuilder($qb, 'DELETE Doctrine\Tests\Models\CMS\CmsUser u'); } - public function testSimpleSelectWithFromIndexBy() + public function testSimpleSelectWithFromIndexBy(): void { $qb = $this->_em->createQueryBuilder() ->from(CmsUser::class, 'u', 'u.id') @@ -105,7 +107,7 @@ public function testSimpleSelectWithFromIndexBy() $this->assertValidQueryBuilder($qb, 'SELECT u.id, u.username FROM Doctrine\Tests\Models\CMS\CmsUser u INDEX BY u.id'); } - public function testSimpleSelectWithIndexBy() + public function testSimpleSelectWithIndexBy(): void { $qb = $this->_em->createQueryBuilder() ->from(CmsUser::class, 'u') @@ -115,7 +117,7 @@ public function testSimpleSelectWithIndexBy() $this->assertValidQueryBuilder($qb, 'SELECT u.id, u.username FROM Doctrine\Tests\Models\CMS\CmsUser u INDEX BY u.id'); } - public function testSimpleUpdate() + public function testSimpleUpdate(): void { $qb = $this->_em->createQueryBuilder() ->update(CmsUser::class, 'u') @@ -124,7 +126,7 @@ public function testSimpleUpdate() $this->assertValidQueryBuilder($qb, 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.username = :username'); } - public function testInnerJoin() + public function testInnerJoin(): void { $qb = $this->_em->createQueryBuilder() ->select('u', 'a') @@ -134,7 +136,7 @@ public function testInnerJoin() $this->assertValidQueryBuilder($qb, 'SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.articles a'); } - public function testComplexInnerJoin() + public function testComplexInnerJoin(): void { $qb = $this->_em->createQueryBuilder() ->select('u', 'a') @@ -147,7 +149,7 @@ public function testComplexInnerJoin() ); } - public function testComplexInnerJoinWithIndexBy() + public function testComplexInnerJoinWithIndexBy(): void { $qb = $this->_em->createQueryBuilder() ->select('u', 'a') @@ -160,7 +162,7 @@ public function testComplexInnerJoinWithIndexBy() ); } - public function testLeftJoin() + public function testLeftJoin(): void { $qb = $this->_em->createQueryBuilder() ->select('u', 'a') @@ -170,7 +172,7 @@ public function testLeftJoin() $this->assertValidQueryBuilder($qb, 'SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a'); } - public function testLeftJoinWithIndexBy() + public function testLeftJoinWithIndexBy(): void { $qb = $this->_em->createQueryBuilder() ->select('u', 'a') @@ -180,7 +182,7 @@ public function testLeftJoinWithIndexBy() $this->assertValidQueryBuilder($qb, 'SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a INDEX BY a.name'); } - public function testMultipleFrom() + public function testMultipleFrom(): void { $qb = $this->_em->createQueryBuilder() ->select('u', 'g') @@ -190,7 +192,7 @@ public function testMultipleFrom() $this->assertValidQueryBuilder($qb, 'SELECT u, g FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsGroup g'); } - public function testMultipleFromWithIndexBy() + public function testMultipleFromWithIndexBy(): void { $qb = $this->_em->createQueryBuilder() ->select('u', 'g') @@ -201,7 +203,7 @@ public function testMultipleFromWithIndexBy() $this->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() + public function testMultipleFromWithJoin(): void { $qb = $this->_em->createQueryBuilder() ->select('u', 'g') @@ -212,7 +214,7 @@ public function testMultipleFromWithJoin() $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'); } - public function testMultipleFromWithMultipleJoin() + public function testMultipleFromWithMultipleJoin(): void { $qb = $this->_em->createQueryBuilder() ->select('u', 'g') @@ -225,7 +227,7 @@ public function testMultipleFromWithMultipleJoin() $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'); } - public function testWhere() + public function testWhere(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -235,7 +237,7 @@ public function testWhere() $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid'); } - public function testComplexAndWhere() + public function testComplexAndWhere(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -246,7 +248,7 @@ public function testComplexAndWhere() $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'); } - public function testAndWhere() + public function testAndWhere(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -257,7 +259,7 @@ public function testAndWhere() $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid AND u.id = :uid2'); } - public function testOrWhere() + public function testOrWhere(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -268,7 +270,7 @@ public function testOrWhere() $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid OR u.id = :uid2'); } - public function testComplexAndWhereOrWhereNesting() + public function testComplexAndWhereOrWhereNesting(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('u') @@ -282,7 +284,7 @@ public function testComplexAndWhereOrWhereNesting() $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'); } - public function testAndWhereIn() + public function testAndWhereIn(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('u') @@ -293,7 +295,7 @@ public function testAndWhereIn() $this->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() + public function testOrWhereIn(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('u') @@ -304,7 +306,7 @@ public function testOrWhereIn() $this->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() + public function testAndWhereNotIn(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('u') @@ -315,7 +317,7 @@ public function testAndWhereNotIn() $this->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() + public function testOrWhereNotIn(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('u') @@ -326,7 +328,7 @@ public function testOrWhereNotIn() $this->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() + public function testGroupBy(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -337,7 +339,7 @@ public function testGroupBy() $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u GROUP BY u.id, u.username'); } - public function testHaving() + public function testHaving(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -348,7 +350,7 @@ public function testHaving() $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u GROUP BY u.id HAVING COUNT(u.id) > 1'); } - public function testAndHaving() + public function testAndHaving(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -360,7 +362,7 @@ public function testAndHaving() $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'); } - public function testOrHaving() + public function testOrHaving(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -373,7 +375,7 @@ public function testOrHaving() $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'); } - public function testOrderBy() + public function testOrderBy(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -383,7 +385,7 @@ public function testOrderBy() $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.username ASC'); } - public function testOrderByWithExpression() + public function testOrderByWithExpression(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('u') @@ -393,7 +395,7 @@ public function testOrderByWithExpression() $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.username ASC'); } - public function testAddOrderBy() + public function testAddOrderBy(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -404,7 +406,7 @@ public function testAddOrderBy() $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.username ASC, u.username DESC'); } - public function testAddOrderByWithExpression() + public function testAddOrderByWithExpression(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('u') @@ -415,7 +417,7 @@ public function testAddOrderByWithExpression() $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.username ASC, u.username DESC'); } - public function testAddCriteriaWhere() + public function testAddCriteriaWhere(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('u') @@ -430,7 +432,7 @@ public function testAddCriteriaWhere() $this->assertNotNull($qb->getParameter('field')); } - public function testAddMultipleSameCriteriaWhere() + public function testAddMultipleSameCriteriaWhere(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('alias1')->from(CmsUser::class, 'alias1'); @@ -451,7 +453,7 @@ public function testAddMultipleSameCriteriaWhere() /** * @group DDC-2844 */ - public function testAddCriteriaWhereWithMultipleParametersWithSameField() + public function testAddCriteriaWhereWithMultipleParametersWithSameField(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('alias1')->from(CmsUser::class, 'alias1'); @@ -470,7 +472,7 @@ public function testAddCriteriaWhereWithMultipleParametersWithSameField() /** * @group DDC-2844 */ - public function testAddCriteriaWhereWithMultipleParametersWithDifferentFields() + public function testAddCriteriaWhereWithMultipleParametersWithDifferentFields(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('alias1')->from(CmsUser::class, 'alias1'); @@ -489,7 +491,7 @@ public function testAddCriteriaWhereWithMultipleParametersWithDifferentFields() /** * @group DDC-2844 */ - public function testAddCriteriaWhereWithMultipleParametersWithSubpathsAndDifferentProperties() + public function testAddCriteriaWhereWithMultipleParametersWithSubpathsAndDifferentProperties(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('alias1')->from(CmsUser::class, 'alias1'); @@ -508,7 +510,7 @@ public function testAddCriteriaWhereWithMultipleParametersWithSubpathsAndDiffere /** * @group DDC-2844 */ - public function testAddCriteriaWhereWithMultipleParametersWithSubpathsAndSameProperty() + public function testAddCriteriaWhereWithMultipleParametersWithSubpathsAndSameProperty(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('alias1')->from(CmsUser::class, 'alias1'); @@ -524,7 +526,7 @@ public function testAddCriteriaWhereWithMultipleParametersWithSubpathsAndSamePro $this->assertSame('value2', $qb->getParameter('field1_1')->getValue()); } - public function testAddCriteriaOrder() + public function testAddCriteriaOrder(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('u') @@ -542,12 +544,12 @@ public function testAddCriteriaOrder() /** * @group DDC-3108 */ - public function testAddCriteriaOrderOnJoinAlias() + public function testAddCriteriaOrderOnJoinAlias(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('u') ->from(CmsUser::class, 'u') - ->join('u.article','a'); + ->join('u.article', 'a'); $criteria = new Criteria(); $criteria->orderBy(['a.field' => Criteria::DESC]); @@ -558,7 +560,7 @@ public function testAddCriteriaOrderOnJoinAlias() $this->assertEquals('a.field DESC', (string) $orderBy[0]); } - public function testAddCriteriaLimit() + public function testAddCriteriaLimit(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('u') @@ -574,7 +576,7 @@ public function testAddCriteriaLimit() $this->assertEquals(10, $qb->getMaxResults()); } - public function testAddCriteriaUndefinedLimit() + public function testAddCriteriaUndefinedLimit(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('u') @@ -590,17 +592,17 @@ public function testAddCriteriaUndefinedLimit() $this->assertEquals(10, $qb->getMaxResults()); } - public function testGetQuery() + public function testGetQuery(): void { $qb = $this->_em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u'); - $q = $qb->getQuery(); + $q = $qb->getQuery(); $this->assertEquals(Query::class, get_class($q)); } - public function testSetParameter() + public function testSetParameter(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -616,7 +618,7 @@ public function testSetParameter() self::assertFalse($inferred->typeWasSpecified()); } - public function testSetParameters() + public function testSetParameters(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('u') @@ -632,8 +634,7 @@ public function testSetParameters() $this->assertEquals($parameters, $qb->getQuery()->getParameters()); } - - public function testGetParameters() + public function testGetParameters(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('u') @@ -648,7 +649,7 @@ public function testGetParameters() $this->assertEquals($parameters, $qb->getParameters()); } - public function testGetParameter() + public function testGetParameter(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -663,7 +664,7 @@ public function testGetParameter() $this->assertEquals($parameters->first(), $qb->getParameter('id')); } - public function testMultipleWhere() + public function testMultipleWhere(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -673,7 +674,7 @@ public function testMultipleWhere() $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid AND u.id = :uid2'); } - public function testMultipleAndWhere() + public function testMultipleAndWhere(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -683,7 +684,7 @@ public function testMultipleAndWhere() $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid AND u.id = :uid2'); } - public function testMultipleOrWhere() + public function testMultipleOrWhere(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('u') @@ -693,9 +694,9 @@ public function testMultipleOrWhere() $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid OR u.id = :uid2'); } - public function testComplexWhere() + public function testComplexWhere(): void { - $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])); @@ -707,7 +708,7 @@ public function testComplexWhere() $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid3 OR u.id IN(1)'); } - public function testWhereInWithStringLiterals() + public function testWhereInWithStringLiterals(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('u') @@ -721,9 +722,9 @@ public function testWhereInWithStringLiterals() $this->assertValidQueryBuilder($qb, "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name IN('O''Reilly', 'O''Neil', 'Smith')"); } - public function testWhereInWithObjectLiterals() + public function testWhereInWithObjectLiterals(): void { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->_em->createQueryBuilder(); $expr = $this->_em->getExpressionBuilder(); $qb->select('u') ->from(CmsUser::class, 'u') @@ -736,9 +737,9 @@ public function testWhereInWithObjectLiterals() $this->assertValidQueryBuilder($qb, "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name IN('O''Reilly', 'O''Neil', 'Smith')"); } - public function testNegation() + public function testNegation(): void { - $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]))); @@ -751,9 +752,9 @@ public function testNegation() $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid3 OR NOT(u.id IN(1))'); } - public function testSomeAllAny() + public function testSomeAllAny(): void { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->_em->createQueryBuilder(); $expr = $this->_em->getExpressionBuilder(); $qb->select('u') @@ -761,12 +762,11 @@ public function testSomeAllAny() ->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)'); - } - public function testMultipleIsolatedQueryConstruction() + public function testMultipleIsolatedQueryConstruction(): void { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->_em->createQueryBuilder(); $expr = $this->_em->getExpressionBuilder(); $qb->select('u')->from(CmsUser::class, 'u'); @@ -790,19 +790,19 @@ public function testMultipleIsolatedQueryConstruction() $this->assertEquals(1, count($q1->getParameters())); // $q1 unaffected } - public function testGetEntityManager() + public function testGetEntityManager(): void { $qb = $this->_em->createQueryBuilder(); $this->assertEquals($this->_em, $qb->getEntityManager()); } - public function testInitialStateIsClean() + public function testInitialStateIsClean(): void { $qb = $this->_em->createQueryBuilder(); $this->assertEquals(QueryBuilder::STATE_CLEAN, $qb->getState()); } - public function testAlteringQueryChangesStateToDirty() + public function testAlteringQueryChangesStateToDirty(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -811,23 +811,23 @@ public function testAlteringQueryChangesStateToDirty() $this->assertEquals(QueryBuilder::STATE_DIRTY, $qb->getState()); } - public function testSelectWithFuncExpression() + public function testSelectWithFuncExpression(): void { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->_em->createQueryBuilder(); $expr = $qb->expr(); $qb->select($expr->count('e.id')); $this->assertValidQueryBuilder($qb, 'SELECT COUNT(e.id)'); } - public function testResetDQLPart() + public function testResetDQLPart(): void { $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('u.username = ?1', (string) $qb->getDQLPart('where')); $this->assertEquals(1, count($qb->getDQLPart('orderBy'))); $qb->resetDQLPart('where')->resetDQLPart('orderBy'); @@ -836,7 +836,7 @@ public function testResetDQLPart() $this->assertEquals(0, count($qb->getDQLPart('orderBy'))); } - public function testResetDQLParts() + public function testResetDQLParts(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -850,7 +850,7 @@ public function testResetDQLParts() $this->assertEquals(0, count($qb->getDQLPart('orderBy'))); } - public function testResetAllDQLParts() + public function testResetAllDQLParts(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -867,7 +867,7 @@ public function testResetAllDQLParts() /** * @group DDC-867 */ - public function testDeepClone() + public function testDeepClone(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -876,22 +876,22 @@ public function testDeepClone() ->andWhere('u.status = ?2'); $expr = $qb->getDQLPart('where'); - $this->assertEquals(2, $expr->count(), "Modifying the second query should affect the first one."); + $this->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."); + $this->assertEquals(2, $expr->count(), 'Modifying the second query should affect the first one.'); } /** * @group DDC-3108 */ - public function testAddCriteriaWhereWithJoinAlias() + public function testAddCriteriaWhereWithJoinAlias(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('alias1')->from(CmsUser::class, 'alias1'); - $qb->join('alias1.articles','alias2'); + $qb->join('alias1.articles', 'alias2'); $criteria = new Criteria(); $criteria->where($criteria->expr()->eq('field', 'value1')); @@ -907,11 +907,11 @@ public function testAddCriteriaWhereWithJoinAlias() /** * @group DDC-3108 */ - public function testAddCriteriaWhereWithDefaultAndJoinAlias() + public function testAddCriteriaWhereWithDefaultAndJoinAlias(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('alias1')->from(CmsUser::class, 'alias1'); - $qb->join('alias1.articles','alias2'); + $qb->join('alias1.articles', 'alias2'); $criteria = new Criteria(); $criteria->where($criteria->expr()->eq('alias1.field', 'value1')); @@ -927,11 +927,11 @@ public function testAddCriteriaWhereWithDefaultAndJoinAlias() /** * @group DDC-3108 */ - public function testAddCriteriaWhereOnJoinAliasWithDuplicateFields() + public function testAddCriteriaWhereOnJoinAliasWithDuplicateFields(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('alias1')->from(CmsUser::class, 'alias1'); - $qb->join('alias1.articles','alias2'); + $qb->join('alias1.articles', 'alias2'); $criteria = new Criteria(); $criteria->where($criteria->expr()->eq('alias1.field', 'value1')); @@ -946,11 +946,10 @@ public function testAddCriteriaWhereOnJoinAliasWithDuplicateFields() $this->assertSame('value3', $qb->getParameter('alias2_field_2')->getValue()); } - /** * @group DDC-1933 */ - public function testParametersAreCloned() + public function testParametersAreCloned(): void { $originalQb = new QueryBuilder($this->_em); @@ -964,7 +963,7 @@ public function testParametersAreCloned() $this->assertSame('value2', $copy->getParameter('parameter2')->getValue()); } - public function testGetRootAlias() + public function testGetRootAlias(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -973,7 +972,7 @@ public function testGetRootAlias() $this->assertEquals('u', $qb->getRootAlias()); } - public function testGetRootAliases() + public function testGetRootAliases(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -982,7 +981,7 @@ public function testGetRootAliases() $this->assertEquals(['u'], $qb->getRootAliases()); } - public function testGetRootEntities() + public function testGetRootEntities(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -991,7 +990,7 @@ public function testGetRootEntities() $this->assertEquals([CmsUser::class], $qb->getRootEntities()); } - public function testGetSeveralRootAliases() + public function testGetSeveralRootAliases(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -1002,7 +1001,7 @@ public function testGetSeveralRootAliases() $this->assertEquals('u', $qb->getRootAlias()); } - public function testBCAddJoinWithoutRootAlias() + public function testBCAddJoinWithoutRootAlias(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -1015,13 +1014,13 @@ public function testBCAddJoinWithoutRootAlias() /** * @group DDC-1211 */ - public function testEmptyStringLiteral() + public function testEmptyStringLiteral(): void { $expr = $this->_em->getExpressionBuilder(); - $qb = $this->_em->createQueryBuilder() + $qb = $this->_em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') - ->where($expr->eq('u.username', $expr->literal(""))); + ->where($expr->eq('u.username', $expr->literal(''))); $this->assertEquals("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = ''", $qb->getDQL()); } @@ -1029,10 +1028,10 @@ public function testEmptyStringLiteral() /** * @group DDC-1211 */ - public function testEmptyNumericLiteral() + public function testEmptyNumericLiteral(): void { $expr = $this->_em->getExpressionBuilder(); - $qb = $this->_em->createQueryBuilder() + $qb = $this->_em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') ->where($expr->eq('u.username', $expr->literal(0))); @@ -1043,7 +1042,7 @@ public function testEmptyNumericLiteral() /** * @group DDC-1227 */ - public function testAddFromString() + public function testAddFromString(): void { $qb = $this->_em->createQueryBuilder() ->add('select', 'u') @@ -1055,7 +1054,7 @@ public function testAddFromString() /** * @group DDC-1619 */ - public function testAddDistinct() + public function testAddDistinct(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -1068,18 +1067,17 @@ public function testAddDistinct() /** * @group DDC-2192 */ - public function testWhereAppend() + public function testWhereAppend(): void { - $this->expectException(\InvalidArgumentException::class); + $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() ->add('where', 'u.foo = ?1') - ->add('where', 'u.bar = ?2', true) - ; + ->add('where', 'u.bar = ?2', true); } - public function testSecondLevelCacheQueryBuilderOptions() + public function testSecondLevelCacheQueryBuilderOptions(): void { $defaultQueryBuilder = $this->_em->createQueryBuilder() ->select('s') @@ -1121,7 +1119,7 @@ public function testSecondLevelCacheQueryBuilderOptions() /** * @group DDC-2253 */ - public function testRebuildsFromParts() + public function testRebuildsFromParts(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -1129,18 +1127,19 @@ public function testRebuildsFromParts() ->join('u.article', 'a'); $dqlParts = $qb->getDQLParts(); - $dql = $qb->getDQL(); + $dql = $qb->getDQL(); $qb2 = $this->_em->createQueryBuilder(); foreach (array_filter($dqlParts) as $name => $part) { $qb2->add($name, $part); } + $dql2 = $qb2->getDQL(); $this->assertEquals($dql, $dql2); } - public function testGetAllAliasesWithNoJoins() + public function testGetAllAliasesWithNoJoins(): void { $qb = $this->_em->createQueryBuilder(); $qb->select('u')->from(CmsUser::class, 'u'); @@ -1150,7 +1149,7 @@ public function testGetAllAliasesWithNoJoins() $this->assertEquals(['u'], $aliases); } - public function testGetAllAliasesWithJoins() + public function testGetAllAliasesWithJoins(): void { $qb = $this->_em->createQueryBuilder() ->select('u') @@ -1165,7 +1164,7 @@ public function testGetAllAliasesWithJoins() /** * @group 6699 */ - public function testGetParameterTypeJuggling() : void + public function testGetParameterTypeJuggling(): void { $builder = $this->_em->createQueryBuilder() ->select('u') @@ -1182,7 +1181,7 @@ public function testGetParameterTypeJuggling() : void /** * @group 6699 */ - public function testSetParameterWithNameZeroIsNotOverridden() : void + public function testSetParameterWithNameZeroIsNotOverridden(): void { $builder = $this->_em->createQueryBuilder() ->select('u') @@ -1201,7 +1200,7 @@ public function testSetParameterWithNameZeroIsNotOverridden() : void /** * @group 6699 */ - public function testSetParameterWithNameZeroDoesNotOverrideAnotherParameter() : void + public function testSetParameterWithNameZeroDoesNotOverrideAnotherParameter(): void { $builder = $this->_em->createQueryBuilder() ->select('u') @@ -1220,7 +1219,7 @@ public function testSetParameterWithNameZeroDoesNotOverrideAnotherParameter() : /** * @group 6699 */ - public function testSetParameterWithTypeJugglingWorks() : void + public function testSetParameterWithTypeJugglingWorks(): void { $builder = $this->_em->createQueryBuilder() ->select('u') diff --git a/tests/Doctrine/Tests/ORM/Repository/DefaultRepositoryFactoryTest.php b/tests/Doctrine/Tests/ORM/Repository/DefaultRepositoryFactoryTest.php index bb2b5a78fb3..822ea48d181 100644 --- a/tests/Doctrine/Tests/ORM/Repository/DefaultRepositoryFactoryTest.php +++ b/tests/Doctrine/Tests/ORM/Repository/DefaultRepositoryFactoryTest.php @@ -1,5 +1,7 @@ configuration = $this->createMock(Configuration::class); $this->entityManager = $this->createEntityManager(); @@ -47,7 +43,7 @@ protected function setUp() : void ->will($this->returnValue(DDC869PaymentRepository::class)); } - public function testCreatesRepositoryFromDefaultRepositoryClass() + public function testCreatesRepositoryFromDefaultRepositoryClass(): void { $this->entityManager ->expects($this->any()) @@ -56,11 +52,11 @@ public function testCreatesRepositoryFromDefaultRepositoryClass() $this->assertInstanceOf( DDC869PaymentRepository::class, - $this->repositoryFactory->getRepository($this->entityManager, __CLASS__) + $this->repositoryFactory->getRepository($this->entityManager, self::class) ); } - public function testCreatedRepositoriesAreCached() + public function testCreatedRepositoriesAreCached(): void { $this->entityManager ->expects($this->any()) @@ -68,14 +64,14 @@ public function testCreatedRepositoriesAreCached() ->will($this->returnCallback([$this, 'buildClassMetadata'])); $this->assertSame( - $this->repositoryFactory->getRepository($this->entityManager, __CLASS__), - $this->repositoryFactory->getRepository($this->entityManager, __CLASS__) + $this->repositoryFactory->getRepository($this->entityManager, self::class), + $this->repositoryFactory->getRepository($this->entityManager, self::class) ); } - public function testCreatesRepositoryFromCustomClassMetadata() + public function testCreatesRepositoryFromCustomClassMetadata(): void { - $customMetadata = $this->buildClassMetadata(__DIR__); + $customMetadata = $this->buildClassMetadata(__DIR__); $customMetadata->customRepositoryClassName = DDC753DefaultRepository::class; $this->entityManager @@ -85,11 +81,11 @@ public function testCreatesRepositoryFromCustomClassMetadata() $this->assertInstanceOf( DDC753DefaultRepository::class, - $this->repositoryFactory->getRepository($this->entityManager, __CLASS__) + $this->repositoryFactory->getRepository($this->entityManager, self::class) ); } - public function testCachesDistinctRepositoriesPerDistinctEntityManager() + public function testCachesDistinctRepositoriesPerDistinctEntityManager(): void { $em1 = $this->createEntityManager(); $em2 = $this->createEntityManager(); @@ -102,26 +98,24 @@ public function testCachesDistinctRepositoriesPerDistinctEntityManager() ->method('getClassMetadata') ->will($this->returnCallback([$this, 'buildClassMetadata'])); - $repo1 = $this->repositoryFactory->getRepository($em1, __CLASS__); - $repo2 = $this->repositoryFactory->getRepository($em2, __CLASS__); + $repo1 = $this->repositoryFactory->getRepository($em1, self::class); + $repo2 = $this->repositoryFactory->getRepository($em2, self::class); - $this->assertSame($repo1, $this->repositoryFactory->getRepository($em1, __CLASS__)); - $this->assertSame($repo2, $this->repositoryFactory->getRepository($em2, __CLASS__)); + $this->assertSame($repo1, $this->repositoryFactory->getRepository($em1, self::class)); + $this->assertSame($repo2, $this->repositoryFactory->getRepository($em2, self::class)); $this->assertNotSame($repo1, $repo2); } /** - * @private - * - * @param string $className + * @return PHPUnit_Framework_MockObject_MockObject|ClassMetadata * - * @return \PHPUnit_Framework_MockObject_MockObject|\Doctrine\ORM\Mapping\ClassMetadata + * @private */ - public function buildClassMetadata($className) + public function buildClassMetadata(string $className) { - /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadata|\PHPUnit_Framework_MockObject_MockObject */ $metadata = $this->createMock(ClassMetadata::class); + assert($metadata instanceof ClassMetadata || $metadata instanceof PHPUnit_Framework_MockObject_MockObject); $metadata->expects($this->any())->method('getName')->will($this->returnValue($className)); @@ -131,7 +125,7 @@ public function buildClassMetadata($className) } /** - * @return \Doctrine\ORM\EntityManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @return EntityManagerInterface|PHPUnit_Framework_MockObject_MockObject */ private function createEntityManager() { diff --git a/tests/Doctrine/Tests/ORM/Tools/AttachEntityListenersListenerTest.php b/tests/Doctrine/Tests/ORM/Tools/AttachEntityListenersListenerTest.php index b1b1d4ab738..1452e8c450f 100644 --- a/tests/Doctrine/Tests/ORM/Tools/AttachEntityListenersListenerTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/AttachEntityListenersListenerTest.php @@ -1,43 +1,42 @@ listener = new AttachEntityListenersListener(); $driver = $this->createAnnotationDriver(); $this->em = $this->_getTestEntityManager(); $evm = $this->em->getEventManager(); - $this->factory = new ClassMetadataFactory; + $this->factory = new ClassMetadataFactory(); $evm->addEventListener(Events::loadClassMetadata, $this->listener); $this->em->getConfiguration()->setMetadataDriverImpl($driver); $this->factory->setEntityManager($this->em); } - public function testAttachEntityListeners() + public function testAttachEntityListeners(): void { $this->listener->addEntityListener( AttachEntityListenersListenerTestFooEntity::class, @@ -54,7 +53,7 @@ public function testAttachEntityListeners() $this->assertEquals(AttachEntityListenersListenerTestListener::class, $metadata->entityListeners['postLoad'][0]['class']); } - public function testAttachToExistingEntityListeners() + public function testAttachToExistingEntityListeners(): void { $this->listener->addEntityListener( AttachEntityListenersListenerTestBarEntity::class, @@ -90,7 +89,7 @@ public function testAttachToExistingEntityListeners() $this->assertEquals(AttachEntityListenersListenerTestListener2::class, $metadata->entityListeners['postPersist'][1]['class']); } - public function testDuplicateEntityListenerException() + public function testDuplicateEntityListenerException(): void { $this->expectException('Doctrine\ORM\Mapping\MappingException'); $this->expectExceptionMessage('Entity Listener "Doctrine\Tests\ORM\Tools\AttachEntityListenersListenerTestListener#postPersist()" in "Doctrine\Tests\ORM\Tools\AttachEntityListenersListenerTestFooEntity" was already declared, but it must be declared only once.'); @@ -141,17 +140,17 @@ class AttachEntityListenersListenerTestListener { public $calls; - public function prePersist() + public function prePersist(): void { $this->calls[__FUNCTION__][] = func_get_args(); } - public function postLoadHandler() + public function postLoadHandler(): void { $this->calls[__FUNCTION__][] = func_get_args(); } - public function postPersist() + public function postPersist(): void { $this->calls[__FUNCTION__][] = func_get_args(); } @@ -161,12 +160,12 @@ class AttachEntityListenersListenerTestListener2 { public $calls; - public function prePersist() + public function prePersist(): void { $this->calls[__FUNCTION__][] = func_get_args(); } - public function postPersistHandler() + public function postPersistHandler(): void { $this->calls[__FUNCTION__][] = func_get_args(); } diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheCollectionRegionCommandTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheCollectionRegionCommandTest.php index c105be11287..5a6563701bb 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 @@ enableSecondLevelCache(); parent::setUp(); @@ -37,7 +35,7 @@ protected function setUp() : void $this->application->add($this->command); } - public function testClearAllRegion() + public function testClearAllRegion(): void { $command = $this->application->find('orm:clear-cache:region:collection'); $tester = new CommandTester($command); @@ -53,7 +51,7 @@ public function testClearAllRegion() self::assertStringContainsString(' // Clearing all second-level cache collection regions', $tester->getDisplay()); } - public function testClearByOwnerEntityClassName() + public function testClearByOwnerEntityClassName(): void { $command = $this->application->find('orm:clear-cache:region:collection'); $tester = new CommandTester($command); @@ -73,7 +71,7 @@ public function testClearByOwnerEntityClassName() ); } - public function testClearCacheEntryName() + public function testClearCacheEntryName(): void { $command = $this->application->find('orm:clear-cache:region:collection'); $tester = new CommandTester($command); @@ -96,7 +94,7 @@ public function testClearCacheEntryName() self::assertStringContainsString(' // entity identified by "1"', $tester->getDisplay()); } - public function testFlushRegionName() + public function testFlushRegionName(): void { $command = $this->application->find('orm:clear-cache:region:collection'); $tester = new CommandTester($command); diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheEntityRegionCommandTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheEntityRegionCommandTest.php index f7493e6eb87..9d263710f1f 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 @@ enableSecondLevelCache(); parent::setUp(); @@ -37,7 +35,7 @@ protected function setUp() : void $this->application->add($this->command); } - public function testClearAllRegion() + public function testClearAllRegion(): void { $command = $this->application->find('orm:clear-cache:region:entity'); $tester = new CommandTester($command); @@ -53,7 +51,7 @@ public function testClearAllRegion() self::assertStringContainsString(' // Clearing all second-level cache entity regions', $tester->getDisplay()); } - public function testClearByEntityClassName() + public function testClearByEntityClassName(): void { $command = $this->application->find('orm:clear-cache:region:entity'); $tester = new CommandTester($command); @@ -72,7 +70,7 @@ public function testClearByEntityClassName() ); } - public function testClearCacheEntryName() + public function testClearCacheEntryName(): void { $command = $this->application->find('orm:clear-cache:region:entity'); $tester = new CommandTester($command); @@ -94,7 +92,7 @@ public function testClearCacheEntryName() self::assertStringContainsString(' // "1"', $tester->getDisplay()); } - public function testFlushRegionName() + public function testFlushRegionName(): void { $command = $this->application->find('orm:clear-cache:region:entity'); $tester = new CommandTester($command); diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheQueryRegionCommandTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheQueryRegionCommandTest.php index 61802ea6e96..aa2fef5fa63 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 @@ enableSecondLevelCache(); parent::setUp(); @@ -36,7 +34,7 @@ protected function setUp() : void $this->application->add($this->command); } - public function testClearAllRegion() + public function testClearAllRegion(): void { $command = $this->application->find('orm:clear-cache:region:query'); $tester = new CommandTester($command); @@ -52,7 +50,7 @@ public function testClearAllRegion() self::assertStringContainsString(' // Clearing all second-level cache query regions', $tester->getDisplay()); } - public function testClearDefaultRegionName() + public function testClearDefaultRegionName(): void { $command = $this->application->find('orm:clear-cache:region:query'); $tester = new CommandTester($command); @@ -71,7 +69,7 @@ public function testClearDefaultRegionName() ); } - public function testClearByRegionName() + public function testClearByRegionName(): void { $command = $this->application->find('orm:clear-cache:region:query'); $tester = new CommandTester($command); @@ -90,7 +88,7 @@ public function testClearByRegionName() ); } - public function testFlushRegionName() + public function testFlushRegionName(): void { $command = $this->application->find('orm:clear-cache:region:query'); $tester = new CommandTester($command); diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommandTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommandTest.php index f21a9a64d3a..7fa6a03e929 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommandTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommandTest.php @@ -1,5 +1,7 @@ assertHasDeprecationMessages(); } - public function testExecution() + public function testExecution(): void { $entityGenerator = $this->createMock(EntityGenerator::class); - $command = new ConvertDoctrine1SchemaCommand(); + $command = new ConvertDoctrine1SchemaCommand(); $command->setEntityGenerator($entityGenerator); $output = $this->createMock(OutputInterface::class); diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/Command/GenerateRepositoriesCommandTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/Command/GenerateRepositoriesCommandTest.php index b487cba5668..14ccabb66ab 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 = \sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid('doctrine_'); + $this->path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid('doctrine_'); - \mkdir($this->path); + mkdir($this->path); $metadataDriver = $this->_em->getConfiguration()->getMetadataDriverImpl(); $metadataDriver->addPaths([__DIR__ . '/../../../../Models/DDC3231/']); @@ -44,18 +58,15 @@ protected function setUp() : void $this->application->add(new GenerateRepositoriesCommand()); } - /** - * @inheritdoc - */ - public function tearDown() : void + public function tearDown(): void { $dirs = []; - $ri = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->path)); - foreach ($ri AS $file) { - /* @var $file \SplFileInfo */ + $ri = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->path)); + foreach ($ri as $file) { + assert($file instanceof SplFileInfo); if ($file->isFile()) { - \unlink($file->getPathname()); + unlink($file->getPathname()); } elseif ($file->getBasename() === '.') { $dirs[] = $file->getRealPath(); } @@ -64,13 +75,13 @@ public function tearDown() : void arsort($dirs); foreach ($dirs as $dir) { - \rmdir($dir); + rmdir($dir); } parent::tearDown(); } - public function testGenerateRepositories() + public function testGenerateRepositories(): void { $this->generateRepositories('DDC3231User1'); @@ -86,15 +97,15 @@ public function testGenerateRepositories() self::assertTrue(class_exists($cname)); self::assertTrue(class_exists('DDC3231User1NoNamespaceRepository')); - $repo1 = new \ReflectionClass($cname); - $repo2 = new \ReflectionClass('DDC3231User1NoNamespaceRepository'); + $repo1 = new ReflectionClass($cname); + $repo2 = new ReflectionClass('DDC3231User1NoNamespaceRepository'); self::assertSame(EntityRepository::class, $repo1->getParentClass()->getName()); self::assertSame(EntityRepository::class, $repo2->getParentClass()->getName()); $this->assertHasDeprecationMessages(); } - public function testGenerateRepositoriesCustomDefaultRepository() + public function testGenerateRepositoriesCustomDefaultRepository(): void { $this->generateRepositories('DDC3231User2', DDC3231EntityRepository::class); @@ -110,19 +121,15 @@ public function testGenerateRepositoriesCustomDefaultRepository() self::assertTrue(class_exists($cname)); self::assertTrue(class_exists('DDC3231User2NoNamespaceRepository')); - $repo1 = new \ReflectionClass($cname); - $repo2 = new \ReflectionClass('DDC3231User2NoNamespaceRepository'); + $repo1 = new ReflectionClass($cname); + $repo2 = new ReflectionClass('DDC3231User2NoNamespaceRepository'); self::assertSame(DDC3231EntityRepository::class, $repo1->getParentClass()->getName()); self::assertSame(DDC3231EntityRepository::class, $repo2->getParentClass()->getName()); $this->assertHasDeprecationMessages(); } - /** - * @param string $filter - * @param string $defaultRepository - */ - private function generateRepositories($filter, $defaultRepository = null) + private function generateRepositories(string $filter, ?string $defaultRepository = null): void { if ($defaultRepository) { $this->_em->getConfiguration()->setDefaultRepositoryClassName($defaultRepository); @@ -140,7 +147,7 @@ private function generateRepositories($filter, $defaultRepository = null) ); } - public function testNoMetadataClassesToProcess() : void + public function testNoMetadataClassesToProcess(): void { $configuration = $this->createMock(Configuration::class); $metadataFactory = $this->createMock(ClassMetadataFactory::class); diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/Command/InfoCommandTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/Command/InfoCommandTest.php index 2139017b53c..9843e8dbbb4 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Console/Command/InfoCommandTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Console/Command/InfoCommandTest.php @@ -1,38 +1,34 @@ tester = new CommandTester($this->command); } - public function testListAllClasses() + public function testListAllClasses(): void { $this->tester->execute(['command' => $this->command->getName()]); @@ -53,7 +49,7 @@ public function testListAllClasses() self::assertStringContainsString(City::class, $this->tester->getDisplay()); } - public function testEmptyEntityClassNames() : void + public function testEmptyEntityClassNames(): void { $mappingDriver = $this->createMock(MappingDriver::class); $configuration = $this->createMock(Configuration::class); @@ -88,7 +84,7 @@ public function testEmptyEntityClassNames() : void ); } - public function testInvalidEntityClassMetadata() : void + public function testInvalidEntityClassMetadata(): void { $mappingDriver = $this->createMock(MappingDriver::class); $configuration = $this->createMock(Configuration::class); diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/Command/MappingDescribeCommandTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/Command/MappingDescribeCommandTest.php index 156b9aee5f4..eebdc19f89e 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Console/Command/MappingDescribeCommandTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Console/Command/MappingDescribeCommandTest.php @@ -1,7 +1,10 @@ tester = new CommandTester($this->command); } - public function testShowSpecificFuzzySingle() + public function testShowSpecificFuzzySingle(): void { $this->tester->execute( [ @@ -59,7 +56,7 @@ public function testShowSpecificFuzzySingle() self::assertStringContainsString('Root entity name', $display); } - public function testShowSpecificFuzzyAmbiguous() + public function testShowSpecificFuzzyAmbiguous(): void { $this->expectException('InvalidArgumentException'); $this->expectExceptionMessage('possible matches'); @@ -71,7 +68,7 @@ public function testShowSpecificFuzzyAmbiguous() ); } - public function testShowSpecificNotFound() + public function testShowSpecificNotFound(): void { $this->expectException('InvalidArgumentException'); $this->expectExceptionMessage('Could not find any mapped Entity classes matching "AttractionFooBar"'); @@ -83,4 +80,3 @@ public function testShowSpecificNotFound() ); } } - diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/Command/RunDqlCommandTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/Command/RunDqlCommandTest.php index 7ffc15fe84a..8c90498058a 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 @@ useModelSet('generic'); @@ -47,12 +45,12 @@ protected function setUp() : void $this->tester = new CommandTester($this->command); } - public function testCommandName() + public function testCommandName(): void { self::assertSame($this->command, $this->application->get('orm:run-dql')); } - public function testWillRunQuery() + public function testWillRunQuery(): void { $this->_em->persist(new DateTimeModel()); $this->_em->flush(); @@ -70,7 +68,7 @@ public function testWillRunQuery() self::assertStringContainsString(DateTimeModel::class, $this->tester->getDisplay()); } - public function testWillShowQuery() + public function testWillShowQuery(): void { $this->_em->persist(new DateTimeModel()); $this->_em->flush(); diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/ConsoleRunnerTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/ConsoleRunnerTest.php index 62225a87e83..9ed41795b16 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Console/ConsoleRunnerTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Console/ConsoleRunnerTest.php @@ -1,5 +1,7 @@ has('orm:validate-schema')); } - public function testCreateApplicationShouldAppendGivenCommands() : void + public function testCreateApplicationShouldAppendGivenCommands(): void { $command = 'my:lovely-command'; $app = ConsoleRunner::createApplication(new HelperSet(), [new Command($command)]); diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/MetadataFilterTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/MetadataFilterTest.php index 24f3b54a3a8..7ba8502e167 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Console/MetadataFilterTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Console/MetadataFilterTest.php @@ -1,23 +1,26 @@ cmf->setEntityManager($em); } - public function testFilterWithEmptyArray() : void + public function testFilterWithEmptyArray(): void { $originalMetadatas = [ $metadataAaa = $this->cmf->getMetadataFor(MetadataFilterTestEntityAaa::class), @@ -45,7 +48,7 @@ public function testFilterWithEmptyArray() : void $this->assertCount(count($originalMetadatas), $metadatas); } - public function testFilterWithString() : void + public function testFilterWithString(): void { $originalMetadatas = [ $metadataAaa = $this->cmf->getMetadataFor(MetadataFilterTestEntityAaa::class), @@ -78,7 +81,7 @@ public function testFilterWithString() : void $this->assertCount(1, $metadatas); } - public function testFilterWithString2() : void + public function testFilterWithString2(): void { $originalMetadatas = [ $metadataFoo = $this->cmf->getMetadataFor(MetadataFilterTestEntityFoo::class), @@ -95,7 +98,7 @@ public function testFilterWithString2() : void $this->assertCount(2, $metadatas); } - public function testFilterWithArray() : void + public function testFilterWithArray(): void { $originalMetadatas = [ $metadataAaa = $this->cmf->getMetadataFor(MetadataFilterTestEntityAaa::class), @@ -115,7 +118,7 @@ public function testFilterWithArray() : void $this->assertCount(2, $metadatas); } - public function testFilterWithRegex() : void + public function testFilterWithRegex(): void { $originalMetadatas = [ $metadataFoo = $this->cmf->getMetadataFor(MetadataFilterTestEntityFoo::class), diff --git a/tests/Doctrine/Tests/ORM/Tools/ConvertDoctrine1SchemaTest.php b/tests/Doctrine/Tests/ORM/Tools/ConvertDoctrine1SchemaTest.php index fe7959ca36f..c0c4fa568b9 100644 --- a/tests/Doctrine/Tests/ORM/Tools/ConvertDoctrine1SchemaTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/ConvertDoctrine1SchemaTest.php @@ -1,29 +1,31 @@ - * @author Roman Borschel setProxyDir(__DIR__ . '/../../Proxies'); $config->setProxyNamespace('Doctrine\Tests\Proxies'); $eventManager = new EventManager(); - $conn = new ConnectionMock([], $driverMock, $config, $eventManager); + $conn = new ConnectionMock([], $driverMock, $config, $eventManager); $config->setMetadataDriverImpl($metadataDriver); return EntityManagerMock::create($conn, $config, $eventManager); } - public function testTest() + public function testTest(): void { - if ( ! class_exists('Symfony\Component\Yaml\Yaml', true)) { + 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(); + $cme = new ClassMetadataExporter(); $converter = new ConvertDoctrine1Schema(__DIR__ . '/doctrine1schema'); $exporter = $cme->getExporter('yml', __DIR__ . '/convert'); @@ -60,12 +62,12 @@ public function testTest() $this->assertTrue(file_exists(__DIR__ . '/convert/Profile.dcm.yml')); $metadataDriver = new YamlDriver(__DIR__ . '/convert'); - $em = $this->_createEntityManager($metadataDriver); - $cmf = new DisconnectedClassMetadataFactory(); + $em = $this->_createEntityManager($metadataDriver); + $cmf = new DisconnectedClassMetadataFactory(); $cmf->setEntityManager($em); - $metadata = $cmf->getAllMetadata(); + $metadata = $cmf->getAllMetadata(); $profileClass = $cmf->getMetadataFor('Profile'); - $userClass = $cmf->getMetadataFor('User'); + $userClass = $cmf->getMetadataFor('User'); $this->assertEquals(2, count($metadata)); $this->assertEquals('Profile', $profileClass->name); @@ -83,7 +85,7 @@ public function testTest() $this->assertHasDeprecationMessages(); } - public function tearDown() : void + public function tearDown(): void { @unlink(__DIR__ . '/convert/User.dcm.yml'); @unlink(__DIR__ . '/convert/Profile.dcm.yml'); diff --git a/tests/Doctrine/Tests/ORM/Tools/EntityGeneratorTest.php b/tests/Doctrine/Tests/ORM/Tools/EntityGeneratorTest.php index a3b70b2e6b5..0df1d884024 100644 --- a/tests/Doctrine/Tests/ORM/Tools/EntityGeneratorTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/EntityGeneratorTest.php @@ -1,7 +1,10 @@ _namespace = uniqid("doctrine_"); - $this->_tmpDir = \sys_get_temp_dir(); - \mkdir($this->_tmpDir . \DIRECTORY_SEPARATOR . $this->_namespace); + $this->_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->setAnnotationPrefix(''); $this->_generator->setGenerateAnnotations(true); $this->_generator->setGenerateStubMethods(true); $this->_generator->setRegenerateEntityIfExists(false); @@ -40,38 +70,37 @@ protected function setUp() : void $this->_generator->setFieldVisibility(EntityGenerator::FIELD_VISIBLE_PROTECTED); } - public function tearDown() : void + public function tearDown(): void { - $ri = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->_tmpDir . '/' . $this->_namespace)); - foreach ($ri AS $file) { - /* @var $file \SplFileInfo */ + $ri = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->_tmpDir . '/' . $this->_namespace)); + foreach ($ri as $file) { + assert($file instanceof SplFileInfo); if ($file->isFile()) { - \unlink($file->getPathname()); + unlink($file->getPathname()); } } + rmdir($this->_tmpDir . '/' . $this->_namespace); } /** @after */ - public function ensureTestGeneratedDeprecationMessages() : void + public function ensureTestGeneratedDeprecationMessages(): void { $this->assertHasDeprecationMessages(); } /** * @param ClassMetadataInfo[] $embeddedClasses - * - * @return ClassMetadataInfo */ - public function generateBookEntityFixture(array $embeddedClasses = []) + public function generateBookEntityFixture(array $embeddedClasses = []): ClassMetadataInfo { - $metadata = new ClassMetadataInfo($this->_namespace . '\EntityGeneratorBook'); - $metadata->namespace = $this->_namespace; - $metadata->customRepositoryClassName = $this->_namespace . '\EntityGeneratorBookRepository'; + $metadata = new ClassMetadataInfo($this->_namespace . '\EntityGeneratorBook'); + $metadata->namespace = $this->_namespace; + $metadata->customRepositoryClassName = $this->_namespace . '\EntityGeneratorBookRepository'; - $metadata->table['name'] = 'book'; + $metadata->table['name'] = 'book'; $metadata->table['uniqueConstraints']['name_uniq'] = ['columns' => ['name']]; - $metadata->table['indexes']['status_idx'] = ['columns' => ['status']]; + $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]); @@ -79,18 +108,18 @@ public function generateBookEntityFixture(array $embeddedClasses = []) ['fieldName' => 'author', 'targetEntity' => EntityGeneratorAuthor::class, 'mappedBy' => 'book'] ); $joinColumns = [ - ['name' => 'author_id', 'referencedColumnName' => 'id'] + ['name' => 'author_id', 'referencedColumnName' => 'id'], ]; $metadata->mapManyToMany( [ - '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']], - ], + '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']], + ], ] ); $metadata->addLifecycleCallback('loading', 'postLoad'); @@ -109,15 +138,15 @@ public function generateBookEntityFixture(array $embeddedClasses = []) private function generateEntityTypeFixture(array $field) { - $metadata = new ClassMetadataInfo($this->_namespace . '\EntityType'); + $metadata = new ClassMetadataInfo($this->_namespace . '\EntityType'); $metadata->namespace = $this->_namespace; $metadata->table['name'] = 'entity_type'; $metadata->mapField(['fieldName' => 'id', 'type' => 'integer', 'id' => true]); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); - $name = $field['fieldName']; - $type = $field['dbType']; + $name = $field['fieldName']; + $type = $field['dbType']; $metadata->mapField(['fieldName' => $name, 'type' => $type]); $this->_generator->writeEntityClass($metadata, $this->_tmpDir); @@ -125,13 +154,10 @@ private function generateEntityTypeFixture(array $field) return $metadata; } - /** - * @return ClassMetadataInfo - */ - private function generateIsbnEmbeddableFixture(array $embeddedClasses = [], $columnPrefix = null) + private function generateIsbnEmbeddableFixture(array $embeddedClasses = [], $columnPrefix = null): ClassMetadataInfo { - $metadata = new ClassMetadataInfo($this->_namespace . '\EntityGeneratorIsbn'); - $metadata->namespace = $this->_namespace; + $metadata = new ClassMetadataInfo($this->_namespace . '\EntityGeneratorIsbn'); + $metadata->namespace = $this->_namespace; $metadata->isEmbeddedClass = true; $metadata->mapField(['fieldName' => 'prefix', 'type' => 'integer']); $metadata->mapField(['fieldName' => 'groupNumber', 'type' => 'integer']); @@ -148,13 +174,10 @@ private function generateIsbnEmbeddableFixture(array $embeddedClasses = [], $col return $metadata; } - /** - * @return ClassMetadataInfo - */ - private function generateTestEmbeddableFixture() + private function generateTestEmbeddableFixture(): ClassMetadataInfo { - $metadata = new ClassMetadataInfo($this->_namespace . '\EntityGeneratorTestEmbeddable'); - $metadata->namespace = $this->_namespace; + $metadata = new ClassMetadataInfo($this->_namespace . '\EntityGeneratorTestEmbeddable'); + $metadata->namespace = $this->_namespace; $metadata->isEmbeddedClass = true; $metadata->mapField(['fieldName' => 'field1', 'type' => 'integer']); $metadata->mapField(['fieldName' => 'field2', 'type' => 'integer', 'nullable' => true]); @@ -166,55 +189,41 @@ private function generateTestEmbeddableFixture() return $metadata; } - /** - * @param string $fieldName - * @param ClassMetadataInfo $classMetadata - * @param ClassMetadataInfo $embeddableMetadata - * @param string|null $columnPrefix - */ private function mapEmbedded( - $fieldName, + string $fieldName, ClassMetadataInfo $classMetadata, ClassMetadataInfo $embeddableMetadata, - $columnPrefix = false - ) { + ?string $columnPrefix = false + ): void { $classMetadata->mapEmbedded( ['fieldName' => $fieldName, 'class' => $embeddableMetadata->name, 'columnPrefix' => $columnPrefix] ); } - /** - * @param string $fieldName - * @param ClassMetadataInfo $classMetadata - * @param ClassMetadataInfo $embeddableMetadata - */ private function mapNestedEmbedded( - $fieldName, + string $fieldName, ClassMetadataInfo $classMetadata, ClassMetadataInfo $embeddableMetadata - ) { + ): void { foreach ($embeddableMetadata->embeddedClasses as $property => $embeddableClass) { $classMetadata->mapEmbedded( [ - 'fieldName' => $fieldName . '.' . $property, - 'class' => $embeddableClass['class'], - 'columnPrefix' => $embeddableClass['columnPrefix'], - 'declaredField' => $embeddableClass['declaredField'] + 'fieldName' => $fieldName . '.' . $property, + 'class' => $embeddableClass['class'], + 'columnPrefix' => $embeddableClass['columnPrefix'], + 'declaredField' => $embeddableClass['declaredField'] ? $fieldName . '.' . $embeddableClass['declaredField'] : $fieldName, - 'originalField' => $embeddableClass['originalField'] ?: $property, + 'originalField' => $embeddableClass['originalField'] ?: $property, ] ); } } - /** - * @param ClassMetadataInfo $metadata - */ - private function loadEntityClass(ClassMetadataInfo $metadata) + private function loadEntityClass(ClassMetadataInfo $metadata): void { $className = basename(str_replace('\\', '/', $metadata->name)); - $path = $this->_tmpDir . '/' . $this->_namespace . '/' . $className . '.php'; + $path = $this->_tmpDir . '/' . $this->_namespace . '/' . $className . '.php'; $this->assertFileExists($path); @@ -222,73 +231,71 @@ private function loadEntityClass(ClassMetadataInfo $metadata) } /** - * @param ClassMetadataInfo $metadata - * * @return mixed An instance of the given metadata's class. */ - public function newInstance($metadata) + public function newInstance(ClassMetadataInfo $metadata) { $this->loadEntityClass($metadata); - return new $metadata->name; + return new $metadata->name(); } /** * @group GH-6314 */ - public function testEmbeddedEntityWithNamedColumnPrefix() + public function testEmbeddedEntityWithNamedColumnPrefix(): void { $columnPrefix = 'GH6314Prefix_'; $testMetadata = $this->generateTestEmbeddableFixture(); $isbnMetadata = $this->generateIsbnEmbeddableFixture(['testEmbedded' => $testMetadata], $columnPrefix); - $isbnEntity = $this->newInstance($isbnMetadata); - $refClass = new \ReflectionClass($isbnEntity); + $isbnEntity = $this->newInstance($isbnMetadata); + $refClass = new ReflectionClass($isbnEntity); 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->name, $columnPrefix); self::assertStringContainsString($needle, $docComment); } /** * @group GH-6314 */ - public function testEmbeddedEntityWithoutColumnPrefix() + public function testEmbeddedEntityWithoutColumnPrefix(): void { $testMetadata = $this->generateTestEmbeddableFixture(); $isbnMetadata = $this->generateIsbnEmbeddableFixture(['testEmbedded' => $testMetadata], false); - $isbnEntity = $this->newInstance($isbnMetadata); - $refClass = new \ReflectionClass($isbnEntity); + $isbnEntity = $this->newInstance($isbnMetadata); + $refClass = new ReflectionClass($isbnEntity); 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->name); self::assertStringContainsString($needle, $docComment); } - public function testGeneratedEntityClass() + public function testGeneratedEntityClass(): void { $testMetadata = $this->generateTestEmbeddableFixture(); $isbnMetadata = $this->generateIsbnEmbeddableFixture(['test' => $testMetadata]); - $metadata = $this->generateBookEntityFixture(['isbn' => $isbnMetadata]); + $metadata = $this->generateBookEntityFixture(['isbn' => $isbnMetadata]); $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->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()); @@ -298,11 +305,11 @@ public function testGeneratedEntityClass() $book->setName('Jonathan H. Wage'); $this->assertEquals('Jonathan H. Wage', $book->getName()); - $reflMethod = new \ReflectionMethod($metadata->name, 'addComment'); + $reflMethod = new ReflectionMethod($metadata->name, 'addComment'); $addCommentParameters = $reflMethod->getParameters(); $this->assertEquals('comment', $addCommentParameters[0]->getName()); - $reflMethod = new \ReflectionMethod($metadata->name, 'removeComment'); + $reflMethod = new ReflectionMethod($metadata->name, 'removeComment'); $removeCommentParameters = $reflMethod->getParameters(); $this->assertEquals('comment', $removeCommentParameters[0]->getName()); @@ -323,12 +330,12 @@ public function testGeneratedEntityClass() $book->setIsbn($isbn); $this->assertSame($isbn, $book->getIsbn()); - $reflMethod = new \ReflectionMethod($metadata->name, 'setIsbn'); + $reflMethod = new ReflectionMethod($metadata->name, 'setIsbn'); $reflParameters = $reflMethod->getParameters(); $this->assertEquals($isbnMetadata->name, $reflParameters[0]->getType()->getName()); } - public function testBooleanDefaultValue() + public function testBooleanDefaultValue(): void { $metadata = $this->generateBookEntityFixture(['isbn' => $this->generateIsbnEmbeddableFixture()]); @@ -347,7 +354,7 @@ public function testBooleanDefaultValue() $this->assertTrue($book->getfoo()); } - public function testEntityUpdatingWorks() + public function testEntityUpdatingWorks(): void { $metadata = $this->generateBookEntityFixture(['isbn' => $this->generateIsbnEmbeddableFixture()]); @@ -358,20 +365,20 @@ public function testEntityUpdatingWorks() $this->_generator->writeEntityClass($metadata, $this->_tmpDir); - $this->assertFileExists($this->_tmpDir . "/" . $this->_namespace . "/EntityGeneratorBook.php~"); + $this->assertFileExists($this->_tmpDir . '/' . $this->_namespace . '/EntityGeneratorBook.php~'); - $book = $this->newInstance($metadata); - $reflClass = new \ReflectionClass($metadata->name); + $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->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."); @@ -391,22 +398,22 @@ public function testEntityUpdatingWorks() /** * @group DDC-3152 */ - public function testDoesNotRegenerateExistingMethodsWithDifferentCase() + public function testDoesNotRegenerateExistingMethodsWithDifferentCase(): void { $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']; + $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->assertFileExists($this->_tmpDir . '/' . $this->_namespace . '/EntityGeneratorBook.php~'); $this->newInstance($metadata); - $reflClass = new \ReflectionClass($metadata->name); + $reflClass = new ReflectionClass($metadata->name); $this->assertTrue($reflClass->hasProperty('status')); $this->assertTrue($reflClass->hasProperty('STATUS')); @@ -421,30 +428,30 @@ public function testDoesNotRegenerateExistingMethodsWithDifferentCase() /** * @group DDC-2121 */ - public function testMethodDocBlockShouldStartWithBackSlash() + public function testMethodDocBlockShouldStartWithBackSlash(): void { $embeddedMetadata = $this->generateIsbnEmbeddableFixture(); - $metadata = $this->generateBookEntityFixture(['isbn' => $embeddedMetadata]); - $book = $this->newInstance($metadata); + $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\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')); + $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')); + $this->assertPhpDocVarType($expectedClassName, new ReflectionProperty($book, 'isbn')); + $this->assertPhpDocReturnType($expectedClassName, new ReflectionMethod($book, 'getIsbn')); + $this->assertPhpDocParamType($expectedClassName, new ReflectionMethod($book, 'setIsbn')); } - public function testEntityExtendsStdClass() + public function testEntityExtendsStdClass(): void { $this->_generator->setClassToExtend('stdClass'); $metadata = $this->generateBookEntityFixture(); @@ -453,25 +460,25 @@ public function testEntityExtendsStdClass() $this->assertInstanceOf('stdClass', $book); $metadata = $this->generateIsbnEmbeddableFixture(); - $isbn = $this->newInstance($metadata); + $isbn = $this->newInstance($metadata); $this->assertInstanceOf('stdClass', $isbn); } - public function testLifecycleCallbacks() + public function testLifecycleCallbacks(): void { $metadata = $this->generateBookEntityFixture(); - $book = $this->newInstance($metadata); - $reflClass = new \ReflectionClass($metadata->name); + $book = $this->newInstance($metadata); + $reflClass = new ReflectionClass($metadata->name); - $this->assertTrue($reflClass->hasMethod('loading'), "Check for postLoad lifecycle callback."); - $this->assertTrue($reflClass->hasMethod('willBeRemoved'), "Check for preRemove lifecycle callback."); + $this->assertTrue($reflClass->hasMethod('loading'), 'Check for postLoad lifecycle callback.'); + $this->assertTrue($reflClass->hasMethod('willBeRemoved'), 'Check for preRemove lifecycle callback.'); } - public function testLoadMetadata() + public function testLoadMetadata(): void { $embeddedMetadata = $this->generateIsbnEmbeddableFixture(); - $metadata = $this->generateBookEntityFixture(['isbn' => $embeddedMetadata]); + $metadata = $this->generateBookEntityFixture(['isbn' => $embeddedMetadata]); $book = $this->newInstance($metadata); @@ -506,11 +513,11 @@ public function testLoadMetadata() $this->assertEquals($cm->isEmbeddedClass, $embeddedMetadata->isEmbeddedClass); } - public function testLoadPrefixedMetadata() + public function testLoadPrefixedMetadata(): void { $this->_generator->setAnnotationPrefix('ORM\\'); $embeddedMetadata = $this->generateIsbnEmbeddableFixture(); - $metadata = $this->generateBookEntityFixture(['isbn' => $embeddedMetadata]); + $metadata = $this->generateBookEntityFixture(['isbn' => $embeddedMetadata]); $reader = new AnnotationReader(); $driver = new AnnotationDriver($reader, []); @@ -546,7 +553,7 @@ public function testLoadPrefixedMetadata() /** * @group DDC-3272 */ - public function testMappedSuperclassAnnotationGeneration() + public function testMappedSuperclassAnnotationGeneration(): void { $metadata = new ClassMetadataInfo($this->_namespace . '\EntityGeneratorBook'); $metadata->namespace = $this->_namespace; @@ -559,7 +566,7 @@ public function testMappedSuperclassAnnotationGeneration() $driver = new AnnotationDriver(new AnnotationReader(), []); $cm = new ClassMetadataInfo($metadata->name); - $cm->initializeReflection(new RuntimeReflectionService); + $cm->initializeReflection(new RuntimeReflectionService()); $driver->loadMetadataForClass($cm->name, $cm); $this->assertTrue($cm->isMappedSuperclass); @@ -568,9 +575,9 @@ public function testMappedSuperclassAnnotationGeneration() /** * @dataProvider getParseTokensInEntityFileData */ - public function testParseTokensInEntityFile($php, $classes) + public function testParseTokensInEntityFile($php, $classes): void { - $r = new \ReflectionObject($this->_generator); + $r = new ReflectionObject($this->_generator); $m = $r->getMethod('parseTokensInEntityFile'); $m->setAccessible(true); @@ -584,17 +591,17 @@ public function testParseTokensInEntityFile($php, $classes) /** * @group DDC-1784 */ - public function testGenerateEntityWithSequenceGenerator() + public function testGenerateEntityWithSequenceGenerator(): void { - $metadata = new ClassMetadataInfo($this->_namespace . '\DDC1784Entity'); - $metadata->namespace = $this->_namespace; + $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( [ - 'sequenceName' => 'DDC1784_ID_SEQ', - 'allocationSize' => 1, - 'initialValue' => 2 + 'sequenceName' => 'DDC1784_ID_SEQ', + 'allocationSize' => 1, + 'initialValue' => 2, ] ); $this->_generator->writeEntityClass($metadata, $this->_tmpDir); @@ -605,8 +612,7 @@ public function testGenerateEntityWithSequenceGenerator() $this->assertFileExists($filename); require_once $filename; - - $reflection = new \ReflectionProperty($metadata->name, 'id'); + $reflection = new ReflectionProperty($metadata->name, 'id'); $docComment = $reflection->getDocComment(); $this->assertStringContainsString('@Id', $docComment); @@ -621,27 +627,27 @@ public function testGenerateEntityWithSequenceGenerator() /** * @group DDC-2079 */ - public function testGenerateEntityWithMultipleInverseJoinColumns() + public function testGenerateEntityWithMultipleInverseJoinColumns(): void { - $metadata = new ClassMetadataInfo($this->_namespace . '\DDC2079Entity'); - $metadata->namespace = $this->_namespace; + $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'] + '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'], + ], ], - 'inverseJoinColumns' => [ - ['name' => 'idcentrocusto', 'referencedColumnName' => 'idcentrocusto'], - ['name' => 'idpais', 'referencedColumnName' => 'idpais'], - ], - ], ] ); $this->_generator->writeEntityClass($metadata, $this->_tmpDir); @@ -652,7 +658,7 @@ public function testGenerateEntityWithMultipleInverseJoinColumns() $this->assertFileExists($filename); require_once $filename; - $property = new \ReflectionProperty($metadata->name, 'centroCustos'); + $property = new ReflectionProperty($metadata->name, 'centroCustos'); $docComment = $property->getDocComment(); //joinColumns @@ -676,19 +682,19 @@ public function testGenerateEntityWithMultipleInverseJoinColumns() } /** - * @group DDC-2172 - */ - public function testGetInheritanceTypeString() + * @group DDC-2172 + */ + public function testGetInheritanceTypeString(): void { - $reflection = new \ReflectionClass('\Doctrine\ORM\Mapping\ClassMetadataInfo'); - $method = new \ReflectionMethod($this->_generator, 'getInheritanceTypeString'); + $reflection = new ReflectionClass('\Doctrine\ORM\Mapping\ClassMetadataInfo'); + $method = new ReflectionMethod($this->_generator, 'getInheritanceTypeString'); $constants = $reflection->getConstants(); $pattern = '/^INHERITANCE_TYPE_/'; $method->setAccessible(true); foreach ($constants as $name => $value) { - if( ! preg_match($pattern, $name)) { + if (! preg_match($pattern, $name)) { continue; } @@ -698,26 +704,26 @@ public function testGetInheritanceTypeString() $this->assertEquals($expected, $actual); } - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid provided InheritanceType: INVALID'); $method->invoke($this->_generator, 'INVALID'); } /** - * @group DDC-2172 - */ - public function testGetChangeTrackingPolicyString() + * @group DDC-2172 + */ + public function testGetChangeTrackingPolicyString(): void { - $reflection = new \ReflectionClass('\Doctrine\ORM\Mapping\ClassMetadata'); - $method = new \ReflectionMethod($this->_generator, 'getChangeTrackingPolicyString'); + $reflection = new ReflectionClass('\Doctrine\ORM\Mapping\ClassMetadata'); + $method = new ReflectionMethod($this->_generator, 'getChangeTrackingPolicyString'); $constants = $reflection->getConstants(); $pattern = '/^CHANGETRACKING_/'; $method->setAccessible(true); foreach ($constants as $name => $value) { - if( ! preg_match($pattern, $name)) { + if (! preg_match($pattern, $name)) { continue; } @@ -727,7 +733,7 @@ public function testGetChangeTrackingPolicyString() $this->assertEquals($expected, $actual); } - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid provided ChangeTrackingPolicy: INVALID'); $method->invoke($this->_generator, 'INVALID'); @@ -736,17 +742,17 @@ public function testGetChangeTrackingPolicyString() /** * @group DDC-2172 */ - public function testGetIdGeneratorTypeString() + public function testGetIdGeneratorTypeString(): void { - $reflection = new \ReflectionClass('\Doctrine\ORM\Mapping\ClassMetadataInfo'); - $method = new \ReflectionMethod($this->_generator, 'getIdGeneratorTypeString'); + $reflection = new ReflectionClass('\Doctrine\ORM\Mapping\ClassMetadataInfo'); + $method = new ReflectionMethod($this->_generator, 'getIdGeneratorTypeString'); $constants = $reflection->getConstants(); $pattern = '/^GENERATOR_TYPE_/'; $method->setAccessible(true); foreach ($constants as $name => $value) { - if( ! preg_match($pattern, $name)) { + if (! preg_match($pattern, $name)) { continue; } @@ -756,7 +762,7 @@ public function testGetIdGeneratorTypeString() $this->assertEquals($expected, $actual); } - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid provided IdGeneratorType: INVALID'); $method->invoke($this->_generator, 'INVALID'); @@ -764,25 +770,24 @@ public function testGetIdGeneratorTypeString() /** * @dataProvider getEntityTypeAliasDataProvider - * * @group DDC-1694 */ - public function testEntityTypeAlias(array $field) + public function testEntityTypeAlias(array $field): void { - $metadata = $this->generateEntityTypeFixture($field); - $path = $this->_tmpDir . '/'. $this->_namespace . '/EntityType.php'; + $metadata = $this->generateEntityTypeFixture($field); + $path = $this->_tmpDir . '/' . $this->_namespace . '/EntityType.php'; $this->assertFileExists($path); require_once $path; - $entity = new $metadata->name; - $reflClass = new \ReflectionClass($metadata->name); + $entity = new $metadata->name(); + $reflClass = new ReflectionClass($metadata->name); $type = $field['phpType']; $name = $field['fieldName']; $value = $field['value']; - $getter = "get" . ucfirst($name); - $setter = "set" . ucfirst($name); + $getter = 'get' . ucfirst($name); + $setter = 'set' . ucfirst($name); $this->assertPhpDocVarType($type, $reflClass->getProperty($name)); $this->assertPhpDocParamType($type, $reflClass->getMethod($setter)); @@ -795,23 +800,23 @@ public function testEntityTypeAlias(array $field) /** * @group DDC-2372 */ - public function testTraitPropertiesAndMethodsAreNotDuplicated() + public function testTraitPropertiesAndMethodsAreNotDuplicated(): void { $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"; + $user = new DDC2372User(); + $metadata = $cmf->getMetadataFor(get_class($user)); + $metadata->name = $this->_namespace . '\DDC2372User'; $metadata->namespace = $this->_namespace; $this->_generator->writeEntityClass($metadata, $this->_tmpDir); - $this->assertFileExists($this->_tmpDir . "/" . $this->_namespace . "/DDC2372User.php"); - require $this->_tmpDir . "/" . $this->_namespace . "/DDC2372User.php"; + $this->assertFileExists($this->_tmpDir . '/' . $this->_namespace . '/DDC2372User.php'); + require $this->_tmpDir . '/' . $this->_namespace . '/DDC2372User.php'; - $reflClass = new \ReflectionClass($metadata->name); + $reflClass = new ReflectionClass($metadata->name); $this->assertSame($reflClass->hasProperty('address'), false); $this->assertSame($reflClass->hasMethod('setAddress'), false); @@ -821,23 +826,23 @@ public function testTraitPropertiesAndMethodsAreNotDuplicated() /** * @group DDC-2372 */ - public function testTraitPropertiesAndMethodsAreNotDuplicatedInChildClasses() + public function testTraitPropertiesAndMethodsAreNotDuplicatedInChildClasses(): void { $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"; + $user = new DDC2372Admin(); + $metadata = $cmf->getMetadataFor(get_class($user)); + $metadata->name = $this->_namespace . '\DDC2372Admin'; $metadata->namespace = $this->_namespace; $this->_generator->writeEntityClass($metadata, $this->_tmpDir); - $this->assertFileExists($this->_tmpDir . "/" . $this->_namespace . "/DDC2372Admin.php"); - require $this->_tmpDir . "/" . $this->_namespace . "/DDC2372Admin.php"; + $this->assertFileExists($this->_tmpDir . '/' . $this->_namespace . '/DDC2372Admin.php'); + require $this->_tmpDir . '/' . $this->_namespace . '/DDC2372Admin.php'; - $reflClass = new \ReflectionClass($metadata->name); + $reflClass = new ReflectionClass($metadata->name); $this->assertSame($reflClass->hasProperty('address'), false); $this->assertSame($reflClass->hasMethod('setAddress'), false); @@ -847,15 +852,15 @@ public function testTraitPropertiesAndMethodsAreNotDuplicatedInChildClasses() /** * @group DDC-1590 */ - public function testMethodsAndPropertiesAreNotDuplicatedInChildClasses() + public function testMethodsAndPropertiesAreNotDuplicatedInChildClasses(): void { - $cmf = new ClassMetadataFactory(); - $em = $this->_getTestEntityManager(); + $cmf = new ClassMetadataFactory(); + $em = $this->_getTestEntityManager(); $cmf->setEntityManager($em); - $ns = $this->_namespace; - $nsdir = $this->_tmpDir . '/' . $ns; + $ns = $this->_namespace; + $nsdir = $this->_tmpDir . '/' . $ns; $content = str_replace( 'namespace Doctrine\Tests\Models\DDC1590', @@ -863,11 +868,10 @@ public function testMethodsAndPropertiesAreNotDuplicatedInChildClasses() file_get_contents(__DIR__ . '/../../Models/DDC1590/DDC1590User.php') ); - $fname = $nsdir . "/DDC1590User.php"; + $fname = $nsdir . '/DDC1590User.php'; file_put_contents($fname, $content); require $fname; - $metadata = $cmf->getMetadataFor($ns . '\DDC1590User'); $this->_generator->writeEntityClass($metadata, $this->_tmpDir); @@ -875,20 +879,19 @@ public function testMethodsAndPropertiesAreNotDuplicatedInChildClasses() $source = file_get_contents($fname); // class _DDC1590User extends DDC1590Entity { ... } - $source2 = str_replace('class DDC1590User', 'class _DDC1590User', $source); - $fname2 = $nsdir . "/_DDC1590User.php"; + $source2 = str_replace('class DDC1590User', 'class _DDC1590User', $source); + $fname2 = $nsdir . '/_DDC1590User.php'; file_put_contents($fname2, $source2); require $fname2; // class __DDC1590User { ... } - $source3 = str_replace('class DDC1590User extends DDC1590Entity', 'class __DDC1590User', $source); - $fname3 = $nsdir . "/__DDC1590User.php"; + $source3 = str_replace('class DDC1590User extends DDC1590Entity', 'class __DDC1590User', $source); + $fname3 = $nsdir . '/__DDC1590User.php'; file_put_contents($fname3, $source3); require $fname3; - // class _DDC1590User extends DDC1590Entity { ... } - $rc2 = new \ReflectionClass($ns.'\_DDC1590User'); + $rc2 = new ReflectionClass($ns . '\_DDC1590User'); $this->assertTrue($rc2->hasProperty('name')); $this->assertTrue($rc2->hasProperty('id')); @@ -901,9 +904,8 @@ public function testMethodsAndPropertiesAreNotDuplicatedInChildClasses() $this->assertTrue($rc2->hasMethod('getCreatedAt')); $this->assertTrue($rc2->hasMethod('setCreatedAt')); - // class __DDC1590User { ... } - $rc3 = new \ReflectionClass($ns.'\__DDC1590User'); + $rc3 = new ReflectionClass($ns . '\__DDC1590User'); $this->assertTrue($rc3->hasProperty('name')); $this->assertFalse($rc3->hasProperty('id')); @@ -920,27 +922,27 @@ public function testMethodsAndPropertiesAreNotDuplicatedInChildClasses() /** * @group DDC-3304 */ - public function testGeneratedMutableEmbeddablesClass() + public function testGeneratedMutableEmbeddablesClass(): void { $embeddedMetadata = $this->generateTestEmbeddableFixture(); - $metadata = $this->generateIsbnEmbeddableFixture(['test' => $embeddedMetadata]); + $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."); + $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.'); $isbn->setPrefix(978); $this->assertSame(978, $isbn->getPrefix()); @@ -951,7 +953,7 @@ public function testGeneratedMutableEmbeddablesClass() $isbn->setTest($test); $this->assertSame($test, $isbn->getTest()); - $reflMethod = new \ReflectionMethod($metadata->name, 'setTest'); + $reflMethod = new ReflectionMethod($metadata->name, 'setTest'); $reflParameters = $reflMethod->getParameters(); $this->assertEquals($embeddedMetadata->name, $reflParameters[0]->getType()->getName()); } @@ -959,34 +961,34 @@ public function testGeneratedMutableEmbeddablesClass() /** * @group DDC-3304 */ - public function testGeneratedImmutableEmbeddablesClass() + public function testGeneratedImmutableEmbeddablesClass(): void { $this->_generator->setEmbeddablesImmutable(true); $embeddedMetadata = $this->generateTestEmbeddableFixture(); - $metadata = $this->generateIsbnEmbeddableFixture(['test' => $embeddedMetadata]); + $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()); + $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); - $reflMethod = new \ReflectionMethod($isbn, '__construct'); + $reflMethod = new ReflectionMethod($isbn, '__construct'); $reflParameters = $reflMethod->getParameters(); $this->assertCount(6, $reflParameters); @@ -1010,7 +1012,7 @@ public function testGeneratedImmutableEmbeddablesClass() $this->assertSame('checkDigit', $reflParameters[5]->getName()); $this->assertFalse($reflParameters[5]->isOptional()); - $reflMethod = new \ReflectionMethod($test, '__construct'); + $reflMethod = new ReflectionMethod($test, '__construct'); $reflParameters = $reflMethod->getParameters(); $this->assertCount(4, $reflParameters); @@ -1030,13 +1032,13 @@ public function testGeneratedImmutableEmbeddablesClass() $this->assertTrue($reflParameters[3]->isOptional()); } - public function testRegenerateEntityClass() + public function testRegenerateEntityClass(): void { $metadata = $this->generateBookEntityFixture(); $this->loadEntityClass($metadata); $className = basename(str_replace('\\', '/', $metadata->name)); - $path = $this->_tmpDir . '/' . $this->_namespace . '/' . $className . '.php'; + $path = $this->_tmpDir . '/' . $this->_namespace . '/' . $className . '.php'; $classTest = file_get_contents($path); $this->_generator->setRegenerateEntityIfExists(true); @@ -1045,103 +1047,103 @@ public function testRegenerateEntityClass() $this->_generator->writeEntityClass($metadata, $this->_tmpDir); $classNew = file_get_contents($path); - $this->assertSame($classTest,$classNew); + $this->assertSame($classTest, $classNew); } /** * @return array */ - public function getEntityTypeAliasDataProvider() + public function getEntityTypeAliasDataProvider(): array { return [ [ [ - 'fieldName' => 'datetimetz', - 'phpType' => '\\DateTime', - 'dbType' => 'datetimetz', - 'value' => new \DateTime - ] + 'fieldName' => 'datetimetz', + 'phpType' => '\\DateTime', + 'dbType' => 'datetimetz', + 'value' => new DateTime(), + ], ], [ [ - 'fieldName' => 'datetime', - 'phpType' => '\\DateTime', - 'dbType' => 'datetime', - 'value' => new \DateTime - ] + 'fieldName' => 'datetime', + 'phpType' => '\\DateTime', + 'dbType' => 'datetime', + 'value' => new DateTime(), + ], ], [ [ - 'fieldName' => 'date', - 'phpType' => '\\DateTime', - 'dbType' => 'date', - 'value' => new \DateTime - ] + 'fieldName' => 'date', + 'phpType' => '\\DateTime', + 'dbType' => 'date', + 'value' => new DateTime(), + ], ], [ [ - 'fieldName' => 'time', - 'phpType' => '\DateTime', - 'dbType' => 'time', - 'value' => new \DateTime - ] + 'fieldName' => 'time', + 'phpType' => '\DateTime', + 'dbType' => 'time', + 'value' => new DateTime(), + ], ], [ [ - 'fieldName' => 'object', - 'phpType' => '\stdClass', - 'dbType' => 'object', - 'value' => new \stdClass() - ] + 'fieldName' => 'object', + 'phpType' => '\stdClass', + 'dbType' => 'object', + 'value' => new stdClass(), + ], ], [ [ - 'fieldName' => 'bigint', - 'phpType' => 'int', - 'dbType' => 'bigint', - 'value' => 11 - ] + 'fieldName' => 'bigint', + 'phpType' => 'int', + 'dbType' => 'bigint', + 'value' => 11, + ], ], [ [ - 'fieldName' => 'smallint', - 'phpType' => 'int', - 'dbType' => 'smallint', - 'value' => 22 - ] + 'fieldName' => 'smallint', + 'phpType' => 'int', + 'dbType' => 'smallint', + 'value' => 22, + ], ], [ [ - 'fieldName' => 'text', - 'phpType' => 'string', - 'dbType' => 'text', - 'value' => 'text' - ] + 'fieldName' => 'text', + 'phpType' => 'string', + 'dbType' => 'text', + 'value' => 'text', + ], ], [ [ - 'fieldName' => 'blob', - 'phpType' => 'string', - 'dbType' => 'blob', - 'value' => 'blob' - ] + 'fieldName' => 'blob', + 'phpType' => 'string', + 'dbType' => 'blob', + 'value' => 'blob', + ], ], [ [ 'fieldName' => 'guid', 'phpType' => 'string', 'dbType' => 'guid', - 'value' => '00000000-0000-0000-0000-000000000001' - ] + 'value' => '00000000-0000-0000-0000-000000000001', + ], ], [ [ - 'fieldName' => 'decimal', - 'phpType' => 'string', - 'dbType' => 'decimal', - 'value' => '12.34' + 'fieldName' => 'decimal', + 'phpType' => 'string', + 'dbType' => 'decimal', + 'value' => '12.34', ], - ] + ], ]; } @@ -1187,11 +1189,7 @@ public static function someMethod(){ ]; } - /** - * @param string $type - * @param \ReflectionProperty $property - */ - private function assertPhpDocVarType($type, \ReflectionProperty $property) + private function assertPhpDocVarType(string $type, ReflectionProperty $property): void { $docComment = $property->getDocComment(); $regex = '/@var\s+([\S]+)$/m'; @@ -1201,11 +1199,7 @@ private function assertPhpDocVarType($type, \ReflectionProperty $property) $this->assertEquals($type, $matches[1]); } - /** - * @param string $type - * @param \ReflectionMethod $method - */ - private function assertPhpDocReturnType($type, \ReflectionMethod $method) + private function assertPhpDocReturnType(string $type, ReflectionMethod $method): void { $docComment = $method->getDocComment(); $regex = '/@return\s+([\S]+)(\s+.*)$/m'; @@ -1216,10 +1210,9 @@ private function assertPhpDocReturnType($type, \ReflectionMethod $method) } /** - * @param string $type - * @param \ReflectionProperty $method + * @param ReflectionProperty $method */ - private function assertPhpDocParamType($type, \ReflectionMethod $method) + private function assertPhpDocParamType(string $type, ReflectionMethod $method): void { $this->assertEquals(1, preg_match('/@param\s+([^\s]+)/', $method->getDocComment(), $matches)); $this->assertEquals($type, $matches[1]); @@ -1227,13 +1220,12 @@ private function assertPhpDocParamType($type, \ReflectionMethod $method) /** * @group 6703 - * * @dataProvider columnOptionsProvider */ - public function testOptionsAreGeneratedProperly(string $expectedAnnotation, array $fieldConfiguration) : void + public function testOptionsAreGeneratedProperly(string $expectedAnnotation, array $fieldConfiguration): void { - $metadata = new ClassMetadataInfo($this->_namespace . '\GH6703Options'); - $metadata->namespace = $this->_namespace; + $metadata = new ClassMetadataInfo($this->_namespace . '\GH6703Options'); + $metadata->namespace = $this->_namespace; $metadata->mapField(['fieldName' => 'id', 'type' => 'integer', 'id' => true]); $metadata->mapField(['fieldName' => 'test'] + $fieldConfiguration); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_SEQUENCE); @@ -1244,13 +1236,13 @@ public function testOptionsAreGeneratedProperly(string $expectedAnnotation, arra self::assertFileExists($filename); require_once $filename; - $property = new \ReflectionProperty($metadata->name, 'test'); + $property = new ReflectionProperty($metadata->name, 'test'); $docComment = $property->getDocComment(); self::assertStringContainsString($expectedAnnotation, $docComment); } - public function columnOptionsProvider() : array + public function columnOptionsProvider(): array { return [ 'string-default' => [ @@ -1287,8 +1279,8 @@ public function columnOptionsProvider() : array 'fixed' => true, 'comment' => 'testing', 'collation' => 'utf8mb4_general_ci', - 'check' => 'CHECK (test IN (""test""))' - ] + 'check' => 'CHECK (test IN (""test""))', + ], ], ], 'int-default' => [ @@ -1316,12 +1308,16 @@ public function columnOptionsProvider() : array 'unsigned' => true, 'comment' => 'testing', 'check' => 'CHECK (test > 5)', - ] + ], ], ], ]; } } -class EntityGeneratorAuthor {} -class EntityGeneratorComment {} +class EntityGeneratorAuthor +{ +} +class EntityGeneratorComment +{ +} diff --git a/tests/Doctrine/Tests/ORM/Tools/EntityRepositoryGeneratorTest.php b/tests/Doctrine/Tests/ORM/Tools/EntityRepositoryGeneratorTest.php index 73f2d40e2df..d88592dbd59 100644 --- a/tests/Doctrine/Tests/ORM/Tools/EntityRepositoryGeneratorTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/EntityRepositoryGeneratorTest.php @@ -1,7 +1,10 @@ _namespace = uniqid('doctrine_'); - $this->_tmpDir = \sys_get_temp_dir() . DIRECTORY_SEPARATOR . $this->_namespace; - \mkdir($this->_tmpDir); + $this->_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->setAnnotationPrefix(''); $this->_generator->setGenerateAnnotations(true); $this->_generator->setGenerateStubMethods(true); $this->_generator->setRegenerateEntityIfExists(false); @@ -49,18 +60,15 @@ protected function setUp() : void $this->_repositoryGenerator = new EntityRepositoryGenerator(); } - /** - * @inheritdoc - */ - public function tearDown() : void + public function tearDown(): void { $dirs = []; - $ri = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->_tmpDir)); - foreach ($ri AS $file) { - /* @var $file \SplFileInfo */ + $ri = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->_tmpDir)); + foreach ($ri as $file) { + assert($file instanceof SplFileInfo); if ($file->isFile()) { - \unlink($file->getPathname()); + unlink($file->getPathname()); } elseif ($file->getBasename() === '.') { $dirs[] = $file->getRealPath(); } @@ -69,12 +77,12 @@ public function tearDown() : void arsort($dirs); foreach ($dirs as $dir) { - \rmdir($dir); + rmdir($dir); } } /** @after */ - public function ensureTestGeneratedDeprecationMessages() : void + public function ensureTestGeneratedDeprecationMessages(): void { $this->assertHasDeprecationMessages(); } @@ -82,7 +90,7 @@ public function ensureTestGeneratedDeprecationMessages() : void /** * @group DDC-3231 */ - public function testGeneratedEntityRepositoryClass() + public function testGeneratedEntityRepositoryClass(): void { $em = $this->_getTestEntityManager(); $ns = $this->_namespace; @@ -96,7 +104,7 @@ public function testGeneratedEntityRepositoryClass() require $rpath; - $repo = new \ReflectionClass($em->getRepository($className)); + $repo = new ReflectionClass($em->getRepository($className)); $this->assertTrue($repo->inNamespace()); $this->assertSame($className . 'Repository', $repo->getName()); @@ -105,7 +113,7 @@ public function testGeneratedEntityRepositoryClass() require_once __DIR__ . '/../../Models/DDC3231/DDC3231User1NoNamespace.php'; $className2 = 'DDC3231User1NoNamespaceTmp'; - $this->writeEntityClass(\DDC3231User1NoNamespace::class, $className2); + $this->writeEntityClass(DDC3231User1NoNamespace::class, $className2); $rpath2 = $this->writeRepositoryClass($className2); @@ -113,7 +121,7 @@ public function testGeneratedEntityRepositoryClass() require $rpath2; - $repo2 = new \ReflectionClass($em->getRepository($className2)); + $repo2 = new ReflectionClass($em->getRepository($className2)); $this->assertFalse($repo2->inNamespace()); $this->assertSame($className2 . 'Repository', $repo2->getName()); @@ -123,7 +131,7 @@ public function testGeneratedEntityRepositoryClass() /** * @group DDC-3231 */ - public function testGeneratedEntityRepositoryClassCustomDefaultRepository() + public function testGeneratedEntityRepositoryClassCustomDefaultRepository(): void { $em = $this->_getTestEntityManager(); $ns = $this->_namespace; @@ -138,13 +146,12 @@ public function testGeneratedEntityRepositoryClassCustomDefaultRepository() require $rpath; - $repo = new \ReflectionClass($em->getRepository($className)); + $repo = new ReflectionClass($em->getRepository($className)); $this->assertTrue($repo->inNamespace()); $this->assertSame($className . 'Repository', $repo->getName()); $this->assertSame(DDC3231EntityRepository::class, $repo->getParentClass()->getName()); - require_once __DIR__ . '/../../Models/DDC3231/DDC3231User2NoNamespace.php'; $className2 = 'DDC3231User2NoNamespaceTmp'; @@ -157,40 +164,31 @@ public function testGeneratedEntityRepositoryClassCustomDefaultRepository() require $rpath2; - $repo2 = new \ReflectionClass($em->getRepository($className2)); + $repo2 = new ReflectionClass($em->getRepository($className2)); $this->assertFalse($repo2->inNamespace()); $this->assertSame($className2 . 'Repository', $repo2->getName()); $this->assertSame(DDC3231EntityRepository::class, $repo2->getParentClass()->getName()); } - /** - * @param string $className - * @param string $newClassName - */ - private function writeEntityClass($className, $newClassName) + private function writeEntityClass(string $className, string $newClassName): void { - $cmf = new ClassMetadataFactory(); - $em = $this->_getTestEntityManager(); + $cmf = new ClassMetadataFactory(); + $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); + $metadata->namespace = $this->_namespace; + $metadata->name = $newClassName; + $metadata->customRepositoryClassName = $newClassName . 'Repository'; $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'; } - /** - * @param string $className - * @param string $defaultRepository - * @return string - */ - private function writeRepositoryClass($className, $defaultRepository = null) + private function writeRepositoryClass(string $className, ?string $defaultRepository = null): string { $this->_repositoryGenerator->setDefaultRepositoryName($defaultRepository); @@ -198,5 +196,4 @@ private function writeRepositoryClass($className, $defaultRepository = null) 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 29185ebb5af..43228cdf86d 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Export/AbstractClassMetadataExporterTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Export/AbstractClassMetadataExporterTest.php @@ -1,5 +1,7 @@ - * @author Roman Borschel setProxyDir(__DIR__ . '/../../Proxies'); $config->setProxyNamespace('Doctrine\Tests\Proxies'); $eventManager = new EventManager(); - $conn = new ConnectionMock([], $driverMock, $config, $eventManager); + $conn = new ConnectionMock([], $driverMock, $config, $eventManager); $config->setMetadataDriverImpl($metadataDriver); return EntityManagerMock::create($conn, $config, $eventManager); @@ -64,17 +75,16 @@ protected function _createMetadataDriver($type, $path) $this->assertArrayHasKey($type, $mappingDriver, "There is no metadata driver for the type '" . $type . "'."); - $class = $mappingDriver[$type]; - $driver = ($type === 'annotation') + $class = $mappingDriver[$type]; + + return $type === 'annotation' ? $this->createAnnotationDriver([$path]) : new $class($path); - - return $driver; } protected function _createClassMetadataFactory($em, $type) { - $factory = ($type === 'annotation') + $factory = $type === 'annotation' ? new ClassMetadataFactory() : new DisconnectedClassMetadataFactory(); @@ -83,28 +93,28 @@ protected function _createClassMetadataFactory($em, $type) return $factory; } - public function testExportDirectoryAndFilesAreCreated() + public function testExportDirectoryAndFilesAreCreated(): void { - $this->_deleteDirectory(__DIR__ . '/export/'.$this->_getType()); + $this->_deleteDirectory(__DIR__ . '/export/' . $this->_getType()); - $type = $this->_getType(); + $type = $this->_getType(); $metadataDriver = $this->_createMetadataDriver($type, __DIR__ . '/' . $type); - $em = $this->_createEntityManager($metadataDriver); - $cmf = $this->_createClassMetadataFactory($em, $type); - $metadata = $cmf->getAllMetadata(); + $em = $this->_createEntityManager($metadataDriver); + $cmf = $this->_createClassMetadataFactory($em, $type); + $metadata = $cmf->getAllMetadata(); $metadata[0]->name = ExportedUser::class; $this->assertEquals(ExportedUser::class, $metadata[0]->name); - $type = $this->_getType(); - $cme = new ClassMetadataExporter(); + $type = $this->_getType(); + $cme = new ClassMetadataExporter(); $exporter = $cme->getExporter($type, __DIR__ . '/export/' . $type); if ($type === 'annotation') { $entityGenerator = new EntityGenerator(); - $entityGenerator->setAnnotationPrefix(""); + $entityGenerator->setAnnotationPrefix(''); $exporter->setEntityGenerator($entityGenerator); } @@ -113,10 +123,10 @@ public function testExportDirectoryAndFilesAreCreated() $exporter->setMetadata($metadata); $exporter->export(); - if ($type == 'annotation') { - $this->assertTrue(file_exists(__DIR__ . '/export/' . $type . '/'.str_replace('\\', '/', ExportedUser::class).$this->_extension)); + if ($type === 'annotation') { + $this->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)); + $this->assertTrue(file_exists(__DIR__ . '/export/' . $type . '/Doctrine.Tests.ORM.Tools.Export.ExportedUser' . $this->_extension)); } $this->assertHasDeprecationMessages(); @@ -130,9 +140,9 @@ public function testExportedMetadataCanBeReadBackIn() $type = $this->_getType(); $metadataDriver = $this->_createMetadataDriver($type, __DIR__ . '/export/' . $type); - $em = $this->_createEntityManager($metadataDriver); - $cmf = $this->_createClassMetadataFactory($em, $type); - $metadata = $cmf->getAllMetadata(); + $em = $this->_createEntityManager($metadataDriver); + $cmf = $this->_createClassMetadataFactory($em, $type); + $metadata = $cmf->getAllMetadata(); $this->assertEquals(1, count($metadata)); @@ -145,23 +155,22 @@ public function testExportedMetadataCanBeReadBackIn() /** * @depends testExportedMetadataCanBeReadBackIn - * @param ClassMetadataInfo $class */ - public function testTableIsExported($class) + public function testTableIsExported(ClassMetadataInfo $class) { $this->assertEquals('cms_users', $class->table['name']); $this->assertEquals( ['engine' => 'MyISAM', 'foo' => ['bar' => 'baz']], - $class->table['options']); + $class->table['options'] + ); return $class; } /** * @depends testTableIsExported - * @param ClassMetadataInfo $class */ - public function testTypeIsExported($class) + public function testTypeIsExported(ClassMetadataInfo $class) { $this->assertFalse($class->isMappedSuperclass); @@ -170,11 +179,10 @@ public function testTypeIsExported($class) /** * @depends testTypeIsExported - * @param ClassMetadataInfo $class */ - public function testIdentifierIsExported($class) + public function testIdentifierIsExported(ClassMetadataInfo $class) { - $this->assertEquals(ClassMetadataInfo::GENERATOR_TYPE_IDENTITY, $class->generatorType, "Generator Type wrong"); + $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); @@ -183,9 +191,8 @@ public function testIdentifierIsExported($class) /** * @depends testIdentifierIsExported - * @param ClassMetadataInfo $class */ - public function testFieldsAreExported($class) + public function testFieldsAreExported(ClassMetadataInfo $class) { $this->assertTrue(isset($class->fieldMappings['id']['id']) && $class->fieldMappings['id']['id'] === true); $this->assertEquals('id', $class->fieldMappings['id']['fieldName']); @@ -210,29 +217,28 @@ public function testFieldsAreExported($class) /** * @depends testExportDirectoryAndFilesAreCreated */ - public function testFieldsAreProperlySerialized() + public function testFieldsAreProperlySerialized(): void { $type = $this->_getType(); - if ($type == 'xml') { - $xml = simplexml_load_file(__DIR__ . '/export/'.$type.'/Doctrine.Tests.ORM.Tools.Export.ExportedUser.dcm.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"); + $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)); $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'); + $this->markTestSkipped('Test not available for ' . $type . ' driver'); } } /** * @depends testFieldsAreExported - * @param ClassMetadataInfo $class */ - public function testOneToOneAssociationsAreExported($class) + public function testOneToOneAssociationsAreExported(ClassMetadataInfo $class) { $this->assertTrue(isset($class->associationMappings['address'])); $this->assertEquals(Address::class, $class->associationMappings['address']['targetEntity']); @@ -254,7 +260,7 @@ public function testOneToOneAssociationsAreExported($class) /** * @depends testFieldsAreExported */ - public function testManyToOneAssociationsAreExported($class) + public function testManyToOneAssociationsAreExported($class): void { $this->assertTrue(isset($class->associationMappings['mainGroup'])); $this->assertEquals(Group::class, $class->associationMappings['mainGroup']['targetEntity']); @@ -262,9 +268,8 @@ public function testManyToOneAssociationsAreExported($class) /** * @depends testOneToOneAssociationsAreExported - * @param ClassMetadataInfo $class */ - public function testOneToManyAssociationsAreExported($class) + public function testOneToManyAssociationsAreExported(ClassMetadataInfo $class) { $this->assertTrue(isset($class->associationMappings['phonenumbers'])); $this->assertEquals(Phonenumber::class, $class->associationMappings['phonenumbers']['targetEntity']); @@ -283,8 +288,9 @@ public function testOneToManyAssociationsAreExported($class) } /** - * @depends testOneToManyAssociationsAreExported * @param ClassMetadataInfo $metadata + * + * @depends testOneToManyAssociationsAreExported */ public function testManyToManyAssociationsAreExported($class) { @@ -311,9 +317,8 @@ public function testManyToManyAssociationsAreExported($class) /** * @depends testManyToManyAssociationsAreExported - * @param ClassMetadataInfo $class */ - public function testLifecycleCallbacksAreExported($class) + public function testLifecycleCallbacksAreExported(ClassMetadataInfo $class) { $this->assertTrue(isset($class->lifecycleCallbacks['prePersist'])); $this->assertEquals(2, count($class->lifecycleCallbacks['prePersist'])); @@ -329,9 +334,8 @@ public function testLifecycleCallbacksAreExported($class) /** * @depends testLifecycleCallbacksAreExported - * @param ClassMetadataInfo $class */ - public function testCascadeIsExported($class) + public function testCascadeIsExported(ClassMetadataInfo $class) { $this->assertTrue($class->associationMappings['phonenumbers']['isCascadePersist']); $this->assertTrue($class->associationMappings['phonenumbers']['isCascadeMerge']); @@ -345,45 +349,43 @@ public function testCascadeIsExported($class) /** * @depends testCascadeIsExported - * @param ClassMetadataInfo $class */ - public function testInversedByIsExported($class) + public function testInversedByIsExported(ClassMetadataInfo $class): void { $this->assertEquals('user', $class->associationMappings['address']['inversedBy']); } + /** * @depends testExportDirectoryAndFilesAreCreated */ - public function testCascadeAllCollapsed() + public function testCascadeAllCollapsed(): void { $type = $this->_getType(); - if ($type == 'xml') { - $xml = simplexml_load_file(__DIR__ . '/export/'.$type.'/Doctrine.Tests.ORM.Tools.Export.ExportedUser.dcm.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"); + $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')); + } elseif ($type === 'yaml') { + $yaml = new Parser(); + $value = $yaml->parse(file_get_contents(__DIR__ . '/export/' . $type . '/Doctrine.Tests.ORM.Tools.Export.ExportedUser.dcm.yml')); $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]); } else { - $this->markTestSkipped('Test not available for '.$type.' driver'); + $this->markTestSkipped('Test not available for ' . $type . ' driver'); } } /** * @depends testExportedMetadataCanBeReadBackIn - * - * @param ClassMetadata $class */ - public function testEntityListenersAreExported($class) + public function testEntityListenersAreExported(ClassMetadata $class): void { $this->assertNotEmpty($class->entityListeners); $this->assertCount(2, $class->entityListeners[Events::prePersist]); @@ -400,18 +402,18 @@ public function testEntityListenersAreExported($class) public function __destruct() { -# $this->_deleteDirectory(__DIR__ . '/export/'.$this->_getType()); +// $this->_deleteDirectory(__DIR__ . '/export/'.$this->_getType()); } protected function _deleteDirectory($path) { if (is_file($path)) { return unlink($path); - } else if (is_dir($path)) { - $files = glob(rtrim($path,'/').'/*'); + } elseif (is_dir($path)) { + $files = glob(rtrim($path, '/') . '/*'); if (is_array($files)) { - foreach ($files as $file){ + foreach ($files as $file) { $this->_deleteDirectory($file); } } @@ -423,38 +425,44 @@ protected function _deleteDirectory($path) class Address { - } class Phonenumber { - } class Group { - } class UserListener { /** * @\Doctrine\ORM\Mapping\PrePersist */ - public function customPrePersist(): void {} + public function customPrePersist(): void + { + } + /** * @\Doctrine\ORM\Mapping\PostPersist */ - public function customPostPersist(): void {} + public function customPostPersist(): void + { + } } class GroupListener { /** * @\Doctrine\ORM\Mapping\PrePersist */ - public function prePersist(): void {} + public function prePersist(): void + { + } } class AddressListener { /** * @\Doctrine\ORM\Mapping\PostPersist */ - public function customPostPersist(): void {} + public function customPostPersist(): void + { + } } diff --git a/tests/Doctrine/Tests/ORM/Tools/Export/AnnotationClassMetadataExporterTest.php b/tests/Doctrine/Tests/ORM/Tools/Export/AnnotationClassMetadataExporterTest.php index a432ec45187..dde1ace412a 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Export/AnnotationClassMetadataExporterTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Export/AnnotationClassMetadataExporterTest.php @@ -1,16 +1,13 @@ - * @author Roman Borschel - * @author Roman Borschel - * @author Roman Borschel mapField( [ - "fieldName" => 'id', - "type" => 'integer', - "columnName" => 'id', - "id" => true, + 'fieldName' => 'id', + 'type' => 'integer', + 'columnName' => 'id', + 'id' => true, ] ); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_SEQUENCE); $metadata->setSequenceGeneratorDefinition( [ - 'sequenceName' => 'seq_entity_test_id', - 'allocationSize' => 5, - 'initialValue' => 1 + 'sequenceName' => 'seq_entity_test_id', + 'allocationSize' => 5, + 'initialValue' => 1, ] ); @@ -71,19 +70,20 @@ public function testSequenceGenerator() { * @group 1216 * @group DDC-3439 */ - public function testFieldOptionsExport() { + public function testFieldOptionsExport(): void + { $exporter = new XmlExporter(); $metadata = new ClassMetadata('entityTest'); $metadata->mapField( [ - "fieldName" => 'myField', - "type" => 'string', - "columnName" => 'my_field', - "options" => [ - "default" => "default_string", - "comment" => "The comment for the field", - ], + 'fieldName' => 'myField', + 'type' => 'string', + 'columnName' => 'my_field', + 'options' => [ + 'default' => 'default_string', + 'comment' => 'The comment for the field', + ], ] ); diff --git a/tests/Doctrine/Tests/ORM/Tools/Export/YamlClassMetadataExporterTest.php b/tests/Doctrine/Tests/ORM/Tools/Export/YamlClassMetadataExporterTest.php index a47c396d2ce..3eb8b8ddaa1 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Export/YamlClassMetadataExporterTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Export/YamlClassMetadataExporterTest.php @@ -1,22 +1,21 @@ - * @author Roman Borschel markTestSkipped('Please install Symfony YAML Component into the include path of your PHP installation.'); } 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 c6a066258f4..0588417d01f 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,5 +1,7 @@ setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_NONE); $metadata->setPrimaryTable( [ - 'name' => 'cms_users', - 'options' => ['engine' => 'MyISAM', 'foo' => ['bar' => 'baz']], + 'name' => 'cms_users', + 'options' => ['engine' => 'MyISAM', 'foo' => ['bar' => 'baz']], ] ); $metadata->setChangeTrackingPolicy(ClassMetadataInfo::CHANGETRACKING_DEFERRED_IMPLICIT); @@ -20,137 +22,131 @@ $metadata->addLifecycleCallback('doStuffOnPostPersist', Events::postPersist); $metadata->mapField( [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - 'columnName' => 'id', + 'id' => true, + 'fieldName' => 'id', + 'type' => 'integer', + 'columnName' => 'id', ] ); $metadata->mapField( [ - 'fieldName' => 'name', - 'type' => 'string', - 'length' => 50, - 'unique' => true, - 'nullable' => true, - 'columnName' => 'name', + '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', + 'fieldName' => 'email', + 'type' => 'string', + 'columnName' => 'user_email', + 'columnDefinition' => 'CHAR(32) NOT NULL', ] ); $metadata->mapField( [ - 'fieldName' => 'age', - 'type' => 'integer', - 'options' => ["unsigned"=>true], + 'fieldName' => 'age', + 'type' => 'integer', + 'options' => ['unsigned' => true], ] ); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); $metadata->mapManyToOne( [ - 'fieldName' => 'mainGroup', - 'targetEntity' => Export\Group::class, + '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, + '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, + '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', - ], + '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, + '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, ] ); $metadata->addEntityListener(Events::prePersist, UserListener::class, 'customPrePersist'); diff --git a/tests/Doctrine/Tests/ORM/Tools/Pagination/CountOutputWalkerTest.php b/tests/Doctrine/Tests/ORM/Tools/Pagination/CountOutputWalkerTest.php index df7f73f7881..db9d2f751e5 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'); + '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() + '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() + public function testCountQuery_MixedResultsWithName(): void { $query = $this->entityManager->createQuery( - 'SELECT a, sum(a.name) as foo FROM Doctrine\Tests\ORM\Tools\Pagination\Author a'); + '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() + '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() ); } public function testCountQuery_GroupBy(): void { $query = $this->entityManager->createQuery( - 'SELECT p.name FROM Doctrine\Tests\ORM\Tools\Pagination\Person p GROUP BY p.name'); + '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() + 'SELECT COUNT(*) AS dctrn_count FROM (SELECT p0_.name AS name_0 FROM Person p0_ GROUP BY p0_.name) dctrn_table', + $query->getSQL() ); } public function testCountQuery_Having(): void { $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'); + '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() + '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() ); } - public function testCountQueryOrderBySqlServer() + public function testCountQueryOrderBySqlServer(): void { - if ($this->entityManager->getConnection()->getDatabasePlatform()->getName() !== "mssql") { + if ($this->entityManager->getConnection()->getDatabasePlatform()->getName() !== 'mssql') { $this->markTestSkipped('SQLServer only test.'); } $query = $this->entityManager->createQuery( - 'SELECT p FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost p ORDER BY p.id'); + '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", + '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() ); } } - diff --git a/tests/Doctrine/Tests/ORM/Tools/Pagination/CountWalkerTest.php b/tests/Doctrine/Tests/ORM/Tools/Pagination/CountWalkerTest.php index 2aa398d6fbe..fa2988a366d 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Pagination/CountWalkerTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Pagination/CountWalkerTest.php @@ -1,89 +1,102 @@ entityManager->createQuery( - 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost p JOIN p.category c JOIN p.author a'); + '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() + '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() + public function testCountQuery_MixedResultsWithName(): void { $query = $this->entityManager->createQuery( - 'SELECT a, sum(a.name) as foo FROM Doctrine\Tests\ORM\Tools\Pagination\Author a'); + '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() + 'SELECT count(DISTINCT a0_.id) AS sclr_0 FROM Author a0_', + $query->getSQL() ); } - public function testCountQuery_KeepsGroupBy() + public function testCountQuery_KeepsGroupBy(): void { $query = $this->entityManager->createQuery( - 'SELECT b FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost b GROUP BY b.id'); + '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() + 'SELECT count(DISTINCT b0_.id) AS sclr_0 FROM BlogPost b0_ GROUP BY b0_.id', + $query->getSQL() ); } - public function testCountQuery_RemovesOrderBy() + public function testCountQuery_RemovesOrderBy(): void { $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'); + '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() + '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() + public function testCountQuery_RemovesLimits(): void { $query = $this->entityManager->createQuery( - 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost p JOIN p.category c JOIN p.author a'); + '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() + '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_HavingException() + public function testCountQuery_HavingException(): void { $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->expectException(RuntimeException::class); $this->expectExceptionMessage('Cannot count query that uses a HAVING clause. Use the output walkers for pagination'); $query->getSQL(); @@ -92,17 +105,18 @@ public function testCountQuery_HavingException() /** * Arbitrary Join */ - public function testCountQueryWithArbitraryJoin() + public function testCountQueryWithArbitraryJoin(): void { $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'); + '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() + 'SELECT count(DISTINCT b0_.id) AS sclr_0 FROM BlogPost b0_ LEFT JOIN Category c1_ ON (b0_.category_id = c1_.id)', + $query->getSQL() ); } } - diff --git a/tests/Doctrine/Tests/ORM/Tools/Pagination/LimitSubqueryOutputWalkerTest.php b/tests/Doctrine/Tests/ORM/Tools/Pagination/LimitSubqueryOutputWalkerTest.php index 39ee1360dc9..31e906dde78 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Pagination/LimitSubqueryOutputWalkerTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Pagination/LimitSubqueryOutputWalkerTest.php @@ -1,5 +1,7 @@ entityManager->createQuery( - 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\MyBlogPost p JOIN p.category c JOIN p.author a'); + 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\MyBlogPost p JOIN p.category c JOIN p.author a' + ); $query->expireQueryCache(true); $limitQuery = clone $query; $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 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() ); } - public function testLimitSubqueryWithSortPg() : void + public function testLimitSubqueryWithSortPg(): void { $odp = $this->entityManager->getConnection()->getDatabasePlatform(); - $this->entityManager->getConnection()->setDatabasePlatform(new PostgreSqlPlatform); + $this->entityManager->getConnection()->setDatabasePlatform(new PostgreSqlPlatform()); - $query = $this->entityManager->createQuery( - 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\MyBlogPost p JOIN p.category c JOIN p.author a ORDER BY p.title'); + $query = $this->entityManager->createQuery( + 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\MyBlogPost p JOIN p.category c JOIN p.author a ORDER BY p.title' + ); $limitQuery = clone $query; $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 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() ); $this->entityManager->getConnection()->setDatabasePlatform($odp); } - public function testLimitSubqueryWithScalarSortPg() : void + public function testLimitSubqueryWithScalarSortPg(): void { $odp = $this->entityManager->getConnection()->getDatabasePlatform(); - $this->entityManager->getConnection()->setDatabasePlatform(new PostgreSqlPlatform); + $this->entityManager->getConnection()->setDatabasePlatform(new PostgreSqlPlatform()); - $query = $this->entityManager->createQuery( + $query = $this->entityManager->createQuery( 'SELECT u, g, COUNT(g.id) AS g_quantity FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.groups g ORDER BY g_quantity' ); $limitQuery = clone $query; $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 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', $limitQuery->getSQL() ); $this->entityManager->getConnection()->setDatabasePlatform($odp); } - public function testLimitSubqueryWithMixedSortPg() : void + public function testLimitSubqueryWithMixedSortPg(): void { $odp = $this->entityManager->getConnection()->getDatabasePlatform(); - $this->entityManager->getConnection()->setDatabasePlatform(new PostgreSqlPlatform); + $this->entityManager->getConnection()->setDatabasePlatform(new PostgreSqlPlatform()); - $query = $this->entityManager->createQuery( + $query = $this->entityManager->createQuery( 'SELECT u, g, COUNT(g.id) AS g_quantity FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.groups g ORDER BY g_quantity, u.id DESC' ); $limitQuery = clone $query; $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 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', $limitQuery->getSQL() ); $this->entityManager->getConnection()->setDatabasePlatform($odp); } - public function testLimitSubqueryWithHiddenScalarSortPg() : void + public function testLimitSubqueryWithHiddenScalarSortPg(): void { $odp = $this->entityManager->getConnection()->getDatabasePlatform(); - $this->entityManager->getConnection()->setDatabasePlatform(new PostgreSqlPlatform); + $this->entityManager->getConnection()->setDatabasePlatform(new PostgreSqlPlatform()); - $query = $this->entityManager->createQuery( - 'SELECT u, g, COUNT(g.id) AS hidden g_quantity FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.groups g ORDER BY g_quantity, u.id DESC' + $query = $this->entityManager->createQuery( + 'SELECT u, g, COUNT(g.id) AS hidden g_quantity FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.groups g ORDER BY g_quantity, u.id DESC' ); $limitQuery = clone $query; $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 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', $limitQuery->getSQL() ); $this->entityManager->getConnection()->setDatabasePlatform($odp); } - public function testLimitSubqueryPg() : void + public function testLimitSubqueryPg(): void { $odp = $this->entityManager->getConnection()->getDatabasePlatform(); - $this->entityManager->getConnection()->setDatabasePlatform(new PostgreSqlPlatform); + $this->entityManager->getConnection()->setDatabasePlatform(new PostgreSqlPlatform()); $this->testLimitSubquery(); $this->entityManager->getConnection()->setDatabasePlatform($odp); } - public function testLimitSubqueryWithSortOracle() : void + public function testLimitSubqueryWithSortOracle(): void { $odp = $this->entityManager->getConnection()->getDatabasePlatform(); - $this->entityManager->getConnection()->setDatabasePlatform(new OraclePlatform); + $this->entityManager->getConnection()->setDatabasePlatform(new OraclePlatform()); $query = $this->entityManager->createQuery( - 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\MyBlogPost p JOIN p.category c JOIN p.author a ORDER BY p.title'); + 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\MyBlogPost p JOIN p.category c JOIN p.author a ORDER BY p.title' + ); $query->expireQueryCache(true); $limitQuery = clone $query; $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 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() ); $this->entityManager->getConnection()->setDatabasePlatform($odp); } - public function testLimitSubqueryWithScalarSortOracle() : void + public function testLimitSubqueryWithScalarSortOracle(): void { $odp = $this->entityManager->getConnection()->getDatabasePlatform(); - $this->entityManager->getConnection()->setDatabasePlatform(new OraclePlatform); + $this->entityManager->getConnection()->setDatabasePlatform(new OraclePlatform()); $query = $this->entityManager->createQuery( 'SELECT u, g, COUNT(g.id) AS g_quantity FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.groups g ORDER BY g_quantity' @@ -138,17 +146,17 @@ 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 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', $limitQuery->getSQL() ); $this->entityManager->getConnection()->setDatabasePlatform($odp); } - public function testLimitSubqueryWithMixedSortOracle() : void + public function testLimitSubqueryWithMixedSortOracle(): void { $odp = $this->entityManager->getConnection()->getDatabasePlatform(); - $this->entityManager->getConnection()->setDatabasePlatform(new OraclePlatform); + $this->entityManager->getConnection()->setDatabasePlatform(new OraclePlatform()); $query = $this->entityManager->createQuery( 'SELECT u, g, COUNT(g.id) AS g_quantity FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.groups g ORDER BY g_quantity, u.id DESC' @@ -158,47 +166,51 @@ 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 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', $limitQuery->getSQL() ); $this->entityManager->getConnection()->setDatabasePlatform($odp); } - public function testLimitSubqueryOracle() : void + public function testLimitSubqueryOracle(): void { $odp = $this->entityManager->getConnection()->getDatabasePlatform(); - $this->entityManager->getConnection()->setDatabasePlatform(new OraclePlatform); + $this->entityManager->getConnection()->setDatabasePlatform(new OraclePlatform()); $query = $this->entityManager->createQuery( - 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\MyBlogPost p JOIN p.category c JOIN p.author a'); + 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\MyBlogPost p JOIN p.category c JOIN p.author a' + ); $query->expireQueryCache(true); $limitQuery = clone $query; $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 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() ); $this->entityManager->getConnection()->setDatabasePlatform($odp); } - public function testCountQueryMixedResultsWithName() : void + public function testCountQueryMixedResultsWithName(): void { - $query = $this->entityManager->createQuery( - 'SELECT a, sum(a.name) as foo FROM Doctrine\Tests\ORM\Tools\Pagination\Author a'); + $query = $this->entityManager->createQuery( + 'SELECT a, sum(a.name) as foo FROM Doctrine\Tests\ORM\Tools\Pagination\Author a' + ); $limitQuery = clone $query; $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 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() ); } /** * @group DDC-3336 */ - public function testCountQueryWithArithmeticOrderByCondition() : void + public function testCountQueryWithArithmeticOrderByCondition(): void { $query = $this->entityManager->createQuery( 'SELECT a FROM Doctrine\Tests\ORM\Tools\Pagination\Author a ORDER BY (1 - 1000) * 1 DESC' @@ -213,7 +225,7 @@ public function testCountQueryWithArithmeticOrderByCondition() : void ); } - public function testCountQueryWithComplexScalarOrderByItem() : void + public function testCountQueryWithComplexScalarOrderByItem(): void { $query = $this->entityManager->createQuery( 'SELECT a FROM Doctrine\Tests\ORM\Tools\Pagination\Avatar a ORDER BY a.image_height * a.image_width DESC' @@ -228,7 +240,7 @@ public function testCountQueryWithComplexScalarOrderByItem() : void ); } - public function testCountQueryWithComplexScalarOrderByItemJoined() : void + public function testCountQueryWithComplexScalarOrderByItemJoined(): void { $query = $this->entityManager->createQuery( 'SELECT u FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.avatar a ORDER BY a.image_height * a.image_width DESC' @@ -243,7 +255,7 @@ public function testCountQueryWithComplexScalarOrderByItemJoined() : void ); } - public function testCountQueryWithComplexScalarOrderByItemJoinedWithPartial() : void + public function testCountQueryWithComplexScalarOrderByItemJoinedWithPartial(): void { $query = $this->entityManager->createQuery( 'SELECT u, partial a.{id, image_alt_desc} FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.avatar a ORDER BY a.image_height * a.image_width DESC' @@ -258,7 +270,7 @@ public function testCountQueryWithComplexScalarOrderByItemJoinedWithPartial() : ); } - public function testCountQueryWithComplexScalarOrderByItemOracle() : void + public function testCountQueryWithComplexScalarOrderByItemOracle(): void { $query = $this->entityManager->createQuery( 'SELECT a FROM Doctrine\Tests\ORM\Tools\Pagination\Avatar a ORDER BY a.image_height * a.image_width DESC' @@ -276,7 +288,7 @@ public function testCountQueryWithComplexScalarOrderByItemOracle() : void /** * @group DDC-3434 */ - public function testLimitSubqueryWithHiddenSelectionInOrderBy() : void + public function testLimitSubqueryWithHiddenSelectionInOrderBy(): void { $query = $this->entityManager->createQuery( 'SELECT a, a.name AS HIDDEN ord FROM Doctrine\Tests\ORM\Tools\Pagination\Author a ORDER BY ord DESC' @@ -290,7 +302,7 @@ public function testLimitSubqueryWithHiddenSelectionInOrderBy() : void ); } - public function testLimitSubqueryWithColumnWithSortDirectionInName() : void + public function testLimitSubqueryWithColumnWithSortDirectionInName(): void { $query = $this->entityManager->createQuery( 'SELECT a FROM Doctrine\Tests\ORM\Tools\Pagination\Avatar a ORDER BY a.image_alt_desc DESC' @@ -305,7 +317,7 @@ public function testLimitSubqueryWithColumnWithSortDirectionInName() : void ); } - public function testLimitSubqueryWithOrderByInnerJoined() : void + public function testLimitSubqueryWithOrderByInnerJoined(): void { $query = $this->entityManager->createQuery( 'SELECT b FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost b JOIN b.author a ORDER BY a.name ASC' @@ -319,7 +331,7 @@ public function testLimitSubqueryWithOrderByInnerJoined() : void ); } - public function testLimitSubqueryWithOrderByAndSubSelectInWhereClauseMySql() : void + public function testLimitSubqueryWithOrderByAndSubSelectInWhereClauseMySql(): void { $this->entityManager->getConnection()->setDatabasePlatform(new MySqlPlatform()); $query = $this->entityManager->createQuery( @@ -335,7 +347,7 @@ public function testLimitSubqueryWithOrderByAndSubSelectInWhereClauseMySql() : v ); } - public function testLimitSubqueryWithOrderByAndSubSelectInWhereClausePgSql() : void + public function testLimitSubqueryWithOrderByAndSubSelectInWhereClausePgSql(): void { $this->entityManager->getConnection()->setDatabasePlatform(new PostgreSqlPlatform()); $query = $this->entityManager->createQuery( @@ -354,7 +366,7 @@ public function testLimitSubqueryWithOrderByAndSubSelectInWhereClausePgSql() : v /** * This tests ordering by property that has the 'declared' field. */ - public function testLimitSubqueryOrderByFieldFromMappedSuperclass() : void + public function testLimitSubqueryOrderByFieldFromMappedSuperclass(): void { $this->entityManager->getConnection()->setDatabasePlatform(new MySqlPlatform()); @@ -373,7 +385,7 @@ public function testLimitSubqueryOrderByFieldFromMappedSuperclass() : void /** * Tests order by on a subselect expression (mysql). */ - public function testLimitSubqueryOrderBySubSelectOrderByExpression() : void + public function testLimitSubqueryOrderBySubSelectOrderByExpression(): void { $this->entityManager->getConnection()->setDatabasePlatform(new MySqlPlatform()); @@ -398,7 +410,7 @@ public function testLimitSubqueryOrderBySubSelectOrderByExpression() : void /** * Tests order by on a subselect expression invoking RowNumberOverFunction (postgres). */ - public function testLimitSubqueryOrderBySubSelectOrderByExpressionPg() : void + public function testLimitSubqueryOrderBySubSelectOrderByExpressionPg(): void { $this->entityManager->getConnection()->setDatabasePlatform(new PostgreSqlPlatform()); @@ -423,7 +435,7 @@ public function testLimitSubqueryOrderBySubSelectOrderByExpressionPg() : void /** * Tests order by on a subselect expression invoking RowNumberOverFunction (oracle). */ - public function testLimitSubqueryOrderBySubSelectOrderByExpressionOracle() : void + public function testLimitSubqueryOrderBySubSelectOrderByExpressionOracle(): void { $this->entityManager->getConnection()->setDatabasePlatform(new OraclePlatform()); @@ -445,4 +457,3 @@ public function testLimitSubqueryOrderBySubSelectOrderByExpressionOracle() : voi ); } } - diff --git a/tests/Doctrine/Tests/ORM/Tools/Pagination/LimitSubqueryWalkerTest.php b/tests/Doctrine/Tests/ORM/Tools/Pagination/LimitSubqueryWalkerTest.php index 32ad2a354ec..e18432cc988 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Pagination/LimitSubqueryWalkerTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Pagination/LimitSubqueryWalkerTest.php @@ -1,5 +1,7 @@ entityManager->createQuery($dql); @@ -19,12 +21,12 @@ public function testLimitSubquery() $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 INNER JOIN Author a2_ ON m0_.author_id = a2_.id", + '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', $limitQuery->getSQL() ); } - public function testLimitSubqueryWithSort() + public function testLimitSubqueryWithSort(): void { $dql = 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\MyBlogPost p JOIN p.category c JOIN p.author a ORDER BY p.title'; $query = $this->entityManager->createQuery($dql); @@ -33,12 +35,12 @@ 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", + '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', $limitQuery->getSQL() ); } - public function testLimitSubqueryWithSortFunction() : void + public function testLimitSubqueryWithSortFunction(): void { $dql = 'SELECT p FROM Doctrine\Tests\ORM\Tools\Pagination\MyBlogPost p JOIN p.category c GROUP BY p.id ORDER BY COUNT(c.id)'; $query = $this->entityManager->createQuery($dql); @@ -52,7 +54,7 @@ public function testLimitSubqueryWithSortFunction() : void ); } - public function testCountQuery_MixedResultsWithName() + public function testCountQuery_MixedResultsWithName(): void { $dql = 'SELECT a, sum(a.name) as foo FROM Doctrine\Tests\ORM\Tools\Pagination\Author a'; $query = $this->entityManager->createQuery($dql); @@ -61,12 +63,12 @@ public function testCountQuery_MixedResultsWithName() $limitQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [LimitSubqueryWalker::class]); $this->assertEquals( - "SELECT DISTINCT a0_.id AS id_0 FROM Author a0_", + 'SELECT DISTINCT a0_.id AS id_0 FROM Author a0_', $limitQuery->getSQL() ); } - public function testAggQuery_MixedResultsWithNameAndSort() : void + public function testAggQuery_MixedResultsWithNameAndSort(): void { $dql = 'SELECT a, sum(a.name) as foo FROM Doctrine\Tests\ORM\Tools\Pagination\Author a ORDER BY foo DESC'; $query = $this->entityManager->createQuery($dql); @@ -80,7 +82,7 @@ public function testAggQuery_MixedResultsWithNameAndSort() : void ); } - public function testAggQuery_MultipleMixedResultsWithSort() : void + public function testAggQuery_MultipleMixedResultsWithSort(): void { $dql = 'SELECT a, sum(a.name) as foo, (SELECT count(subA.id) FROM Doctrine\Tests\ORM\Tools\Pagination\Author subA WHERE subA.id = a.id ) as bar FROM Doctrine\Tests\ORM\Tools\Pagination\Author a ORDER BY foo DESC, bar ASC'; $query = $this->entityManager->createQuery($dql); @@ -97,7 +99,7 @@ public function testAggQuery_MultipleMixedResultsWithSort() : void /** * @group DDC-2890 */ - public function testLimitSubqueryWithSortOnAssociation() + public function testLimitSubqueryWithSortOnAssociation(): void { $dql = 'SELECT p FROM Doctrine\Tests\ORM\Tools\Pagination\MyBlogPost p ORDER BY p.author'; $query = $this->entityManager->createQuery($dql); @@ -106,7 +108,7 @@ 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", + 'SELECT DISTINCT m0_.id AS id_0, m0_.author_id AS sclr_1 FROM MyBlogPost m0_ ORDER BY m0_.author_id ASC', $limitQuery->getSQL() ); } @@ -114,7 +116,7 @@ public function testLimitSubqueryWithSortOnAssociation() /** * Arbitrary Join */ - public function testLimitSubqueryWithArbitraryJoin() + public function testLimitSubqueryWithArbitraryJoin(): void { $dql = 'SELECT p, c FROM Doctrine\Tests\ORM\Tools\Pagination\MyBlogPost p JOIN Doctrine\Tests\ORM\Tools\Pagination\Category c WITH p.category = c'; $query = $this->entityManager->createQuery($dql); @@ -123,12 +125,12 @@ 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)", + 'SELECT DISTINCT m0_.id AS id_0 FROM MyBlogPost m0_ INNER JOIN Category c1_ ON (m0_.category_id = c1_.id)', $limitQuery->getSQL() ); } - public function testLimitSubqueryWithSortWithArbitraryJoin() + public function testLimitSubqueryWithSortWithArbitraryJoin(): void { $dql = 'SELECT p, c FROM Doctrine\Tests\ORM\Tools\Pagination\MyBlogPost p JOIN Doctrine\Tests\ORM\Tools\Pagination\Category c WITH p.category = c ORDER BY p.title'; $query = $this->entityManager->createQuery($dql); @@ -137,9 +139,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", + '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', $limitQuery->getSQL() ); } } - diff --git a/tests/Doctrine/Tests/ORM/Tools/Pagination/PaginationTestCase.php b/tests/Doctrine/Tests/ORM/Tools/Pagination/PaginationTestCase.php index 3cddf5c7a90..2020d285e29 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Pagination/PaginationTestCase.php +++ b/tests/Doctrine/Tests/ORM/Tools/Pagination/PaginationTestCase.php @@ -1,17 +1,18 @@ entityManager = $this->_getTestEntityManager(); } @@ -19,20 +20,15 @@ protected function setUp() : void /** -* @Entity -*/ + * @Entity + */ class MyBlogPost { - /** @Id @Column(type="integer") @GeneratedValue */ public $id; - /** - * @ManyToOne(targetEntity="Author") - */ + /** @ManyToOne(targetEntity="Author") */ public $author; - /** - * @ManyToOne(targetEntity="Category") - */ + /** @ManyToOne(targetEntity="Category") */ public $category; /** @Column(type="string") */ public $title; @@ -43,21 +39,17 @@ class MyBlogPost */ class MyAuthor { - /** @Id @Column(type="integer") @GeneratedValue */ public $id; - } /** -* @Entity -*/ + * @Entity + */ class MyCategory { - /** @Id @Column(type="integer") @GeneratedValue */ public $id; - } @@ -66,16 +58,11 @@ class MyCategory */ class BlogPost { - /** @Id @Column(type="integer") @GeneratedValue */ public $id; - /** - * @ManyToOne(targetEntity="Author") - */ + /** @ManyToOne(targetEntity="Author") */ public $author; - /** - * @ManyToOne(targetEntity="Category") - */ + /** @ManyToOne(targetEntity="Category") */ public $category; } @@ -84,12 +71,10 @@ class BlogPost */ class Author { - /** @Id @Column(type="integer") @GeneratedValue */ public $id; /** @Column(type="string") */ public $name; - } /** @@ -97,14 +82,12 @@ class Author */ class Person { - /** @Id @Column(type="integer") @GeneratedValue */ public $id; /** @Column(type="string") */ public $name; /** @Column(type="string") */ public $biography; - } /** @@ -112,17 +95,14 @@ class Person */ class Category { - /** @Id @Column(type="integer") @GeneratedValue */ public $id; - } /** @Entity @Table(name="groups") */ class Group { - /** @Id @Column(type="integer") @GeneratedValue */ public $id; /** @ManyToMany(targetEntity="User", mappedBy="groups") */ @@ -132,7 +112,6 @@ class Group /** @Entity */ class User { - /** @Id @Column(type="integer") @GeneratedValue */ public $id; /** @@ -144,9 +123,7 @@ class User * ) */ public $groups; - /** - * @OneToOne(targetEntity="Avatar", mappedBy="user") - */ + /** @OneToOne(targetEntity="Avatar", mappedBy="user") */ public $avatar; } diff --git a/tests/Doctrine/Tests/ORM/Tools/Pagination/PaginatorTest.php b/tests/Doctrine/Tests/ORM/Tools/Pagination/PaginatorTest.php index 20b2abdda17..4b3df4310e4 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Pagination/PaginatorTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Pagination/PaginatorTest.php @@ -23,25 +23,23 @@ class PaginatorTest extends OrmTestCase /** @var AbstractHydrator */ private $hydrator; - protected function setUp() : void + protected function setUp(): void { $this->connection = $this->getMockBuilder(ConnectionMock::class) ->setConstructorArgs([[], new DriverMock()]) ->setMethods(['executeQuery']) - ->getMock() - ; + ->getMock(); $this->em = $this->getMockBuilder(EntityManagerDecorator::class) ->setConstructorArgs([$this->_getTestEntityManager($this->connection)]) ->setMethods(['newHydrator']) - ->getMock() - ; + ->getMock(); $this->hydrator = $this->createMock(AbstractHydrator::class); $this->em->method('newHydrator')->willReturn($this->hydrator); } - public function testExtraParametersAreStrippedWhenWalkerRemovingOriginalSelectElementsIsUsed() : void + public function testExtraParametersAreStrippedWhenWalkerRemovingOriginalSelectElementsIsUsed(): void { $paramInWhere = 1; $paramInSubSelect = 2; @@ -68,24 +66,21 @@ public function testExtraParametersAreStrippedWhenWalkerRemovingOriginalSelectEl $this->connection->expects($this->at(0)) ->method('executeQuery') - ->with($this->anything(), [$paramInWhere]) - ; + ->with($this->anything(), [$paramInWhere]); $this->connection->expects($this->at(1)) ->method('executeQuery') - ->with($this->anything(), [$paramInWhere]) - ; + ->with($this->anything(), [$paramInWhere]); $this->connection->expects($this->at(2)) ->method('executeQuery') - ->with($this->anything(), [$paramInSubSelect, $paramInWhere, $returnedIds]) - ; + ->with($this->anything(), [$paramInSubSelect, $paramInWhere, $returnedIds]); $paginator->count(); $paginator->getIterator(); } - public function testPaginatorNotCaringAboutExtraParametersWithoutOutputWalkers() : void + public function testPaginatorNotCaringAboutExtraParametersWithoutOutputWalkers(): void { $this->connection->expects($this->exactly(3))->method('executeQuery'); @@ -94,7 +89,7 @@ public function testPaginatorNotCaringAboutExtraParametersWithoutOutputWalkers() $this->createPaginatorWithExtraParametersWithoutOutputWalkers([])->getIterator(); } - public function testgetIteratorDoesCareAboutExtraParametersWithoutOutputWalkersWhenResultIsNotEmpty() : void + public function testgetIteratorDoesCareAboutExtraParametersWithoutOutputWalkersWhenResultIsNotEmpty(): void { $this->connection->expects($this->exactly(1))->method('executeQuery'); $this->expectException(Query\QueryException::class); @@ -106,7 +101,7 @@ public function testgetIteratorDoesCareAboutExtraParametersWithoutOutputWalkersW /** * @param int[][] $willReturnRows */ - private function createPaginatorWithExtraParametersWithoutOutputWalkers(array $willReturnRows) : Paginator + private function createPaginatorWithExtraParametersWithoutOutputWalkers(array $willReturnRows): Paginator { $this->hydrator->method('hydrateAll')->willReturn($willReturnRows); $this->connection->method('executeQuery')->with($this->anything(), []); diff --git a/tests/Doctrine/Tests/ORM/Tools/Pagination/WhereInWalkerTest.php b/tests/Doctrine/Tests/ORM/Tools/Pagination/WhereInWalkerTest.php index 647fed17420..d97bb21c0f1 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Pagination/WhereInWalkerTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Pagination/WhereInWalkerTest.php @@ -1,5 +1,7 @@ entityManager->createQuery( + $query = $this->entityManager->createQuery( 'SELECT u, g FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.groups g' ); $whereInQuery = clone $query; @@ -34,7 +36,8 @@ public function testWhereInQuery_NoWhere() $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, [1, 2, 3, 4, 5, 6, 7, 8, 9, 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() + '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() ); $this->assertPaginatorWhereInParameterToBe( @@ -43,9 +46,9 @@ public function testWhereInQuery_NoWhere() ); } - public function testCountQuery_MixedResultsWithName() + public function testCountQuery_MixedResultsWithName(): void { - $query = $this->entityManager->createQuery( + $query = $this->entityManager->createQuery( 'SELECT a, sum(a.name) as foo FROM Doctrine\Tests\ORM\Tools\Pagination\Author a' ); $whereInQuery = clone $query; @@ -54,7 +57,8 @@ public function testCountQuery_MixedResultsWithName() $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, [1, 2, 3, 4, 5, 6, 7, 8, 9, 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() + '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() ); $this->assertPaginatorWhereInParameterToBe( @@ -63,9 +67,9 @@ public function testCountQuery_MixedResultsWithName() ); } - public function testWhereInQuery_SingleWhere() + public function testWhereInQuery_SingleWhere(): void { - $query = $this->entityManager->createQuery( + $query = $this->entityManager->createQuery( 'SELECT u, g FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.groups g WHERE 1 = 1' ); $whereInQuery = clone $query; @@ -74,7 +78,8 @@ public function testWhereInQuery_SingleWhere() $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, [1, 2, 3, 4, 5, 6, 7, 8, 9, 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() + '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() ); $this->assertPaginatorWhereInParameterToBe( @@ -83,9 +88,9 @@ public function testWhereInQuery_SingleWhere() ); } - public function testWhereInQuery_MultipleWhereWithAnd() + public function testWhereInQuery_MultipleWhereWithAnd(): void { - $query = $this->entityManager->createQuery( + $query = $this->entityManager->createQuery( 'SELECT u, g FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.groups g WHERE 1 = 1 AND 2 = 2' ); $whereInQuery = clone $query; @@ -94,7 +99,8 @@ public function testWhereInQuery_MultipleWhereWithAnd() $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, [1, 2, 3, 4, 5, 6, 7, 8, 9, 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() + '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() ); $this->assertPaginatorWhereInParameterToBe( @@ -103,9 +109,9 @@ public function testWhereInQuery_MultipleWhereWithAnd() ); } - public function testWhereInQuery_MultipleWhereWithOr() + public function testWhereInQuery_MultipleWhereWithOr(): void { - $query = $this->entityManager->createQuery( + $query = $this->entityManager->createQuery( 'SELECT u, g FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.groups g WHERE 1 = 1 OR 2 = 2' ); $whereInQuery = clone $query; @@ -114,7 +120,8 @@ public function testWhereInQuery_MultipleWhereWithOr() $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, [1, 2, 3, 4, 5, 6, 7, 8, 9, 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() + '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() ); $this->assertPaginatorWhereInParameterToBe( @@ -123,9 +130,9 @@ public function testWhereInQuery_MultipleWhereWithOr() ); } - public function testWhereInQuery_MultipleWhereWithMixed_1() + public function testWhereInQuery_MultipleWhereWithMixed_1(): void { - $query = $this->entityManager->createQuery( + $query = $this->entityManager->createQuery( 'SELECT u, g FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.groups g WHERE (1 = 1 OR 2 = 2) AND 3 = 3' ); $whereInQuery = clone $query; @@ -134,7 +141,8 @@ public function testWhereInQuery_MultipleWhereWithMixed_1() $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, [1, 2, 3, 4, 5, 6, 7, 8, 9, 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() + '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() ); $this->assertPaginatorWhereInParameterToBe( @@ -143,9 +151,9 @@ public function testWhereInQuery_MultipleWhereWithMixed_1() ); } - public function testWhereInQuery_MultipleWhereWithMixed_2() + public function testWhereInQuery_MultipleWhereWithMixed_2(): void { - $query = $this->entityManager->createQuery( + $query = $this->entityManager->createQuery( 'SELECT u, g FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.groups g WHERE 1 = 1 AND 2 = 2 OR 3 = 3' ); $whereInQuery = clone $query; @@ -154,7 +162,8 @@ public function testWhereInQuery_MultipleWhereWithMixed_2() $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, [1, 2, 3, 4, 5, 6, 7, 8, 9, 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() + '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() ); $this->assertPaginatorWhereInParameterToBe( @@ -163,9 +172,9 @@ public function testWhereInQuery_MultipleWhereWithMixed_2() ); } - public function testWhereInQuery_WhereNot() + public function testWhereInQuery_WhereNot(): void { - $query = $this->entityManager->createQuery( + $query = $this->entityManager->createQuery( 'SELECT u, g FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.groups g WHERE NOT 1 = 2' ); $whereInQuery = clone $query; @@ -174,7 +183,8 @@ public function testWhereInQuery_WhereNot() $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, [1, 2, 3, 4, 5, 6, 7, 8, 9, 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() + '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() ); $this->assertPaginatorWhereInParameterToBe( @@ -186,9 +196,9 @@ public function testWhereInQuery_WhereNot() /** * Arbitrary Join */ - public function testWhereInQueryWithArbitraryJoin_NoWhere() + public function testWhereInQueryWithArbitraryJoin_NoWhere(): void { - $whereInQuery = $this->entityManager->createQuery( + $whereInQuery = $this->entityManager->createQuery( 'SELECT p FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost p JOIN Doctrine\Tests\ORM\Tools\Pagination\Category c WITH p.category = c' ); $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [WhereInWalker::class]); @@ -196,7 +206,8 @@ public function testWhereInQueryWithArbitraryJoin_NoWhere() $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, [1, 2, 3, 4, 5, 6, 7, 8, 9, 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() + '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() ); $this->assertPaginatorWhereInParameterToBe( @@ -205,7 +216,7 @@ public function testWhereInQueryWithArbitraryJoin_NoWhere() ); } - public function testWhereInQueryWithArbitraryJoin_SingleWhere() + public function testWhereInQueryWithArbitraryJoin_SingleWhere(): void { $whereInQuery = $this->entityManager->createQuery( 'SELECT p FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost p JOIN Doctrine\Tests\ORM\Tools\Pagination\Category c WITH p.category = c WHERE 1 = 1' @@ -215,7 +226,8 @@ public function testWhereInQueryWithArbitraryJoin_SingleWhere() $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, [1, 2, 3, 4, 5, 6, 7, 8, 9, 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() + '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() ); $this->assertPaginatorWhereInParameterToBe( @@ -224,7 +236,7 @@ public function testWhereInQueryWithArbitraryJoin_SingleWhere() ); } - public function testWillReplaceBoundQueryIdentifiersWithConvertedTypesAsPerIdentifierMapping() : void + public function testWillReplaceBoundQueryIdentifiersWithConvertedTypesAsPerIdentifierMapping(): void { $whereInQuery = $this->entityManager->createQuery( 'SELECT e.id4 FROM ' . AuxiliaryEntity::class . ' e' @@ -239,7 +251,7 @@ public function testWillReplaceBoundQueryIdentifiersWithConvertedTypesAsPerIdent ); } - public function testWillReplaceBoundQueryIdentifiersWithConvertedTypesAsPerAssociatedEntityIdentifierMapping() : void + public function testWillReplaceBoundQueryIdentifiersWithConvertedTypesAsPerAssociatedEntityIdentifierMapping(): void { $whereInQuery = $this->entityManager->createQuery( 'SELECT e FROM ' . OwningManyToOneIdForeignKeyEntity::class . ' e' @@ -255,7 +267,7 @@ public function testWillReplaceBoundQueryIdentifiersWithConvertedTypesAsPerAssoc } /** @param mixed $parameter */ - private function assertPaginatorWhereInParameterToBe(Query $query, $parameter) : void + private function assertPaginatorWhereInParameterToBe(Query $query, $parameter): void { $query->getSQL(); // forces walker to process the query @@ -265,4 +277,3 @@ private function assertPaginatorWhereInParameterToBe(Query $query, $parameter) : self::assertSame($parameter, $boundParameter->getValue()); } } - diff --git a/tests/Doctrine/Tests/ORM/Tools/ResolveTargetEntityListenerTest.php b/tests/Doctrine/Tests/ORM/Tools/ResolveTargetEntityListenerTest.php index 9189e53dec4..b13dada1f0f 100644 --- a/tests/Doctrine/Tests/ORM/Tools/ResolveTargetEntityListenerTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/ResolveTargetEntityListenerTest.php @@ -1,43 +1,40 @@ createAnnotationDriver(); $this->em = $this->_getTestEntityManager(); $this->em->getConfiguration()->setMetadataDriverImpl($annotationDriver); - $this->factory = $this->em->getMetadataFactory(); + $this->factory = $this->em->getMetadataFactory(); $this->listener = new ResolveTargetEntityListener(); } /** * @group DDC-1544 */ - public function testResolveTargetEntityListenerCanResolveTargetEntity() + public function testResolveTargetEntityListenerCanResolveTargetEntity(): void { $evm = $this->em->getEventManager(); $this->listener->addResolveTargetEntity(ResolveTargetInterface::class, ResolveTargetEntity::class, []); @@ -60,7 +57,7 @@ public function testResolveTargetEntityListenerCanResolveTargetEntity() * @group 1181 * @group 385 */ - public function testResolveTargetEntityListenerCanRetrieveTargetEntityByInterfaceName() + public function testResolveTargetEntityListenerCanRetrieveTargetEntityByInterfaceName(): void { $this->listener->addResolveTargetEntity(ResolveTargetInterface::class, ResolveTargetEntity::class, []); @@ -74,14 +71,14 @@ public function testResolveTargetEntityListenerCanRetrieveTargetEntityByInterfac /** * @group DDC-2109 */ - public function testAssertTableColumnsAreNotAddedInManyToMany() + public function testAssertTableColumnsAreNotAddedInManyToMany(): void { $evm = $this->em->getEventManager(); $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); + $cm = $this->factory->getMetadataFor(ResolveTargetEntity::class); $meta = $cm->associationMappings['manyToMany']; $this->assertSame(TargetEntity::class, $meta['targetEntity']); @@ -91,10 +88,9 @@ public function testAssertTableColumnsAreNotAddedInManyToMany() /** * @group 1572 * @group functional - * * @coversNothing */ - public function testDoesResolveTargetEntitiesInDQLAlsoWithInterfaces() + public function testDoesResolveTargetEntitiesInDQLAlsoWithInterfaces(): void { $evm = $this->em->getEventManager(); $this->listener->addResolveTargetEntity(ResolveTargetInterface::class, ResolveTargetEntity::class, []); @@ -113,7 +109,7 @@ public function testDoesResolveTargetEntitiesInDQLAlsoWithInterfaces() interface ResolveTargetInterface { - public function getId(); + public function getId(): void; } interface TargetInterface extends ResolveTargetInterface @@ -132,19 +128,13 @@ class ResolveTargetEntity implements ResolveTargetInterface */ private $id; - /** - * @ManyToMany(targetEntity="Doctrine\Tests\ORM\Tools\TargetInterface") - */ + /** @ManyToMany(targetEntity="Doctrine\Tests\ORM\Tools\TargetInterface") */ private $manyToMany; - /** - * @ManyToOne(targetEntity="Doctrine\Tests\ORM\Tools\ResolveTargetInterface", inversedBy="oneToMany") - */ + /** @ManyToOne(targetEntity="Doctrine\Tests\ORM\Tools\ResolveTargetInterface", inversedBy="oneToMany") */ private $manyToOne; - /** - * @OneToMany(targetEntity="Doctrine\Tests\ORM\Tools\ResolveTargetInterface", mappedBy="manyToOne") - */ + /** @OneToMany(targetEntity="Doctrine\Tests\ORM\Tools\ResolveTargetInterface", mappedBy="manyToOne") */ private $oneToMany; /** diff --git a/tests/Doctrine/Tests/ORM/Tools/SchemaToolTest.php b/tests/Doctrine/Tests/ORM/Tools/SchemaToolTest.php index 24415af92e6..2edd9b3f40a 100644 --- a/tests/Doctrine/Tests/ORM/Tools/SchemaToolTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/SchemaToolTest.php @@ -1,5 +1,7 @@ _getTestEntityManager(); + $em = $this->_getTestEntityManager(); $schemaTool = new SchemaTool($em); $classes = [ @@ -43,13 +46,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."); + $this->assertTrue($schema->hasTable('cms_users'), 'Table cms_users should exist.'); + $this->assertTrue($schema->getTable('cms_users')->columnsAreIndexed(['username']), 'username column should be indexed.'); } - public function testAnnotationOptionsAttribute() : void + public function testAnnotationOptionsAttribute(): void { - $em = $this->_getTestEntityManager(); + $em = $this->_getTestEntityManager(); $schemaTool = new SchemaTool($em); $schema = $schemaTool->getSchemaFromMetadata( @@ -68,23 +71,23 @@ public function testAnnotationOptionsAttribute() : void /** * @group DDC-200 */ - public function testPassColumnDefinitionToJoinColumn() + public function testPassColumnDefinitionToJoinColumn(): void { - $customColumnDef = "MEDIUMINT(6) UNSIGNED NOT NULL"; + $customColumnDef = 'MEDIUMINT(6) UNSIGNED NOT NULL'; - $em = $this->_getTestEntityManager(); + $em = $this->_getTestEntityManager(); $schemaTool = new SchemaTool($em); - $avatar = $em->getClassMetadata(ForumAvatar::class); + $avatar = $em->getClassMetadata(ForumAvatar::class); $avatar->fieldMappings['id']['columnDefinition'] = $customColumnDef; - $user = $em->getClassMetadata(ForumUser::class); + $user = $em->getClassMetadata(ForumUser::class); $classes = [$avatar, $user]; $schema = $schemaTool->getSchemaFromMetadata($classes); $this->assertTrue($schema->hasTable('forum_users')); - $table = $schema->getTable("forum_users"); + $table = $schema->getTable('forum_users'); $this->assertTrue($table->hasColumn('avatar_id')); $this->assertEquals($customColumnDef, $table->getColumn('avatar_id')->getColumnDefinition()); } @@ -92,20 +95,20 @@ public function testPassColumnDefinitionToJoinColumn() /** * @group 6830 */ - public function testPassColumnOptionsToJoinColumn() : void + public function testPassColumnOptionsToJoinColumn(): void { - $em = $this->_getTestEntityManager(); + $em = $this->_getTestEntityManager(); $category = $em->getClassMetadata(GH6830Category::class); - $board = $em->getClassMetadata(GH6830Board::class); + $board = $em->getClassMetadata(GH6830Board::class); $schemaTool = new SchemaTool($em); - $schema = $schemaTool->getSchemaFromMetadata([$category, $board]); + $schema = $schemaTool->getSchemaFromMetadata([$category, $board]); self::assertTrue($schema->hasTable('GH6830Category')); self::assertTrue($schema->hasTable('GH6830Board')); $tableCategory = $schema->getTable('GH6830Category'); - $tableBoard = $schema->getTable('GH6830Board'); + $tableBoard = $schema->getTable('GH6830Board'); self::assertTrue($tableBoard->hasColumn('category_id')); @@ -130,13 +133,14 @@ public function testPassColumnOptionsToJoinColumn() : void /** * @group DDC-283 */ - public function testPostGenerateEvents() + public function testPostGenerateEvents(): void { $listener = new GenerateSchemaEventListener(); $em = $this->_getTestEntityManager(); $em->getEventManager()->addEventListener( - [ToolEvents::postGenerateSchemaTable, ToolEvents::postGenerateSchema], $listener + [ToolEvents::postGenerateSchemaTable, ToolEvents::postGenerateSchema], + $listener ); $schemaTool = new SchemaTool($em); @@ -156,9 +160,9 @@ public function testPostGenerateEvents() $this->assertTrue($listener->schemaCalled); } - public function testNullDefaultNotAddedToCustomSchemaOptions() + public function testNullDefaultNotAddedToCustomSchemaOptions(): void { - $em = $this->_getTestEntityManager(); + $em = $this->_getTestEntityManager(); $schemaTool = new SchemaTool($em); $customSchemaOptions = $schemaTool->getSchemaFromMetadata([$em->getClassMetadata(NullDefaultColumn::class)]) @@ -172,7 +176,7 @@ public function testNullDefaultNotAddedToCustomSchemaOptions() /** * @group DDC-3671 */ - public function testSchemaHasProperIndexesFromUniqueConstraintAnnotation() + public function testSchemaHasProperIndexesFromUniqueConstraintAnnotation(): void { $em = $this->_getTestEntityManager(); $schemaTool = new SchemaTool($em); @@ -190,26 +194,26 @@ public function testSchemaHasProperIndexesFromUniqueConstraintAnnotation() $this->assertTrue($table->hasIndex('uniq_hash')); } - public function testRemoveUniqueIndexOverruledByPrimaryKey() + public function testRemoveUniqueIndexOverruledByPrimaryKey(): void { $em = $this->_getTestEntityManager(); $schemaTool = new SchemaTool($em); $classes = [ $em->getClassMetadata(FirstEntity::class), - $em->getClassMetadata(SecondEntity::class) + $em->getClassMetadata(SecondEntity::class), ]; $schema = $schemaTool->getSchemaFromMetadata($classes); - $this->assertTrue($schema->hasTable('first_entity'), "Table first_entity should exist."); + $this->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"); + $this->assertCount(1, $indexes, 'there should be only one index'); + $this->assertTrue(current($indexes)->isPrimary(), 'index should be primary'); } - public function testSetDiscriminatorColumnWithoutLength() : void + public function testSetDiscriminatorColumnWithoutLength(): void { $em = $this->_getTestEntityManager(); $schemaTool = new SchemaTool($em); @@ -229,7 +233,7 @@ public function testSetDiscriminatorColumnWithoutLength() : void $this->assertEquals(255, $column->getLength()); } - public function testDerivedCompositeKey() : void + public function testDerivedCompositeKey(): void { $em = $this->_getTestEntityManager(); $schemaTool = new SchemaTool($em); @@ -283,23 +287,21 @@ class TestEntityWithAnnotationOptionsAttribute /** @Id @Column */ private $id; - /** - * @Column(type="string", options={"foo": "bar", "baz": {"key": "val"}}) - */ + /** @Column(type="string", options={"foo": "bar", "baz": {"key": "val"}}) */ private $test; } class GenerateSchemaEventListener { - public $tableCalls = 0; + public $tableCalls = 0; public $schemaCalled = false; - public function postGenerateSchemaTable(GenerateSchemaTableEventArgs $eventArgs) + public function postGenerateSchemaTable(GenerateSchemaTableEventArgs $eventArgs): void { $this->tableCalls++; } - public function postGenerateSchema(GenerateSchemaEventArgs $eventArgs) + public function postGenerateSchema(GenerateSchemaEventArgs $eventArgs): void { $this->schemaCalled = true; } @@ -316,9 +318,7 @@ class UniqueConstraintAnnotationModel /** @Id @Column */ private $id; - /** - * @Column(name="hash", type="string", length=8, nullable=false, unique=true) - */ + /** @Column(name="hash", type="string", length=8, nullable=false, unique=true) */ private $hash; } @@ -340,9 +340,7 @@ class FirstEntity */ public $secondEntity; - /** - * @Column(name="name") - */ + /** @Column(name="name") */ public $name; } @@ -358,9 +356,7 @@ class SecondEntity */ public $fist_entity_id; - /** - * @Column(name="name") - */ + /** @Column(name="name") */ public $name; } @@ -390,13 +386,10 @@ class GH6830Category /** * @Id * @Column(type="string", length=8, options={"fixed":true, "collation":"latin1_bin", "foo":"bar"}) - * * @var string */ public $id; - /** - * @OneToMany(targetEntity=GH6830Board::class, mappedBy="category") - */ + /** @OneToMany(targetEntity=GH6830Board::class, mappedBy="category") */ public $boards; } diff --git a/tests/Doctrine/Tests/ORM/Tools/SchemaValidatorTest.php b/tests/Doctrine/Tests/ORM/Tools/SchemaValidatorTest.php index 939a049232c..284d9c3d4a0 100644 --- a/tests/Doctrine/Tests/ORM/Tools/SchemaValidatorTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/SchemaValidatorTest.php @@ -4,8 +4,8 @@ namespace Doctrine\Tests\ORM\Tools; +use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\EntityManager; -use Doctrine\ORM\Mapping\Embeddable; use Doctrine\ORM\Mapping\OneToOne; use Doctrine\ORM\Tools\SchemaValidator; use Doctrine\Tests\OrmTestCase; @@ -18,7 +18,7 @@ class SchemaValidatorTest extends OrmTestCase /** @var SchemaValidator */ private $validator = null; - protected function setUp() : void + protected function setUp(): void { $this->em = $this->_getTestEntityManager(); $this->validator = new SchemaValidator($this->em); @@ -27,7 +27,7 @@ protected function setUp() : void /** * @dataProvider modelSetProvider */ - public function testCmsModelSet(string $path) + public function testCmsModelSet(string $path): void { $this->em->getConfiguration() ->getMetadataDriverImpl() @@ -36,7 +36,7 @@ public function testCmsModelSet(string $path) self::assertEmpty($this->validator->validateMapping()); } - public function modelSetProvider() : array + public function modelSetProvider(): array { return [ 'cms' => [__DIR__ . '/../../Models/CMS'], @@ -51,7 +51,7 @@ public function modelSetProvider() : array /** * @group DDC-1439 */ - public function testInvalidManyToManyJoinColumnSchema() + public function testInvalidManyToManyJoinColumnSchema(): void { $class1 = $this->em->getClassMetadata(InvalidEntity1::class); $class2 = $this->em->getClassMetadata(InvalidEntity2::class); @@ -70,7 +70,7 @@ public function testInvalidManyToManyJoinColumnSchema() /** * @group DDC-1439 */ - public function testInvalidToOneJoinColumnSchema() + public function testInvalidToOneJoinColumnSchema(): void { $class1 = $this->em->getClassMetadata(InvalidEntity1::class); $class2 = $this->em->getClassMetadata(InvalidEntity2::class); @@ -89,7 +89,7 @@ public function testInvalidToOneJoinColumnSchema() /** * @group DDC-1587 */ - public function testValidOneToOneAsIdentifierSchema() + public function testValidOneToOneAsIdentifierSchema(): void { $class1 = $this->em->getClassMetadata(DDC1587ValidEntity2::class); $class2 = $this->em->getClassMetadata(DDC1587ValidEntity1::class); @@ -102,7 +102,7 @@ public function testValidOneToOneAsIdentifierSchema() /** * @group DDC-1649 */ - public function testInvalidTripleAssociationAsKeyMapping() + public function testInvalidTripleAssociationAsKeyMapping(): void { $classThree = $this->em->getClassMetadata(DDC1649Three::class); $ce = $this->validator->validateClass($classThree); @@ -119,7 +119,7 @@ public function testInvalidTripleAssociationAsKeyMapping() /** * @group DDC-3274 */ - public function testInvalidBiDirectionalRelationMappingMissingInversedByAttribute() + public function testInvalidBiDirectionalRelationMappingMissingInversedByAttribute(): void { $class = $this->em->getClassMetadata(DDC3274One::class); $ce = $this->validator->validateClass($class); @@ -137,7 +137,7 @@ public function testInvalidBiDirectionalRelationMappingMissingInversedByAttribut /** * @group DDC-3322 */ - public function testInvalidOrderByInvalidField() + public function testInvalidOrderByInvalidField(): void { $class = $this->em->getClassMetadata(DDC3322One::class); $ce = $this->validator->validateClass($class); @@ -154,7 +154,7 @@ public function testInvalidOrderByInvalidField() /** * @group DDC-3322 */ - public function testInvalidOrderByCollectionValuedAssociation() + public function testInvalidOrderByCollectionValuedAssociation(): void { $class = $this->em->getClassMetadata(DDC3322Two::class); $ce = $this->validator->validateClass($class); @@ -171,7 +171,7 @@ public function testInvalidOrderByCollectionValuedAssociation() /** * @group DDC-3322 */ - public function testInvalidOrderByAssociationInverseSide() + public function testInvalidOrderByAssociationInverseSide(): void { $class = $this->em->getClassMetadata(DDC3322Three::class); $ce = $this->validator->validateClass($class); @@ -188,7 +188,7 @@ public function testInvalidOrderByAssociationInverseSide() /** * @group 8052 */ - public function testInvalidAssociationInsideEmbeddable() + public function testInvalidAssociationInsideEmbeddable(): void { $class = $this->em->getClassMetadata(EmbeddableWithAssociation::class); $ce = $this->validator->validateClass($class); @@ -205,16 +205,27 @@ public function testInvalidAssociationInsideEmbeddable() */ class InvalidEntity1 { - /** @Id @Column */ + /** + * @var mixed + * @Id + * @Column + */ protected $key1; - /** @Id @Column */ + + /** + * @var mixed + * @Id + * @Column + */ protected $key2; + /** + * @var ArrayCollection * @ManyToMany (targetEntity="InvalidEntity2") * @JoinTable (name="Entity1Entity2", * joinColumns={@JoinColumn(name="key1", referencedColumnName="key1")}, * inverseJoinColumns={@JoinColumn(name="key3", referencedColumnName="key3")} - * ) + * ) */ protected $entity2; } @@ -224,13 +235,24 @@ class InvalidEntity1 */ class InvalidEntity2 { - /** @Id @Column */ + /** + * @var mixed + * @Id + * @Column + */ protected $key3; - /** @Id @Column */ + /** + * @var mixed + * @Id + * @Column + */ protected $key4; - /** @ManyToOne(targetEntity="InvalidEntity1") */ + /** + * @var InvalidEntity1 + * @ManyToOne(targetEntity="InvalidEntity1") + */ protected $assoc; } @@ -287,7 +309,12 @@ class DDC1587ValidEntity2 */ class DDC1649One { - /** @Id @Column @GeneratedValue */ + /** + * @var mixed + * @Id + * @Column + * @GeneratedValue + */ public $id; } @@ -296,7 +323,12 @@ class DDC1649One */ class DDC1649Two { - /** @Id @ManyToOne(targetEntity="DDC1649One")@JoinColumn(name="id", referencedColumnName="id") */ + /** + * @var DDC1649One + * @Id + * @ManyToOne(targetEntity="DDC1649One") + * @JoinColumn(name="id", referencedColumnName="id") + */ public $one; } @@ -305,8 +337,12 @@ class DDC1649Two */ class DDC1649Three { - /** @Id @ManyToOne(targetEntity="DDC1649Two") @JoinColumn(name="id", - * referencedColumnName="id") */ + /** + * @var DDC1649Two + * @Id + * @ManyToOne(targetEntity="DDC1649Two") + * @JoinColumn(name="id", referencedColumnName="id") + */ private $two; } @@ -315,10 +351,18 @@ class DDC1649Three */ class DDC3274One { - /** @Id @Column @GeneratedValue */ + /** + * @var mixed + * @Id + * @Column + * @GeneratedValue + */ private $id; - /** @OneToMany(targetEntity="DDC3274Two", mappedBy="one") */ + /** + * @var ArrayCollection + * @OneToMany(targetEntity="DDC3274Two", mappedBy="one") + */ private $two; } @@ -328,6 +372,7 @@ class DDC3274One class DDC3274Two { /** + * @var DDC3274One * @Id * @ManyToOne(targetEntity="DDC3274One") */ @@ -339,37 +384,72 @@ class DDC3274Two */ class DDC3322ValidEntity1 { - /** @Id @Column @GeneratedValue */ + /** + * @var mixed + * @Id + * @Column + * @GeneratedValue + */ private $id; - /** @ManyToOne(targetEntity="DDC3322One", inversedBy="validAssoc") */ + /** + * @var DDC3322One + * @ManyToOne(targetEntity="DDC3322One", inversedBy="validAssoc") + */ private $oneValid; - /** @ManyToOne(targetEntity="DDC3322One", inversedBy="invalidAssoc") */ + /** + * @var DDC3322One + * @ManyToOne(targetEntity="DDC3322One", inversedBy="invalidAssoc") + */ private $oneInvalid; - /** @ManyToOne(targetEntity="DDC3322Two", inversedBy="validAssoc") */ + /** + * @var DDC3322Two + * @ManyToOne(targetEntity="DDC3322Two", inversedBy="validAssoc") + */ private $twoValid; - /** @ManyToOne(targetEntity="DDC3322Two", inversedBy="invalidAssoc") */ + /** + * @var DDC3322Two + * @ManyToOne(targetEntity="DDC3322Two", inversedBy="invalidAssoc") + */ private $twoInvalid; - /** @ManyToOne(targetEntity="DDC3322Three", inversedBy="validAssoc") */ + /** + * @var DDC3322Three + * @ManyToOne(targetEntity="DDC3322Three", inversedBy="validAssoc") + */ private $threeValid; - /** @ManyToOne(targetEntity="DDC3322Three", inversedBy="invalidAssoc") */ + /** + * @var DDC3322Three + * @ManyToOne(targetEntity="DDC3322Three", inversedBy="invalidAssoc") + */ private $threeInvalid; - /** @OneToMany(targetEntity="DDC3322ValidEntity2", mappedBy="manyToOne") */ + /** + * @var DDC3322ValidEntity2 + * @OneToMany(targetEntity="DDC3322ValidEntity2", mappedBy="manyToOne") + */ private $oneToMany; - /** @ManyToOne(targetEntity="DDC3322ValidEntity2", inversedBy="oneToMany") */ + /** + * @var DDC3322ValidEntity2 + * @ManyToOne(targetEntity="DDC3322ValidEntity2", inversedBy="oneToMany") + */ private $manyToOne; - /** @OneToOne(targetEntity="DDC3322ValidEntity2", mappedBy="oneToOneOwning") */ + /** + * @var DDC3322ValidEntity2 + * @OneToOne(targetEntity="DDC3322ValidEntity2", mappedBy="oneToOneOwning") + */ private $oneToOneInverse; - /** @OneToOne(targetEntity="DDC3322ValidEntity2", inversedBy="oneToOneInverse") */ + /** + * @var DDC3322ValidEntity2 + * @OneToOne(targetEntity="DDC3322ValidEntity2", inversedBy="oneToOneInverse") + */ private $oneToOneOwning; } diff --git a/tests/Doctrine/Tests/ORM/Tools/SetupTest.php b/tests/Doctrine/Tests/ORM/Tools/SetupTest.php index f784eb7b3e8..1bf2056078f 100644 --- a/tests/Doctrine/Tests/ORM/Tools/SetupTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/SetupTest.php @@ -1,5 +1,7 @@ originalAutoloaderCount = count(spl_autoload_functions()); - $this->originalIncludePath = get_include_path(); + $this->originalIncludePath = get_include_path(); } - public function tearDown() : void + public function tearDown(): void { - if ( ! $this->originalIncludePath) { + if (! $this->originalIncludePath) { return; } set_include_path($this->originalIncludePath); - $loaders = spl_autoload_functions(); + $loaders = spl_autoload_functions(); $numberOfLoaders = count($loaders); for ($i = 0; $i < $numberOfLoaders; $i++) { - if ($i > $this->originalAutoloaderCount+1) { + if ($i > $this->originalAutoloaderCount + 1) { spl_autoload_unregister($loaders[$i]); } } } - public function testDirectoryAutoload() + public function testDirectoryAutoload(): void { - Setup::registerAutoloadDirectory(__DIR__ . "/../../../../../vendor/doctrine/common/lib"); + Setup::registerAutoloadDirectory(__DIR__ . '/../../../../../vendor/doctrine/common/lib'); $this->assertEquals($this->originalAutoloaderCount + 2, count(spl_autoload_functions())); } - public function testAnnotationConfiguration() + public function testAnnotationConfiguration(): void { $config = Setup::createAnnotationMetadataConfiguration([], true); @@ -58,7 +67,7 @@ public function testAnnotationConfiguration() $this->assertInstanceOf(AnnotationDriver::class, $config->getMetadataDriverImpl()); } - public function testXMLConfiguration() + public function testXMLConfiguration(): void { $config = Setup::createXMLMetadataConfiguration([], true); @@ -66,7 +75,7 @@ public function testXMLConfiguration() $this->assertInstanceOf(XmlDriver::class, $config->getMetadataDriverImpl()); } - public function testYAMLConfiguration() + public function testYAMLConfiguration(): void { $config = Setup::createYAMLMetadataConfiguration([], true); @@ -78,7 +87,7 @@ public function testYAMLConfiguration() /** * @group 5904 */ - public function testCacheNamespaceShouldBeGeneratedWhenCacheIsNotGiven() : void + public function testCacheNamespaceShouldBeGeneratedWhenCacheIsNotGiven(): void { $config = Setup::createConfiguration(false, '/foo'); $cache = $config->getMetadataCacheImpl(); @@ -89,7 +98,7 @@ public function testCacheNamespaceShouldBeGeneratedWhenCacheIsNotGiven() : void /** * @group 5904 */ - public function testCacheNamespaceShouldBeGeneratedWhenCacheIsGivenButHasNoNamespace() : void + public function testCacheNamespaceShouldBeGeneratedWhenCacheIsGivenButHasNoNamespace(): void { $config = Setup::createConfiguration(false, '/foo', new ArrayCache()); $cache = $config->getMetadataCacheImpl(); @@ -100,7 +109,7 @@ public function testCacheNamespaceShouldBeGeneratedWhenCacheIsGivenButHasNoNames /** * @group 5904 */ - public function testConfiguredCacheNamespaceShouldBeUsedAsPrefixOfGeneratedNamespace() : void + public function testConfiguredCacheNamespaceShouldBeUsedAsPrefixOfGeneratedNamespace(): void { $originalCache = new ArrayCache(); $originalCache->setNamespace('foo'); @@ -115,18 +124,18 @@ public function testConfiguredCacheNamespaceShouldBeUsedAsPrefixOfGeneratedNames /** * @group DDC-1350 */ - public function testConfigureProxyDir() + public function testConfigureProxyDir(): void { - $config = Setup::createAnnotationMetadataConfiguration([], true, "/foo"); + $config = Setup::createAnnotationMetadataConfiguration([], true, '/foo'); $this->assertEquals('/foo', $config->getProxyDir()); } /** * @group DDC-1350 */ - public function testConfigureCache() + public function testConfigureCache(): void { - $cache = new ArrayCache(); + $cache = new ArrayCache(); $config = Setup::createAnnotationMetadataConfiguration([], true, null, $cache); $this->assertSame($cache, $config->getResultCacheImpl()); @@ -137,7 +146,7 @@ public function testConfigureCache() /** * @group DDC-3190 */ - public function testConfigureCacheCustomInstance() + public function testConfigureCacheCustomInstance(): void { $cache = $this->createMock(Cache::class); $config = Setup::createConfiguration(true, null, $cache); diff --git a/tests/Doctrine/Tests/ORM/UnitOfWorkTest.php b/tests/Doctrine/Tests/ORM/UnitOfWorkTest.php index 088c8b59079..b9caa793871 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); + $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); } - public function testRegisterRemovedOnNewEntityIsIgnored() + public function testRegisterRemovedOnNewEntityIsIgnored(): void { - $user = new ForumUser(); + $user = new ForumUser(); $user->username = 'romanb'; $this->assertFalse($this->_unitOfWork->isScheduledForDelete($user)); $this->_unitOfWork->scheduleForDelete($user); $this->assertFalse($this->_unitOfWork->isScheduledForDelete($user)); } - /* Operational tests */ - public function testSavingSingleEntityWithIdentityColumnForcesInsert() + public function testSavingSingleEntityWithIdentityColumnForcesInsert(): void { // Setup fake persister and id generator for identity generation $userPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(ForumUser::class)); @@ -88,7 +97,7 @@ public function testSavingSingleEntityWithIdentityColumnForcesInsert() $userPersister->setMockIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY); // Test - $user = new ForumUser(); + $user = new ForumUser(); $user->username = 'romanb'; $this->_unitOfWork->persist($user); @@ -119,7 +128,7 @@ public function testSavingSingleEntityWithIdentityColumnForcesInsert() * Tests a scenario where a save() operation is cascaded from a ForumUser * to its associated ForumAvatar, both entities using IDENTITY id generation. */ - public function testCascadedIdentityColumnInsert() + public function testCascadedIdentityColumnInsert(): void { // Setup fake persister and id generator for identity generation //ForumUser @@ -132,10 +141,10 @@ public function testCascadedIdentityColumnInsert() $avatarPersister->setMockIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY); // Test - $user = new ForumUser(); + $user = new ForumUser(); $user->username = 'romanb'; - $avatar = new ForumAvatar(); - $user->avatar = $avatar; + $avatar = new ForumAvatar(); + $user->avatar = $avatar; $this->_unitOfWork->persist($user); // save cascaded to avatar $this->_unitOfWork->commit(); @@ -152,14 +161,14 @@ public function testCascadedIdentityColumnInsert() $this->assertEquals(0, count($avatarPersister->getDeletes())); } - public function testChangeTrackingNotify() + public function testChangeTrackingNotify(): void { $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 = new NotifyChangedEntity(); $entity->setData('thedata'); $this->_unitOfWork->persist($entity); @@ -187,7 +196,6 @@ public function testChangeTrackingNotify() $persister->reset(); $itemPersister->reset(); - $entity->getItems()->removeElement($item); $item->setOwner(null); $this->assertTrue($entity->getItems()->isDirty()); @@ -197,17 +205,17 @@ public function testChangeTrackingNotify() $this->assertTrue($updates[0] === $item); } - public function testChangeTrackingNotifyIndividualCommit() + public function testChangeTrackingNotifyIndividualCommit(): void { - $persister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata("Doctrine\Tests\ORM\NotifyChangedEntity")); + $persister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata('Doctrine\Tests\ORM\NotifyChangedEntity')); $this->_unitOfWork->setEntityPersister('Doctrine\Tests\ORM\NotifyChangedEntity', $persister); - $itemPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata("Doctrine\Tests\ORM\NotifyChangedRelatedItem")); + $itemPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata('Doctrine\Tests\ORM\NotifyChangedRelatedItem')); $this->_unitOfWork->setEntityPersister('Doctrine\Tests\ORM\NotifyChangedRelatedItem', $itemPersister); - $entity = new NotifyChangedEntity; + $entity = new NotifyChangedEntity(); $entity->setData('thedata'); - $entity2 = new NotifyChangedEntity; + $entity2 = new NotifyChangedEntity(); $entity2->setData('thedata'); $this->_unitOfWork->persist($entity); @@ -227,28 +235,28 @@ public function testChangeTrackingNotifyIndividualCommit() $this->_unitOfWork->commit($entity); $this->assertTrue($this->_unitOfWork->isScheduledForDirtyCheck($entity2)); - $this->assertEquals(array('data' => array('thedata', 'newdata')), $this->_unitOfWork->getEntityChangeSet($entity2)); + $this->assertEquals(['data' => ['thedata', 'newdata']], $this->_unitOfWork->getEntityChangeSet($entity2)); $this->assertFalse($this->_unitOfWork->isScheduledForDirtyCheck($entity)); - $this->assertEquals(array(), $this->_unitOfWork->getEntityChangeSet($entity)); + $this->assertEquals([], $this->_unitOfWork->getEntityChangeSet($entity)); } - public function testGetEntityStateOnVersionedEntityWithAssignedIdentifier() + public function testGetEntityStateOnVersionedEntityWithAssignedIdentifier(): void { $persister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(VersionedAssignedIdentifierEntity::class)); $this->_unitOfWork->setEntityPersister(VersionedAssignedIdentifierEntity::class, $persister); - $e = new VersionedAssignedIdentifierEntity(); + $e = new VersionedAssignedIdentifierEntity(); $e->id = 42; $this->assertEquals(UnitOfWork::STATE_NEW, $this->_unitOfWork->getEntityState($e)); $this->assertFalse($persister->isExistsCalled()); } - public function testGetEntityStateWithAssignedIdentity() + public function testGetEntityStateWithAssignedIdentity(): void { $persister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(CmsPhonenumber::class)); $this->_unitOfWork->setEntityPersister(CmsPhonenumber::class, $persister); - $ph = new CmsPhonenumber(); + $ph = new CmsPhonenumber(); $ph->phonenumber = '12345'; $this->assertEquals(UnitOfWork::STATE_NEW, $this->_unitOfWork->getEntityState($ph)); @@ -260,7 +268,7 @@ public function testGetEntityStateWithAssignedIdentity() $this->_unitOfWork->registerManaged($ph, ['phonenumber' => '12345'], []); $this->assertEquals(UnitOfWork::STATE_MANAGED, $this->_unitOfWork->getEntityState($ph)); $this->assertFalse($persister->isExistsCalled()); - $ph2 = new CmsPhonenumber(); + $ph2 = new CmsPhonenumber(); $ph2->phonenumber = '12345'; $this->assertEquals(UnitOfWork::STATE_DETACHED, $this->_unitOfWork->getEntityState($ph2)); $this->assertFalse($persister->isExistsCalled()); @@ -269,7 +277,7 @@ public function testGetEntityStateWithAssignedIdentity() /** * DDC-2086 [GH-484] Prevented 'Undefined index' notice when updating. */ - public function testNoUndefinedIndexNoticeOnScheduleForUpdateWithoutChanges() + public function testNoUndefinedIndexNoticeOnScheduleForUpdateWithoutChanges(): void { // Setup fake persister and id generator $userPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(ForumUser::class)); @@ -277,7 +285,7 @@ public function testNoUndefinedIndexNoticeOnScheduleForUpdateWithoutChanges() $this->_unitOfWork->setEntityPersister(ForumUser::class, $userPersister); // Create a test user - $user = new ForumUser(); + $user = new ForumUser(); $user->username = 'Jasper'; $this->_unitOfWork->persist($user); $this->_unitOfWork->commit(); @@ -296,20 +304,19 @@ public function testNoUndefinedIndexNoticeOnScheduleForUpdateWithoutChanges() /** * @group DDC-1984 */ - public function testLockWithoutEntityThrowsException() + public function testLockWithoutEntityThrowsException(): void { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->_unitOfWork->lock(null, null, null); } /** - * @group DDC-3490 + * @param mixed $invalidValue * + * @group DDC-3490 * @dataProvider invalidAssociationValuesDataProvider - * - * @param mixed $invalidValue */ - public function testRejectsPersistenceOfObjectsWithInvalidAssociationValue($invalidValue) + public function testRejectsPersistenceOfObjectsWithInvalidAssociationValue($invalidValue): void { $this->_unitOfWork->setEntityPersister( ForumUser::class, @@ -323,19 +330,18 @@ public function testRejectsPersistenceOfObjectsWithInvalidAssociationValue($inva $user->username = 'John'; $user->avatar = $invalidValue; - $this->expectException(\Doctrine\ORM\ORMInvalidArgumentException::class); + $this->expectException(ORMInvalidArgumentException::class); $this->_unitOfWork->persist($user); } /** - * @group DDC-3490 + * @param mixed $invalidValue * + * @group DDC-3490 * @dataProvider invalidAssociationValuesDataProvider - * - * @param mixed $invalidValue */ - public function testRejectsChangeSetComputationForObjectsWithInvalidAssociationValue($invalidValue) + public function testRejectsChangeSetComputationForObjectsWithInvalidAssociationValue($invalidValue): void { $metadata = $this->_emMock->getClassMetadata(ForumUser::class); @@ -351,7 +357,7 @@ public function testRejectsChangeSetComputationForObjectsWithInvalidAssociationV $user->username = 'John'; $user->avatar = $invalidValue; - $this->expectException(\Doctrine\ORM\ORMInvalidArgumentException::class); + $this->expectException(ORMInvalidArgumentException::class); $this->_unitOfWork->computeChangeSet($metadata, $user); } @@ -360,7 +366,7 @@ public function testRejectsChangeSetComputationForObjectsWithInvalidAssociationV * @group DDC-3619 * @group 1338 */ - public function testRemovedAndRePersistedEntitiesAreInTheIdentityMapAndAreNotGarbageCollected() + public function testRemovedAndRePersistedEntitiesAreInTheIdentityMapAndAreNotGarbageCollected(): void { $entity = new ForumUser(); $entity->id = 123; @@ -379,7 +385,7 @@ public function testRemovedAndRePersistedEntitiesAreInTheIdentityMapAndAreNotGar * @group 5849 * @group 5850 */ - public function testPersistedEntityAndClearManager() + public function testPersistedEntityAndClearManager(): void { $entity1 = new City(123, 'London'); $entity2 = new Country(456, 'United Kingdom'); @@ -400,10 +406,10 @@ public function testPersistedEntityAndClearManager() /** * @group #5579 */ - public function testEntityChangeSetIsNotClearedAfterFlushOnSingleEntity() : void + public function testEntityChangeSetIsNotClearedAfterFlushOnSingleEntity(): void { - $entity1 = new NotifyChangedEntity; - $entity2 = new NotifyChangedEntity; + $entity1 = new NotifyChangedEntity(); + $entity2 = new NotifyChangedEntity(); $entity1->setData('thedata'); $entity2->setData('thedata'); @@ -419,11 +425,11 @@ public function testEntityChangeSetIsNotClearedAfterFlushOnSingleEntity() : void /** * @group #5579 */ - public function testEntityChangeSetIsNotClearedAfterFlushOnArrayOfEntities() : void + public function testEntityChangeSetIsNotClearedAfterFlushOnArrayOfEntities(): void { - $entity1 = new NotifyChangedEntity; - $entity2 = new NotifyChangedEntity; - $entity3 = new NotifyChangedEntity; + $entity1 = new NotifyChangedEntity(); + $entity2 = new NotifyChangedEntity(); + $entity3 = new NotifyChangedEntity(); $entity1->setData('thedata'); $entity2->setData('thedata'); @@ -445,7 +451,7 @@ public function testEntityChangeSetIsNotClearedAfterFlushOnArrayOfEntities() : v * * @return mixed[][] */ - public function invalidAssociationValuesDataProvider() + public function invalidAssociationValuesDataProvider(): array { return [ ['foo'], @@ -459,13 +465,8 @@ public function invalidAssociationValuesDataProvider() /** * @dataProvider entitiesWithValidIdentifiersProvider - * - * @param object $entity - * @param string $idHash - * - * @return void */ - public function testAddToIdentityMapValidIdentifiers($entity, $idHash) + public function testAddToIdentityMapValidIdentifiers(object $entity, string $idHash): void { $this->_unitOfWork->persist($entity); $this->_unitOfWork->addToIdentityMap($entity); @@ -511,7 +512,7 @@ public function entitiesWithValidIdentifiersProvider() ]; } - public function testRegisteringAManagedInstanceRequiresANonEmptyIdentifier() + public function testRegisteringAManagedInstanceRequiresANonEmptyIdentifier(): void { $this->expectException(ORMInvalidArgumentException::class); @@ -519,24 +520,20 @@ public function testRegisteringAManagedInstanceRequiresANonEmptyIdentifier() } /** - * @dataProvider entitiesWithInvalidIdentifiersProvider + * @param array $identifier * - * @param object $entity - * @param array $identifier - * - * @return void + * @dataProvider entitiesWithInvalidIdentifiersProvider */ - public function testAddToIdentityMapInvalidIdentifiers($entity, array $identifier) + public function testAddToIdentityMapInvalidIdentifiers(object $entity, array $identifier): void { $this->expectException(ORMInvalidArgumentException::class); $this->_unitOfWork->registerManaged($entity, $identifier, []); } - public function entitiesWithInvalidIdentifiersProvider() { - $firstNullString = new EntityWithCompositeStringIdentifier(); + $firstNullString = new EntityWithCompositeStringIdentifier(); $firstNullString->id2 = uniqid('id2', true); @@ -556,7 +553,7 @@ public function entitiesWithInvalidIdentifiersProvider() * @group 5689 * @group 1465 */ - public function testObjectHashesOfMergedEntitiesAreNotUsedInOriginalEntityDataMap() + public function testObjectHashesOfMergedEntitiesAreNotUsedInOriginalEntityDataMap(): void { $user = new CmsUser(); $user->name = 'ocramius'; @@ -565,7 +562,6 @@ public function testObjectHashesOfMergedEntitiesAreNotUsedInOriginalEntityDataMa 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; @@ -585,7 +581,7 @@ public function testObjectHashesOfMergedEntitiesAreNotUsedInOriginalEntityDataMa * @group 5570 * @group 6174 */ - public function testMergeWithNewEntityWillPersistItAndTriggerPrePersistListenersWithMergedEntityData() + public function testMergeWithNewEntityWillPersistItAndTriggerPrePersistListenersWithMergedEntityData(): void { $entity = new EntityWithRandomlyGeneratedField(); @@ -595,7 +591,7 @@ public function testMergeWithNewEntityWillPersistItAndTriggerPrePersistListeners ->eventManager ->expects(self::any()) ->method('hasListeners') - ->willReturnCallback(function ($eventName) { + ->willReturnCallback(static function ($eventName) { return $eventName === Events::prePersist; }); $this @@ -604,9 +600,9 @@ public function testMergeWithNewEntityWillPersistItAndTriggerPrePersistListeners ->method('dispatchEvent') ->with( self::anything(), - self::callback(function (LifecycleEventArgs $args) use ($entity, $generatedFieldValue) { - /* @var $object EntityWithRandomlyGeneratedField */ + self::callback(static function (LifecycleEventArgs $args) use ($entity, $generatedFieldValue) { $object = $args->getObject(); + assert($object instanceof EntityWithRandomlyGeneratedField); self::assertInstanceOf(EntityWithRandomlyGeneratedField::class, $object); self::assertNotSame($entity, $object); @@ -616,8 +612,8 @@ public function testMergeWithNewEntityWillPersistItAndTriggerPrePersistListeners }) ); - /* @var $object EntityWithRandomlyGeneratedField */ $object = $this->_unitOfWork->merge($entity); + assert($object instanceof EntityWithRandomlyGeneratedField); self::assertNotSame($object, $entity); self::assertInstanceOf(EntityWithRandomlyGeneratedField::class, $object); @@ -629,12 +625,12 @@ public function testMergeWithNewEntityWillPersistItAndTriggerPrePersistListeners * @group 5570 * @group 6174 */ - public function testMergeWithExistingEntityWillNotPersistItNorTriggerPrePersistListeners() + public function testMergeWithExistingEntityWillNotPersistItNorTriggerPrePersistListeners(): void { $persistedEntity = new EntityWithRandomlyGeneratedField(); $mergedEntity = new EntityWithRandomlyGeneratedField(); - $mergedEntity->id = $persistedEntity->id; + $mergedEntity->id = $persistedEntity->id; $mergedEntity->generatedField = random_int( $persistedEntity->generatedField + 1, $persistedEntity->generatedField + 1000 @@ -644,7 +640,7 @@ public function testMergeWithExistingEntityWillNotPersistItNorTriggerPrePersistL ->eventManager ->expects(self::any()) ->method('hasListeners') - ->willReturnCallback(function ($eventName) { + ->willReturnCallback(static function ($eventName) { return $eventName === Events::prePersist; }); $this->eventManager->expects(self::never())->method('dispatchEvent'); @@ -655,8 +651,8 @@ public function testMergeWithExistingEntityWillNotPersistItNorTriggerPrePersistL ['generatedField' => $persistedEntity->generatedField] ); - /* @var $merged EntityWithRandomlyGeneratedField */ $merged = $this->_unitOfWork->merge($mergedEntity); + assert($merged instanceof EntityWithRandomlyGeneratedField); self::assertSame($merged, $persistedEntity); self::assertSame($persistedEntity->generatedField, $mergedEntity->generatedField); @@ -669,7 +665,7 @@ public function testMergeWithExistingEntityWillNotPersistItNorTriggerPrePersistL * @group DDC-2922 * @group #1521 */ - public function testNewAssociatedEntityPersistenceOfNewEntitiesThroughCascadedAssociationsFirst() + public function testNewAssociatedEntityPersistenceOfNewEntitiesThroughCascadedAssociationsFirst(): void { $persister1 = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(CascadePersistedEntity::class)); $persister2 = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(EntityWithCascadingAssociation::class)); @@ -686,7 +682,7 @@ public function testNewAssociatedEntityPersistenceOfNewEntitiesThroughCascadedAs // the cascading association not set. Having the "cascading path" involve // a non-new object is important to show that the ORM should be considering // cascades across entity changesets in subsequent flushes. - $cascading->cascaded = $cascadePersisted; + $cascading->cascaded = $cascadePersisted; $nonCascading->cascaded = $cascadePersisted; $this->_unitOfWork->persist($cascading); @@ -706,7 +702,7 @@ public function testNewAssociatedEntityPersistenceOfNewEntitiesThroughCascadedAs * @group DDC-2922 * @group #1521 */ - public function testNewAssociatedEntityPersistenceOfNewEntitiesThroughNonCascadedAssociationsFirst() + public function testNewAssociatedEntityPersistenceOfNewEntitiesThroughNonCascadedAssociationsFirst(): void { $persister1 = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(CascadePersistedEntity::class)); $persister2 = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(EntityWithCascadingAssociation::class)); @@ -750,7 +746,6 @@ public function testNewAssociatedEntityPersistenceOfNewEntitiesThroughNonCascade self::assertCount(1, $persister3->getInserts()); } - /** * This test exhibits the bug describe in the ticket, where an object that * ought to be reachable causes errors. @@ -758,7 +753,7 @@ public function testNewAssociatedEntityPersistenceOfNewEntitiesThroughNonCascade * @group DDC-2922 * @group #1521 */ - public function testPreviousDetectedIllegalNewNonCascadedEntitiesAreCleanedUpOnSubsequentCommits() + public function testPreviousDetectedIllegalNewNonCascadedEntitiesAreCleanedUpOnSubsequentCommits(): void { $persister1 = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(CascadePersistedEntity::class)); $persister2 = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(EntityWithNonCascadingAssociation::class)); @@ -794,7 +789,7 @@ public function testPreviousDetectedIllegalNewNonCascadedEntitiesAreCleanedUpOnS /** * @group #7946 Throw OptimisticLockException when connection::commit() returns false. */ - public function testCommitThrowOptimisticLockExceptionWhenConnectionCommitReturnFalse() : void + public function testCommitThrowOptimisticLockExceptionWhenConnectionCommitReturnFalse(): void { // Set another connection mock that fail on commit $this->_connectionMock = $this->getMockBuilder(ConnectionMock::class) @@ -834,9 +829,7 @@ class NotifyChangedEntity implements NotifyPropertyChanged * @GeneratedValue */ private $id; - /** - * @Column(type="string") - */ + /** @Column(type="string") */ private $data; private $transient; // not persisted @@ -844,42 +837,49 @@ class NotifyChangedEntity implements NotifyPropertyChanged /** @OneToMany(targetEntity="NotifyChangedRelatedItem", mappedBy="owner") */ private $items; - public function __construct() { - $this->items = new ArrayCollection; + public function __construct() + { + $this->items = new ArrayCollection(); } - public function getId() { + public function getId() + { return $this->id; } - public function getItems() { + public function getItems() + { return $this->items; } - public function setTransient($value) { - if ($value != $this->transient) { + public function setTransient($value): void + { + if ($value !== $this->transient) { $this->_onPropertyChanged('transient', $this->transient, $value); $this->transient = $value; } } - public function getData() { + public function getData() + { return $this->data; } - public function setData($data) { - if ($data != $this->data) { + public function setData($data): void + { + if ($data !== $this->data) { $this->_onPropertyChanged('data', $this->data, $data); $this->data = $data; } } - public function addPropertyChangedListener(PropertyChangedListener $listener) + public function addPropertyChangedListener(PropertyChangedListener $listener): void { $this->_listeners[] = $listener; } - protected function _onPropertyChanged($propName, $oldValue, $newValue) { + protected function _onPropertyChanged($propName, $oldValue, $newValue): void + { if ($this->_listeners) { foreach ($this->_listeners as $listener) { $listener->propertyChanged($this, $propName, $oldValue, $newValue); @@ -901,15 +901,18 @@ class NotifyChangedRelatedItem /** @ManyToOne(targetEntity="NotifyChangedEntity", inversedBy="items") */ private $owner; - public function getId() { + public function getId() + { return $this->id; } - public function getOwner() { + public function getOwner() + { return $this->owner; } - public function setOwner($owner) { + public function setOwner($owner): void + { $this->owner = $owner; } } @@ -917,13 +920,9 @@ public function setOwner($owner) { /** @Entity */ class VersionedAssignedIdentifierEntity { - /** - * @Id @Column(type="integer") - */ + /** @Id @Column(type="integer") */ public $id; - /** - * @Version @Column(type="integer") - */ + /** @Version @Column(type="integer") */ public $version; } @@ -932,7 +931,6 @@ class EntityWithStringIdentifier { /** * @Id @Column(type="string") - * * @var string|null */ public $id; @@ -943,7 +941,6 @@ class EntityWithBooleanIdentifier { /** * @Id @Column(type="boolean") - * * @var bool|null */ public $id; @@ -954,14 +951,12 @@ class EntityWithCompositeStringIdentifier { /** * @Id @Column(type="string") - * * @var string|null */ public $id1; /** * @Id @Column(type="string") - * * @var string|null */ public $id2; @@ -973,9 +968,7 @@ class EntityWithRandomlyGeneratedField /** @Id @Column(type="string") */ public $id; - /** - * @Column(type="integer") - */ + /** @Column(type="integer") */ public $generatedField; public function __construct() diff --git a/tests/Doctrine/Tests/ORM/Utility/HierarchyDiscriminatorResolverTest.php b/tests/Doctrine/Tests/ORM/Utility/HierarchyDiscriminatorResolverTest.php index cffb8cd3b33..a47234fe153 100644 --- a/tests/Doctrine/Tests/ORM/Utility/HierarchyDiscriminatorResolverTest.php +++ b/tests/Doctrine/Tests/ORM/Utility/HierarchyDiscriminatorResolverTest.php @@ -1,24 +1,25 @@ name = 'Some\Class\Child\Name'; + $childClassMetadata = new ClassMetadata('ChildEntity'); + $childClassMetadata->name = 'Some\Class\Child\Name'; $childClassMetadata->discriminatorValue = 'child-discriminator'; - - $classMetadata = new ClassMetadata('Entity'); - $classMetadata->subClasses = [$childClassMetadata->name]; - $classMetadata->name = 'Some\Class\Name'; + + $classMetadata = new ClassMetadata('Entity'); + $classMetadata->subClasses = [$childClassMetadata->name]; + $classMetadata->name = 'Some\Class\Name'; $classMetadata->discriminatorValue = 'discriminator'; $em = $this->prophesize(EntityManagerInterface::class); @@ -30,17 +31,17 @@ public function testResolveDiscriminatorsForClass() ->willReturn($childClassMetadata); $discriminators = HierarchyDiscriminatorResolver::resolveDiscriminatorsForClass($classMetadata, $em->reveal()); - + $this->assertCount(2, $discriminators); $this->assertArrayHasKey($classMetadata->discriminatorValue, $discriminators); $this->assertArrayHasKey($childClassMetadata->discriminatorValue, $discriminators); } - public function testResolveDiscriminatorsForClassWithNoSubclasses() + public function testResolveDiscriminatorsForClassWithNoSubclasses(): void { - $classMetadata = new ClassMetadata('Entity'); - $classMetadata->subClasses = []; - $classMetadata->name = 'Some\Class\Name'; + $classMetadata = new ClassMetadata('Entity'); + $classMetadata->subClasses = []; + $classMetadata->name = 'Some\Class\Name'; $classMetadata->discriminatorValue = 'discriminator'; $em = $this->prophesize(EntityManagerInterface::class); @@ -49,7 +50,7 @@ public function testResolveDiscriminatorsForClassWithNoSubclasses() ->willReturn($classMetadata); $discriminators = HierarchyDiscriminatorResolver::resolveDiscriminatorsForClass($classMetadata, $em->reveal()); - + $this->assertCount(1, $discriminators); $this->assertArrayHasKey($classMetadata->discriminatorValue, $discriminators); } diff --git a/tests/Doctrine/Tests/ORM/Utility/IdentifierFlattenerTest.php b/tests/Doctrine/Tests/ORM/Utility/IdentifierFlattenerTest.php index a1ceccfdabd..45795af401d 100644 --- a/tests/Doctrine/Tests/ORM/Utility/IdentifierFlattenerTest.php +++ b/tests/Doctrine/Tests/ORM/Utility/IdentifierFlattenerTest.php @@ -1,19 +1,20 @@ * @covers \Doctrine\ORM\Utility\IdentifierFlattener */ class IdentifierFlattenerTest extends OrmFunctionalTestCase @@ -21,11 +22,11 @@ class IdentifierFlattenerTest extends OrmFunctionalTestCase /** * Identifier flattener * - * @var \Doctrine\ORM\Utility\IdentifierFlattener + * @var IdentifierFlattener */ private $identifierFlattener; - protected function setUp() : void + protected function setUp(): void { parent::setUp(); @@ -40,7 +41,7 @@ protected function setUp() : void $this->_em->getClassMetadata(FirstRelatedEntity::class), $this->_em->getClassMetadata(SecondRelatedEntity::class), $this->_em->getClassMetadata(Flight::class), - $this->_em->getClassMetadata(City::class) + $this->_em->getClassMetadata(City::class), ] ); } catch (ORMException $e) { @@ -50,16 +51,16 @@ protected function setUp() : void /** * @group utilities */ - public function testFlattenIdentifierWithOneToOneId() + public function testFlattenIdentifierWithOneToOneId(): void { - $secondRelatedEntity = new SecondRelatedEntity(); + $secondRelatedEntity = new SecondRelatedEntity(); $secondRelatedEntity->name = 'Bob'; $this->_em->persist($secondRelatedEntity); $this->_em->flush(); - $firstRelatedEntity = new FirstRelatedEntity(); - $firstRelatedEntity->name = 'Fred'; + $firstRelatedEntity = new FirstRelatedEntity(); + $firstRelatedEntity->name = 'Fred'; $firstRelatedEntity->secondEntity = $secondRelatedEntity; $this->_em->persist($firstRelatedEntity); @@ -94,9 +95,9 @@ public function testFlattenIdentifierWithOneToOneId() /** * @group utilities */ - public function testFlattenIdentifierWithMutlipleIds() + public function testFlattenIdentifierWithMutlipleIds(): void { - $leeds = new City('Leeds'); + $leeds = new City('Leeds'); $london = new City('London'); $this->_em->persist($leeds); @@ -109,7 +110,7 @@ public function testFlattenIdentifierWithMutlipleIds() $this->_em->flush(); $class = $this->_em->getClassMetadata(Flight::class); - $id = $class->getIdentifierValues($flight); + $id = $class->getIdentifierValues($flight); $this->assertCount(2, $id); diff --git a/tests/Doctrine/Tests/OrmFunctionalTestCase.php b/tests/Doctrine/Tests/OrmFunctionalTestCase.php index 2ca95f52a82..fa7326c9f97 100644 --- a/tests/Doctrine/Tests/OrmFunctionalTestCase.php +++ b/tests/Doctrine/Tests/OrmFunctionalTestCase.php @@ -1,8 +1,11 @@ [ Models\Generic\BooleanModel::class, @@ -216,7 +232,7 @@ abstract class OrmFunctionalTestCase extends OrmTestCase Models\Cache\ComplexAction::class, Models\Cache\AttractionInfo::class, Models\Cache\AttractionContactInfo::class, - Models\Cache\AttractionLocationInfo::class + Models\Cache\AttractionLocationInfo::class, ], 'tweet' => [ Models\Tweet\User::class, @@ -239,60 +255,60 @@ abstract class OrmFunctionalTestCase extends OrmTestCase Models\Quote\Group::class, Models\Quote\NumericEntity::class, Models\Quote\Phone::class, - Models\Quote\User::class + Models\Quote\User::class, ], 'vct_onetoone' => [ Models\ValueConversionType\InversedOneToOneEntity::class, - Models\ValueConversionType\OwningOneToOneEntity::class + Models\ValueConversionType\OwningOneToOneEntity::class, ], 'vct_onetoone_compositeid' => [ Models\ValueConversionType\InversedOneToOneCompositeIdEntity::class, - Models\ValueConversionType\OwningOneToOneCompositeIdEntity::class + Models\ValueConversionType\OwningOneToOneCompositeIdEntity::class, ], 'vct_onetoone_compositeid_foreignkey' => [ Models\ValueConversionType\AuxiliaryEntity::class, Models\ValueConversionType\InversedOneToOneCompositeIdForeignKeyEntity::class, - Models\ValueConversionType\OwningOneToOneCompositeIdForeignKeyEntity::class + Models\ValueConversionType\OwningOneToOneCompositeIdForeignKeyEntity::class, ], 'vct_onetomany' => [ Models\ValueConversionType\InversedOneToManyEntity::class, - Models\ValueConversionType\OwningManyToOneEntity::class + Models\ValueConversionType\OwningManyToOneEntity::class, ], 'vct_onetomany_compositeid' => [ Models\ValueConversionType\InversedOneToManyCompositeIdEntity::class, - Models\ValueConversionType\OwningManyToOneCompositeIdEntity::class + Models\ValueConversionType\OwningManyToOneCompositeIdEntity::class, ], 'vct_onetomany_compositeid_foreignkey' => [ Models\ValueConversionType\AuxiliaryEntity::class, Models\ValueConversionType\InversedOneToManyCompositeIdForeignKeyEntity::class, - Models\ValueConversionType\OwningManyToOneCompositeIdForeignKeyEntity::class + Models\ValueConversionType\OwningManyToOneCompositeIdForeignKeyEntity::class, ], 'vct_onetomany_extralazy' => [ Models\ValueConversionType\InversedOneToManyExtraLazyEntity::class, - Models\ValueConversionType\OwningManyToOneExtraLazyEntity::class + Models\ValueConversionType\OwningManyToOneExtraLazyEntity::class, ], 'vct_manytomany' => [ Models\ValueConversionType\InversedManyToManyEntity::class, - Models\ValueConversionType\OwningManyToManyEntity::class + Models\ValueConversionType\OwningManyToManyEntity::class, ], 'vct_manytomany_compositeid' => [ Models\ValueConversionType\InversedManyToManyCompositeIdEntity::class, - Models\ValueConversionType\OwningManyToManyCompositeIdEntity::class + Models\ValueConversionType\OwningManyToManyCompositeIdEntity::class, ], 'vct_manytomany_compositeid_foreignkey' => [ Models\ValueConversionType\AuxiliaryEntity::class, Models\ValueConversionType\InversedManyToManyCompositeIdForeignKeyEntity::class, - Models\ValueConversionType\OwningManyToManyCompositeIdForeignKeyEntity::class + Models\ValueConversionType\OwningManyToManyCompositeIdForeignKeyEntity::class, ], 'vct_manytomany_extralazy' => [ Models\ValueConversionType\InversedManyToManyExtraLazyEntity::class, - Models\ValueConversionType\OwningManyToManyExtraLazyEntity::class + Models\ValueConversionType\OwningManyToManyExtraLazyEntity::class, ], 'geonames' => [ Models\GeoNames\Country::class, Models\GeoNames\Admin1::class, Models\GeoNames\Admin1AlternateName::class, - Models\GeoNames\City::class + Models\GeoNames\City::class, ], 'custom_id_object_type' => [ Models\CustomType\CustomIdObjectTypeParent::class, @@ -316,27 +332,20 @@ abstract class OrmFunctionalTestCase extends OrmTestCase ], ]; - /** - * @param string $setName - * - * @return void - */ - protected function useModelSet($setName) + protected function useModelSet(string $setName): void { $this->_usedModelSets[$setName] = true; } /** * Sweeps the database tables and clears the EntityManager. - * - * @return void */ - protected function tearDown() : void + protected function tearDown(): void { $conn = static::$_sharedConn; // In case test is skipped, tearDown is called, but no setup may have run - if ( ! $conn) { + if (! $conn) { return; } @@ -403,19 +412,21 @@ protected function tearDown() : void $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'])) { - $conn->executeUpdate('DELETE FROM ' . $platform->quoteIdentifier("file")); + $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'])) { $conn->executeUpdate('DELETE FROM ddc117editor_ddc117translation'); $conn->executeUpdate('DELETE FROM DDC117Editor'); @@ -426,12 +437,14 @@ protected function tearDown() : void $conn->executeUpdate('DELETE FROM DDC117Translation'); $conn->executeUpdate('DELETE FROM DDC117Article'); } + 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'])) { $conn->executeUpdate('DELETE FROM legacy_users_cars'); $conn->executeUpdate('DELETE FROM legacy_users_reference'); @@ -501,7 +514,7 @@ protected function tearDown() : void $conn->executeUpdate( sprintf( 'UPDATE %s SET %s = NULL', - $platform->quoteIdentifier("quote-address"), + $platform->quoteIdentifier('quote-address'), $platform->quoteIdentifier('user-id') ) ); @@ -575,6 +588,7 @@ protected function tearDown() : void $conn->executeUpdate('DELETE FROM vct_owning_manytomany_extralazy'); $conn->executeUpdate('DELETE FROM vct_inversed_manytomany_extralazy'); } + if (isset($this->_usedModelSets['geonames'])) { $conn->executeUpdate('DELETE FROM geonames_admin1_alternate_name'); $conn->executeUpdate('DELETE FROM geonames_admin1'); @@ -611,21 +625,19 @@ protected function tearDown() : void /** * @param array $classNames * - * @return void - * - * @throws \RuntimeException + * @throws RuntimeException */ - protected function setUpEntitySchema(array $classNames) + protected function setUpEntitySchema(array $classNames): void { if ($this->_em === null) { - throw new \RuntimeException("EntityManager not set, you have to call parent::setUp() before invoking this method."); + 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])) { + if (! isset(static::$_entityTablesCreated[$className])) { static::$_entityTablesCreated[$className] = true; - $classes[] = $this->_em->getClassMetadata($className); + $classes[] = $this->_em->getClassMetadata($className); } } @@ -637,34 +649,32 @@ protected function setUpEntitySchema(array $classNames) /** * Creates a connection to the test database, if there is none yet, and * creates the necessary tables. - * - * @return void */ - protected function setUp() : void + protected function setUp(): void { $this->setUpDBALTypes(); - if ( ! isset(static::$_sharedConn)) { + 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 /*' . static::class . '*/'); + } elseif (static::$_sharedConn->getDatabasePlatform()->getName() === 'oracle') { + static::$_sharedConn->executeQuery('SELECT 1 /*' . static::class . '*/ FROM dual'); } } - if ( ! $this->_em) { - $this->_em = $this->_getEntityManager(); + 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])) { + if (! isset(static::$_tablesCreated[$setName])) { foreach (static::$_modelSets[$setName] as $className) { $classes[] = $this->_em->getClassMetadata($className); } @@ -683,20 +693,18 @@ protected function setUp() : void /** * Gets an EntityManager for testing purposes. * - * @return EntityManager - * - * @throws \Doctrine\ORM\ORMException + * @throws ORMException */ protected function _getEntityManager( - Connection $connection = null, - MappingDriver $mappingDriver = null - ) { + ?Connection $connection = null, + ?MappingDriver $mappingDriver = null + ): EntityManager { // 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 (isset($GLOBALS['DOCTRINE_CACHE_IMPL'])) { - self::$_metadataCacheImpl = new $GLOBALS['DOCTRINE_CACHE_IMPL']; + self::$_metadataCacheImpl = new $GLOBALS['DOCTRINE_CACHE_IMPL'](); } else { self::$_metadataCacheImpl = new ArrayCache(); } @@ -706,7 +714,7 @@ protected function _getEntityManager( self::$_queryCacheImpl = new ArrayCache(); } - $this->_sqlLoggerStack = new DebugStack(); + $this->_sqlLoggerStack = new DebugStack(); $this->_sqlLoggerStack->enabled = false; //FIXME: two different configs! $conn and the created entity manager have @@ -717,17 +725,16 @@ protected function _getEntityManager( $config->setProxyDir(__DIR__ . '/Proxies'); $config->setProxyNamespace('Doctrine\Tests\Proxies'); - if (null !== $this->resultCacheImpl) { + if ($this->resultCacheImpl !== null) { $config->setResultCacheImpl($this->resultCacheImpl); } $enableSecondLevelCache = getenv('ENABLE_SECOND_LEVEL_CACHE'); if ($this->isSecondLevelCacheEnabled || $enableSecondLevelCache) { - - $cacheConfig = new CacheConfiguration(); - $cache = $this->getSharedSecondLevelCacheDriverImpl(); - $factory = new DefaultCacheFactory($cacheConfig->getRegionsConfiguration(), $cache); + $cacheConfig = new CacheConfiguration(); + $cache = $this->getSharedSecondLevelCacheDriverImpl(); + $factory = new DefaultCacheFactory($cacheConfig->getRegionsConfiguration(), $cache); $this->secondLevelCacheFactory = $factory; @@ -747,7 +754,7 @@ protected function _getEntityManager( $mappingDriver ?? $config->newDefaultAnnotationDriver( [ realpath(__DIR__ . '/Models/Cache'), - realpath(__DIR__ . '/Models/GeoNames') + realpath(__DIR__ . '/Models/GeoNames'), ], true ) @@ -758,8 +765,8 @@ protected function _getEntityManager( // get rid of more global state $evm = $conn->getEventManager(); - foreach ($evm->getListeners() AS $event => $listeners) { - foreach ($listeners AS $listener) { + foreach ($evm->getListeners() as $event => $listeners) { + foreach ($listeners as $listener) { $evm->removeEventListener([$event], $listener); } } @@ -769,7 +776,7 @@ protected function _getEntityManager( } if (isset($GLOBALS['db_event_subscribers'])) { - foreach (explode(",", $GLOBALS['db_event_subscribers']) AS $subscriberClass) { + foreach (explode(',', $GLOBALS['db_event_subscribers']) as $subscriberClass) { $subscriberInstance = new $subscriberClass(); $evm->addEventSubscriber($subscriberInstance); } @@ -783,54 +790,58 @@ protected function _getEntityManager( } /** - * @throws \Throwable + * @throws Throwable */ - protected function onNotSuccessfulTest(Throwable $e) : void + protected function onNotSuccessfulTest(Throwable $e): void { if ($e instanceof AssertionFailedError || $e instanceof Warning) { throw $e; } - if(isset($this->_sqlLoggerStack->queries) && count($this->_sqlLoggerStack->queries)) { - $queries = ""; + if (isset($this->_sqlLoggerStack->queries) && count($this->_sqlLoggerStack->queries)) { + $queries = ''; $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'] ?: [] - ); - $queries .= $i.". SQL: '".$query['sql']."' Params: ".implode(", ", $params).PHP_EOL; + $params = array_map(static 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) { + $trace = $e->getTrace(); + $traceMsg = ''; + foreach ($trace as $part) { + if (isset($part['file'])) { + if (strpos($part['file'], 'PHPUnit/') !== false) { // Beginning with PHPUnit files we don't print the trace anymore. break; } - $traceMsg .= $part['file'].":".$part['line'].PHP_EOL; + $traceMsg .= $part['file'] . ':' . $part['line'] . PHP_EOL; } } - $message = "[".get_class($e)."] ".$e->getMessage().PHP_EOL.PHP_EOL."With queries:".PHP_EOL.$queries.PHP_EOL."Trace:".PHP_EOL.$traceMsg; + $message = '[' . get_class($e) . '] ' . $e->getMessage() . PHP_EOL . PHP_EOL . 'With queries:' . PHP_EOL . $queries . PHP_EOL . 'Trace:' . PHP_EOL . $traceMsg; - throw new \Exception($message, (int)$e->getCode(), $e); + throw new Exception($message, (int) $e->getCode(), $e); } + throw $e; } public function assertSQLEquals($expectedSql, $actualSql) { - return $this->assertEquals(strtolower($expectedSql), strtolower($actualSql), "Lowercase comparison of SQL statements failed."); + return $this->assertEquals(strtolower($expectedSql), strtolower($actualSql), 'Lowercase comparison of SQL statements failed.'); } /** * Using the SQL Logger Stack this method retrieves the current query count executed in this test. - * - * @return int */ - protected function getCurrentQueryCount() + protected function getCurrentQueryCount(): int { return count($this->_sqlLoggerStack->queries); } @@ -838,7 +849,7 @@ protected function getCurrentQueryCount() /** * Configures DBAL types required in tests */ - protected function setUpDBALTypes() + protected function setUpDBALTypes(): void { if (Type::hasType('rot13')) { Type::overrideType('rot13', Rot13Type::class); diff --git a/tests/Doctrine/Tests/OrmPerformanceTestCase.php b/tests/Doctrine/Tests/OrmPerformanceTestCase.php index b58390ac909..d1d9644c15e 100644 --- a/tests/Doctrine/Tests/OrmPerformanceTestCase.php +++ b/tests/Doctrine/Tests/OrmPerformanceTestCase.php @@ -1,64 +1,53 @@ maxRunningTime != 0 && $time > $this->maxRunningTime) { + if ($this->maxRunningTime !== 0 && $time > $this->maxRunningTime) { $this->fail( - sprintf( - 'expected running time: <= %s but was: %s', - - $this->maxRunningTime, - $time - ) + sprintf( + 'expected running time: <= %s but was: %s', + $this->maxRunningTime, + $time + ) ); } } /** - * @param integer $maxRunningTime - * - * @return void - * - * @throws \InvalidArgumentException - * - * @since Method available since Release 2.3.0 + * @throws InvalidArgumentException */ - public function setMaxRunningTime($maxRunningTime) + public function setMaxRunningTime(int $maxRunningTime): void { if (is_integer($maxRunningTime) && $maxRunningTime >= 0) { $this->maxRunningTime = $maxRunningTime; } else { - throw new \InvalidArgumentException; + throw new InvalidArgumentException(); } } - /** - * @return int - * - * @since Method available since Release 2.3.0 - */ - public function getMaxRunningTime() + public function getMaxRunningTime(): int { return $this->maxRunningTime; } diff --git a/tests/Doctrine/Tests/OrmTestCase.php b/tests/Doctrine/Tests/OrmTestCase.php index 1de2b2ac620..7dfce2feecd 100644 --- a/tests/Doctrine/Tests/OrmTestCase.php +++ b/tests/Doctrine/Tests/OrmTestCase.php @@ -1,17 +1,26 @@ setProxyNamespace('Doctrine\Tests\Proxies'); $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver( [ - realpath(__DIR__ . '/Models/Cache') - ], true)); + realpath(__DIR__ . '/Models/Cache'), + ], + true + )); if ($this->isSecondLevelCacheEnabled) { - - $cacheConfig = new CacheConfiguration(); - $cache = $this->getSharedSecondLevelCacheDriverImpl(); - $factory = new DefaultCacheFactory($cacheConfig->getRegionsConfiguration(), $cache); + $cacheConfig = new CacheConfiguration(); + $cache = $this->getSharedSecondLevelCacheDriverImpl(); + $factory = new DefaultCacheFactory($cacheConfig->getRegionsConfiguration(), $cache); $this->secondLevelCacheFactory = $factory; @@ -125,7 +121,7 @@ protected function _getTestEntityManager($conn = null, $conf = null, $eventManag 'driverClass' => Mocks\DriverMock::class, 'wrapperClass' => Mocks\ConnectionMock::class, 'user' => 'john', - 'password' => 'wayne' + 'password' => 'wayne', ]; } @@ -136,16 +132,13 @@ protected function _getTestEntityManager($conn = null, $conf = null, $eventManag return EntityManagerMock::create($conn, $config, $eventManager); } - protected function enableSecondLevelCache($log = true) + protected function enableSecondLevelCache($log = true): void { $this->isSecondLevelCacheEnabled = true; $this->isSecondLevelCacheLogEnabled = $log; } - /** - * @return \Doctrine\Common\Cache\Cache - */ - private static function getSharedMetadataCacheImpl() + private static function getSharedMetadataCacheImpl(): Cache { if (self::$_metadataCacheImpl === null) { self::$_metadataCacheImpl = new ArrayCache(); @@ -154,10 +147,7 @@ private static function getSharedMetadataCacheImpl() return self::$_metadataCacheImpl; } - /** - * @return \Doctrine\Common\Cache\Cache - */ - private static function getSharedQueryCacheImpl() + private static function getSharedQueryCacheImpl(): Cache { if (self::$_queryCacheImpl === null) { self::$_queryCacheImpl = new ArrayCache(); @@ -166,10 +156,7 @@ private static function getSharedQueryCacheImpl() return self::$_queryCacheImpl; } - /** - * @return \Doctrine\Common\Cache\Cache - */ - protected function getSharedSecondLevelCacheDriverImpl() + protected function getSharedSecondLevelCacheDriverImpl(): Cache { if ($this->secondLevelCacheDriverImpl === null) { $this->secondLevelCacheDriverImpl = new ArrayCache(); diff --git a/tests/Doctrine/Tests/TestInit.php b/tests/Doctrine/Tests/TestInit.php index 1474bab4eb8..2cfe1761b0d 100644 --- a/tests/Doctrine/Tests/TestInit.php +++ b/tests/Doctrine/Tests/TestInit.php @@ -1,9 +1,23 @@ getDatabasePlatform(); + $platform = $tmpConn->getDatabasePlatform(); if ($platform->supportsCreateDropDatabase()) { $dbname = $realConn->getDatabase(); @@ -110,7 +108,7 @@ private static function getSpecifiedConnectionParams() $sm = $realConn->getSchemaManager(); $schema = $sm->createSchema(); - $stmts = $schema->toDropSql($realConn->getDatabasePlatform()); + $stmts = $schema->toDropSql($realConn->getDatabasePlatform()); foreach ($stmts as $stmt) { $realConn->exec($stmt); @@ -127,7 +125,7 @@ private static function getFallbackConnectionParams() { $params = [ 'driver' => 'pdo_sqlite', - 'memory' => true + 'memory' => true, ]; if (isset($GLOBALS['db_path'])) { @@ -138,11 +136,11 @@ private static function getFallbackConnectionParams() return $params; } - private static function addDbEventSubscribers(Connection $conn) + private static function addDbEventSubscribers(Connection $conn): void { if (isset($GLOBALS['db_event_subscribers'])) { $evm = $conn->getEventManager(); - foreach (explode(",", $GLOBALS['db_event_subscribers']) as $subscriberClass) { + foreach (explode(',', $GLOBALS['db_event_subscribers']) as $subscriberClass) { $subscriberInstance = new $subscriberClass(); $evm->addEventSubscriber($subscriberInstance); } @@ -157,7 +155,7 @@ private static function getParamsForTemporaryConnection() 'password' => $GLOBALS['tmpdb_password'], 'host' => $GLOBALS['tmpdb_host'], 'dbname' => null, - 'port' => $GLOBALS['tmpdb_port'] + 'port' => $GLOBALS['tmpdb_port'], ]; if (isset($GLOBALS['tmpdb_name'])) { @@ -183,7 +181,7 @@ private static function getParamsForMainConnection() 'password' => $GLOBALS['db_password'], 'host' => $GLOBALS['db_host'], 'dbname' => $GLOBALS['db_name'], - 'port' => $GLOBALS['db_port'] + 'port' => $GLOBALS['db_port'], ]; if (isset($GLOBALS['db_server'])) { diff --git a/tests/Doctrine/Tests/VerifyDeprecations.php b/tests/Doctrine/Tests/VerifyDeprecations.php index 9404af22d08..17b57bc3175 100644 --- a/tests/Doctrine/Tests/VerifyDeprecations.php +++ b/tests/Doctrine/Tests/VerifyDeprecations.php @@ -4,10 +4,11 @@ namespace Doctrine\Tests; -use const E_USER_DEPRECATED; use function in_array; use function set_error_handler; +use const E_USER_DEPRECATED; + trait VerifyDeprecations { /** @var string[] */ @@ -23,14 +24,14 @@ trait VerifyDeprecations private $originalHandler; /** @before */ - public function resetDeprecations() : void + public function resetDeprecations(): void { $this->actualDeprecations = []; $this->expectedDeprecations = []; $this->ignoredDeprecations = []; $this->originalHandler = set_error_handler( - function (int $errorNumber, string $errorMessage) : void { + function (int $errorNumber, string $errorMessage): void { if (in_array($errorMessage, $this->ignoredDeprecations, true)) { return; } @@ -42,14 +43,14 @@ function (int $errorNumber, string $errorMessage) : void { } /** @after */ - public function resetErrorHandler() : void + public function resetErrorHandler(): void { set_error_handler($this->originalHandler, E_USER_DEPRECATED); $this->originalHandler = null; } /** @after */ - public function validateDeprecationExpectations() : void + public function validateDeprecationExpectations(): void { if ($this->expectedDeprecations === []) { return; @@ -62,22 +63,22 @@ public function validateDeprecationExpectations() : void ); } - protected function ignoreDeprecationMessage(string $message) : void + protected function ignoreDeprecationMessage(string $message): void { $this->ignoredDeprecations[] = $message; } - protected function expectDeprecationMessageSame(string $message) : void + protected function expectDeprecationMessageSame(string $message): void { $this->expectedDeprecations[] = $message; } - protected function assertHasDeprecationMessages() : void + protected function assertHasDeprecationMessages(): void { self::assertNotSame([], $this->actualDeprecations, 'Failed asserting that test has triggered deprecation messages.'); } - protected function assertNotHasDeprecationMessages() : void + protected function assertNotHasDeprecationMessages(): void { self::assertSame([], $this->actualDeprecations, 'Failed asserting that test has not triggered deprecation messages.'); } diff --git a/tools/sandbox/Entities/Address.php b/tools/sandbox/Entities/Address.php index 0dda78f9536..72cf6c3fa32 100644 --- a/tools/sandbox/Entities/Address.php +++ b/tools/sandbox/Entities/Address.php @@ -1,5 +1,7 @@ street; } - public function setStreet($street) + public function setStreet($street): void { $this->street = $street; } @@ -35,7 +37,7 @@ public function getUser() return $this->user; } - public function setUser(User $user) + public function setUser(User $user): void { if ($this->user !== $user) { $this->user = $user; diff --git a/tools/sandbox/Entities/User.php b/tools/sandbox/Entities/User.php index 394686c8465..2874ccee44b 100644 --- a/tools/sandbox/Entities/User.php +++ b/tools/sandbox/Entities/User.php @@ -1,5 +1,7 @@ name; } - public function setName($name) + public function setName($name): void { $this->name = $name; } @@ -38,7 +40,7 @@ public function getAddress() return $this->address; } - public function setAddress(Address $address) + public function setAddress(Address $address): void { if ($this->address !== $address) { $this->address = $address; diff --git a/tools/sandbox/bootstrap.php b/tools/sandbox/bootstrap.php index 410ea7f72e3..a945fb705dd 100644 --- a/tools/sandbox/bootstrap.php +++ b/tools/sandbox/bootstrap.php @@ -1,30 +1,37 @@ add('Entities', __DIR__); $loader->add('Proxies', __DIR__); -$debug = true; -$config = new \Doctrine\ORM\Configuration(); +$debug = true; +$config = new Configuration(); // Set up Metadata Drivers -$driverImpl = $config->newDefaultAnnotationDriver([__DIR__ . "/Entities"]); +$driverImpl = $config->newDefaultAnnotationDriver([__DIR__ . '/Entities']); $config->setMetadataDriverImpl($driverImpl); // Set up caches, depending on $debug variable. // You can use another variable to define which one of the cache systems you gonna use. -$cache = $debug ? new Cache\ArrayCache : new Cache\ApcCache; +$cache = $debug ? new Cache\ArrayCache() : new Cache\ApcCache(); $config->setMetadataCacheImpl($cache); $config->setQueryCacheImpl($cache); @@ -35,14 +42,14 @@ // Database connection information $connectionOptions = [ 'driver' => 'pdo_sqlite', - 'path' => 'database.sqlite' + 'path' => 'database.sqlite', ]; // Enable second-level cache -$cacheConfig = new \Doctrine\ORM\Cache\CacheConfiguration(); -$cacheDriver = $debug ? new Cache\ArrayCache : new Cache\ApcCache; -$cacheLogger = new \Doctrine\ORM\Cache\Logging\StatisticsCacheLogger(); -$factory = new \Doctrine\ORM\Cache\DefaultCacheFactory($cacheConfig->getRegionsConfiguration(), $cacheDriver); +$cacheConfig = new CacheConfiguration(); +$cacheDriver = $debug ? new Cache\ArrayCache() : new Cache\ApcCache(); +$cacheLogger = new StatisticsCacheLogger(); +$factory = new DefaultCacheFactory($cacheConfig->getRegionsConfiguration(), $cacheDriver); if ($debug) { $cacheConfig->setCacheLogger($cacheLogger); diff --git a/tools/sandbox/doctrine.php b/tools/sandbox/doctrine.php index 8b4af6fe13d..8795464b9bc 100644 --- a/tools/sandbox/doctrine.php +++ b/tools/sandbox/doctrine.php @@ -1,43 +1,66 @@ setCatchExceptions(true); $cli->setHelperSet(new Symfony\Component\Console\Helper\HelperSet( [ - 'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($em->getConnection()), - 'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em) + 'db' => new ConnectionHelper($em->getConnection()), + 'em' => new EntityManagerHelper($em), ] )); $cli->addCommands( [ // DBAL Commands - new \Doctrine\DBAL\Tools\Console\Command\RunSqlCommand(), - new \Doctrine\DBAL\Tools\Console\Command\ImportCommand(), + new RunSqlCommand(), + new ImportCommand(), // ORM Commands - new \Doctrine\ORM\Tools\Console\Command\ClearCache\QueryRegionCommand(), - new \Doctrine\ORM\Tools\Console\Command\ClearCache\EntityRegionCommand(), - new \Doctrine\ORM\Tools\Console\Command\ClearCache\CollectionRegionCommand(), - new \Doctrine\ORM\Tools\Console\Command\ClearCache\MetadataCommand(), - new \Doctrine\ORM\Tools\Console\Command\ClearCache\ResultCommand(), - new \Doctrine\ORM\Tools\Console\Command\ClearCache\QueryCommand(), - new \Doctrine\ORM\Tools\Console\Command\SchemaTool\CreateCommand(), - new \Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand(), - new \Doctrine\ORM\Tools\Console\Command\SchemaTool\DropCommand(), - new \Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand(), - new \Doctrine\ORM\Tools\Console\Command\ConvertDoctrine1SchemaCommand(), - new \Doctrine\ORM\Tools\Console\Command\GenerateRepositoriesCommand(), - new \Doctrine\ORM\Tools\Console\Command\GenerateEntitiesCommand(), - new \Doctrine\ORM\Tools\Console\Command\GenerateProxiesCommand(), - new \Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand(), - new \Doctrine\ORM\Tools\Console\Command\RunDqlCommand(), - new \Doctrine\ORM\Tools\Console\Command\ValidateSchemaCommand(), + new QueryRegionCommand(), + new EntityRegionCommand(), + new CollectionRegionCommand(), + new MetadataCommand(), + new ResultCommand(), + new QueryCommand(), + new CreateCommand(), + new UpdateCommand(), + new DropCommand(), + new EnsureProductionSettingsCommand(), + new ConvertDoctrine1SchemaCommand(), + new GenerateRepositoriesCommand(), + new GenerateEntitiesCommand(), + new GenerateProxiesCommand(), + new ConvertMappingCommand(), + new RunDqlCommand(), + new ValidateSchemaCommand(), ] ); diff --git a/tools/sandbox/index.php b/tools/sandbox/index.php index f866aeadac7..b3fc605dc2b 100644 --- a/tools/sandbox/index.php +++ b/tools/sandbox/index.php @@ -1,4 +1,7 @@ Date: Fri, 29 Jan 2021 21:38:19 +0100 Subject: [PATCH 04/22] Run phpcbf in the CI There are still many CS issues to fix, but with this, we now know people can run vendor/bin/phpcbf to fix their issues and only their issues. --- .github/workflows/coding-standard.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/coding-standard.yml b/.github/workflows/coding-standard.yml index 2066e4d4af6..d3f88e8bb5e 100644 --- a/.github/workflows/coding-standard.yml +++ b/.github/workflows/coding-standard.yml @@ -35,5 +35,8 @@ jobs: - name: "Fetch head branch" run: "git remote set-branches --add origin $GITHUB_BASE_REF && git fetch origin $GITHUB_BASE_REF" + - name: "Run phpcbf" + run: "vendor/bin/phpcbf" + - name: "Run git-phpcs" run: "php git-phpcs.phar origin/$GITHUB_BASE_REF...$GITHUB_SHA --report=checkstyle | cs2pr" From 8991df0785380c79d5ae017a46f3f7d4b52818ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Fri, 29 Jan 2021 21:40:59 +0100 Subject: [PATCH 05/22] Add missing return types --- tests/Doctrine/Tests/Models/Company/CompanyContract.php | 2 +- tests/Doctrine/Tests/Models/Company/CompanyFixContract.php | 2 +- .../Doctrine/Tests/Models/Company/CompanyFlexContract.php | 2 +- .../Tests/Models/Company/CompanyFlexUltraContract.php | 2 +- tests/Doctrine/Tests/ORM/Cache/DefaultRegionTest.php | 2 +- tests/Doctrine/Tests/ORM/Cache/FileLockRegionTest.php | 3 ++- tests/Doctrine/Tests/ORM/Cache/MultiGetRegionTest.php | 2 +- .../NonStrictReadWriteCachedCollectionPersisterTest.php | 2 +- .../Collection/ReadOnlyCachedCollectionPersisterTest.php | 5 +---- .../Collection/ReadWriteCachedCollectionPersisterTest.php | 5 +---- .../Entity/NonStrictReadWriteCachedEntityPersisterTest.php | 5 +---- .../Persister/Entity/ReadOnlyCachedEntityPersisterTest.php | 5 +---- .../Entity/ReadWriteCachedEntityPersisterTest.php | 5 +---- .../Tests/ORM/Functional/ManyToOneOrphanRemovalTest.php | 3 ++- .../Tests/ORM/Mapping/AbstractMappingDriverTest.php | 3 ++- tests/Doctrine/Tests/ORM/Mapping/AnnotationDriverTest.php | 2 +- tests/Doctrine/Tests/ORM/Mapping/PHPMappingDriverTest.php | 2 +- .../Tests/ORM/Mapping/StaticPHPMappingDriverTest.php | 2 +- .../Tests/ORM/Mapping/Symfony/AbstractDriverTest.php | 5 +++-- tests/Doctrine/Tests/ORM/Mapping/Symfony/XmlDriverTest.php | 5 +++-- .../Doctrine/Tests/ORM/Mapping/Symfony/YamlDriverTest.php | 5 +++-- tests/Doctrine/Tests/ORM/Mapping/XmlMappingDriverTest.php | 2 +- tests/Doctrine/Tests/ORM/Mapping/YamlMappingDriverTest.php | 2 +- .../ORM/Tools/Export/AbstractClassMetadataExporterTest.php | 2 +- .../Tools/Export/AnnotationClassMetadataExporterTest.php | 2 +- .../ORM/Tools/Export/PhpClassMetadataExporterTest.php | 2 +- .../ORM/Tools/Export/XmlClassMetadataExporterTest.php | 2 +- .../ORM/Tools/Export/YamlClassMetadataExporterTest.php | 2 +- .../Tests/ORM/Tools/ResolveTargetEntityListenerTest.php | 7 ++++--- 29 files changed, 41 insertions(+), 49 deletions(-) diff --git a/tests/Doctrine/Tests/Models/Company/CompanyContract.php b/tests/Doctrine/Tests/Models/Company/CompanyContract.php index 7751b5ea933..925f3f665ce 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyContract.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyContract.php @@ -129,7 +129,7 @@ public function removeEngineer(CompanyEmployee $engineer): void $this->engineers->removeElement($engineer); } - abstract public function calculatePrice(): void; + abstract public function calculatePrice(): int; public static function loadMetadata(ClassMetadataInfo $metadata): void { diff --git a/tests/Doctrine/Tests/Models/Company/CompanyFixContract.php b/tests/Doctrine/Tests/Models/Company/CompanyFixContract.php index 4cd31c0a893..945d340d74d 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyFixContract.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyFixContract.php @@ -17,7 +17,7 @@ class CompanyFixContract extends CompanyContract */ private $fixPrice = 0; - public function calculatePrice() + public function calculatePrice(): int { return $this->fixPrice; } diff --git a/tests/Doctrine/Tests/Models/Company/CompanyFlexContract.php b/tests/Doctrine/Tests/Models/Company/CompanyFlexContract.php index ff13f1e9a97..62de14a57f2 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyFlexContract.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyFlexContract.php @@ -72,7 +72,7 @@ class CompanyFlexContract extends CompanyContract */ public $managers; - public function calculatePrice() + public function calculatePrice(): int { return $this->hoursWorked * $this->pricePerHour; } diff --git a/tests/Doctrine/Tests/Models/Company/CompanyFlexUltraContract.php b/tests/Doctrine/Tests/Models/Company/CompanyFlexUltraContract.php index 893a0383c60..6f95f9fa0be 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyFlexUltraContract.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyFlexUltraContract.php @@ -21,7 +21,7 @@ class CompanyFlexUltraContract extends CompanyFlexContract */ private $maxPrice = 0; - public function calculatePrice() + public function calculatePrice(): int { return max($this->maxPrice, parent::calculatePrice()); } diff --git a/tests/Doctrine/Tests/ORM/Cache/DefaultRegionTest.php b/tests/Doctrine/Tests/ORM/Cache/DefaultRegionTest.php index 6562c2b3bda..8c3391b6428 100644 --- a/tests/Doctrine/Tests/ORM/Cache/DefaultRegionTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/DefaultRegionTest.php @@ -20,7 +20,7 @@ */ class DefaultRegionTest extends AbstractRegionTest { - protected function createRegion() + protected function createRegion(): DefaultRegion { return new DefaultRegion('default.region.test', $this->cache); } diff --git a/tests/Doctrine/Tests/ORM/Cache/FileLockRegionTest.php b/tests/Doctrine/Tests/ORM/Cache/FileLockRegionTest.php index 0c4449b2de3..0f251da9272 100644 --- a/tests/Doctrine/Tests/ORM/Cache/FileLockRegionTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/FileLockRegionTest.php @@ -7,6 +7,7 @@ use Doctrine\ORM\Cache\CacheKey; use Doctrine\ORM\Cache\ConcurrentRegion; use Doctrine\ORM\Cache\Lock; +use Doctrine\ORM\Cache\Region; use Doctrine\ORM\Cache\Region\DefaultRegion; use Doctrine\ORM\Cache\Region\FileLockRegion; use Doctrine\Tests\Mocks\CacheEntryMock; @@ -54,7 +55,7 @@ private function getFileName(ConcurrentRegion $region, CacheKey $key): string return $reflection->invoke($region, $key); } - protected function createRegion() + protected function createRegion(): Region { $this->directory = sys_get_temp_dir() . '/doctrine_lock_' . uniqid(); diff --git a/tests/Doctrine/Tests/ORM/Cache/MultiGetRegionTest.php b/tests/Doctrine/Tests/ORM/Cache/MultiGetRegionTest.php index b8bc33951da..fba59e04ef9 100644 --- a/tests/Doctrine/Tests/ORM/Cache/MultiGetRegionTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/MultiGetRegionTest.php @@ -11,7 +11,7 @@ class MultiGetRegionTest extends AbstractRegionTest { - protected function createRegion() + protected function createRegion(): DefaultMultiGetRegion { return new DefaultMultiGetRegion('default.region.test', $this->cache); } diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersisterTest.php index 3b70f774ad6..d3178d9034f 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersisterTest.php @@ -17,7 +17,7 @@ class NonStrictReadWriteCachedCollectionPersisterTest extends AbstractCollection /** * {@inheritdoc} */ - protected function createPersister(EntityManager $em, CollectionPersister $persister, Region $region, array $mapping) + protected function createPersister(EntityManager $em, CollectionPersister $persister, Region $region, array $mapping): NonStrictReadWriteCachedCollectionPersister { return new NonStrictReadWriteCachedCollectionPersister($persister, $region, $em, $mapping); } diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/ReadOnlyCachedCollectionPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/ReadOnlyCachedCollectionPersisterTest.php index 419e855eb5f..183e3f88f60 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/ReadOnlyCachedCollectionPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/ReadOnlyCachedCollectionPersisterTest.php @@ -14,10 +14,7 @@ */ class ReadOnlyCachedCollectionPersisterTest extends AbstractCollectionPersisterTest { - /** - * {@inheritdoc} - */ - protected function createPersister(EntityManager $em, CollectionPersister $persister, Region $region, array $mapping) + protected function createPersister(EntityManager $em, CollectionPersister $persister, Region $region, array $mapping): ReadOnlyCachedCollectionPersister { return new ReadOnlyCachedCollectionPersister($persister, $region, $em, $mapping); } diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersisterTest.php index 5ef3b2e428c..bc9d8f5985b 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersisterTest.php @@ -31,10 +31,7 @@ class ReadWriteCachedCollectionPersisterTest extends AbstractCollectionPersister 'unlock', ]; - /** - * {@inheritdoc} - */ - protected function createPersister(EntityManager $em, CollectionPersister $persister, Region $region, array $mapping) + protected function createPersister(EntityManager $em, CollectionPersister $persister, Region $region, array $mapping): ReadWriteCachedCollectionPersister { return new ReadWriteCachedCollectionPersister($persister, $region, $em, $mapping); } diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersisterTest.php index f73c11b328e..35e9d5ae583 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersisterTest.php @@ -19,10 +19,7 @@ */ class NonStrictReadWriteCachedEntityPersisterTest extends AbstractEntityPersisterTest { - /** - * {@inheritdoc} - */ - protected function createPersister(EntityManager $em, EntityPersister $persister, Region $region, ClassMetadata $metadata) + protected function createPersister(EntityManager $em, EntityPersister $persister, Region $region, ClassMetadata $metadata): NonStrictReadWriteCachedEntityPersister { return new NonStrictReadWriteCachedEntityPersister($persister, $region, $em, $metadata); } diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadOnlyCachedEntityPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadOnlyCachedEntityPersisterTest.php index 8cfdd42b289..f80b0bf349c 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadOnlyCachedEntityPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadOnlyCachedEntityPersisterTest.php @@ -16,10 +16,7 @@ */ class ReadOnlyCachedEntityPersisterTest extends AbstractEntityPersisterTest { - /** - * {@inheritdoc} - */ - protected function createPersister(EntityManager $em, EntityPersister $persister, Region $region, ClassMetadata $metadata) + protected function createPersister(EntityManager $em, EntityPersister $persister, Region $region, ClassMetadata $metadata): ReadOnlyCachedEntityPersister { return new ReadOnlyCachedEntityPersister($persister, $region, $em, $metadata); } diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersisterTest.php index 78fe89c5158..18e662c7d61 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersisterTest.php @@ -20,10 +20,7 @@ */ class ReadWriteCachedEntityPersisterTest extends AbstractEntityPersisterTest { - /** - * {@inheritdoc} - */ - protected function createPersister(EntityManager $em, EntityPersister $persister, Region $region, ClassMetadata $metadata) + protected function createPersister(EntityManager $em, EntityPersister $persister, Region $region, ClassMetadata $metadata): ReadWriteCachedEntityPersister { return new ReadWriteCachedEntityPersister($persister, $region, $em, $metadata); } diff --git a/tests/Doctrine/Tests/ORM/Functional/ManyToOneOrphanRemovalTest.php b/tests/Doctrine/Tests/ORM/Functional/ManyToOneOrphanRemovalTest.php index 617679cd18e..1e0d616c718 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ManyToOneOrphanRemovalTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ManyToOneOrphanRemovalTest.php @@ -5,6 +5,7 @@ namespace Doctrine\Tests\ORM\Functional; use Doctrine\DBAL\Driver\Connection; +use Doctrine\ORM\EntityManager; use Doctrine\ORM\Mapping\Driver\XmlDriver; use Doctrine\Persistence\Mapping\Driver\MappingDriver; use Doctrine\Tests\Models\OrnementalOrphanRemoval\Person; @@ -84,7 +85,7 @@ public function testOrphanRemovalIsPurelyOrnemental(): void protected function _getEntityManager( ?Connection $connection = null, ?MappingDriver $mappingDriver = null - ) { + ): EntityManager { return parent::_getEntityManager($connection, new XmlDriver( __DIR__ . DIRECTORY_SEPARATOR . 'xml' )); diff --git a/tests/Doctrine/Tests/ORM/Mapping/AbstractMappingDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/AbstractMappingDriverTest.php index 84be3344b2b..b3dd4f4568e 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/AbstractMappingDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/AbstractMappingDriverTest.php @@ -14,6 +14,7 @@ use Doctrine\ORM\Mapping\Id; use Doctrine\ORM\Mapping\MappingException; use Doctrine\ORM\Mapping\UnderscoreNamingStrategy; +use Doctrine\Persistence\Mapping\Driver\MappingDriver; use Doctrine\Persistence\Mapping\RuntimeReflectionService; use Doctrine\Tests\Models\Cache\City; use Doctrine\Tests\Models\CMS\CmsAddress; @@ -50,7 +51,7 @@ abstract class AbstractMappingDriverTest extends OrmTestCase { - abstract protected function _loadDriver(): void; + abstract protected function _loadDriver(): MappingDriver; public function createClassMetadata($entityClassName) { diff --git a/tests/Doctrine/Tests/ORM/Mapping/AnnotationDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/AnnotationDriverTest.php index cca9454687e..2b9bac6803f 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/AnnotationDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/AnnotationDriverTest.php @@ -120,7 +120,7 @@ protected function _loadDriverForCMSModels() return $annotationDriver; } - protected function _loadDriver() + protected function _loadDriver(): AnnotationDriver { return $this->createAnnotationDriver(); } diff --git a/tests/Doctrine/Tests/ORM/Mapping/PHPMappingDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/PHPMappingDriverTest.php index a27364d0197..2bb168752c8 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/PHPMappingDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/PHPMappingDriverTest.php @@ -13,7 +13,7 @@ class PHPMappingDriverTest extends AbstractMappingDriverTest { - protected function _loadDriver() + protected function _loadDriver(): PHPDriver { $path = __DIR__ . DIRECTORY_SEPARATOR . 'php'; diff --git a/tests/Doctrine/Tests/ORM/Mapping/StaticPHPMappingDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/StaticPHPMappingDriverTest.php index 432d45c12e4..f7ab2b22e4d 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/StaticPHPMappingDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/StaticPHPMappingDriverTest.php @@ -12,7 +12,7 @@ class StaticPHPMappingDriverTest extends AbstractMappingDriverTest { - protected function _loadDriver() + protected function _loadDriver(): StaticPHPDriver { return new StaticPHPDriver(__DIR__ . DIRECTORY_SEPARATOR . 'php'); } diff --git a/tests/Doctrine/Tests/ORM/Mapping/Symfony/AbstractDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/Symfony/AbstractDriverTest.php index 76ce5b6cc98..a9cdb5ff933 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/Symfony/AbstractDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/Symfony/AbstractDriverTest.php @@ -4,6 +4,7 @@ namespace Doctrine\Tests\ORM\Mapping\Symfony; +use Doctrine\Persistence\Mapping\Driver\FileDriver; use Doctrine\Persistence\Mapping\MappingException; use PHPUnit\Framework\TestCase; use RecursiveDirectoryIterator; @@ -94,7 +95,7 @@ protected function tearDown(): void @rmdir($this->dir); } - abstract protected function getFileExtension(): void; + abstract protected function getFileExtension(): string; - abstract protected function getDriver(array $paths = []): void; + abstract protected function getDriver(array $paths = []): FileDriver; } diff --git a/tests/Doctrine/Tests/ORM/Mapping/Symfony/XmlDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/Symfony/XmlDriverTest.php index 8771d42a4d8..57d1a8f93cd 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/Symfony/XmlDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/Symfony/XmlDriverTest.php @@ -5,6 +5,7 @@ namespace Doctrine\Tests\ORM\Mapping\Symfony; use Doctrine\ORM\Mapping\Driver\SimplifiedXmlDriver; +use Doctrine\Persistence\Mapping\Driver\FileDriver; use function array_flip; @@ -13,12 +14,12 @@ */ class XmlDriverTest extends AbstractDriverTest { - protected function getFileExtension() + protected function getFileExtension(): string { return '.orm.xml'; } - protected function getDriver(array $paths = []) + protected function getDriver(array $paths = []): FileDriver { return new SimplifiedXmlDriver(array_flip($paths)); } diff --git a/tests/Doctrine/Tests/ORM/Mapping/Symfony/YamlDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/Symfony/YamlDriverTest.php index d2f9584cc31..c3aa924d816 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/Symfony/YamlDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/Symfony/YamlDriverTest.php @@ -5,6 +5,7 @@ namespace Doctrine\Tests\ORM\Mapping\Symfony; use Doctrine\ORM\Mapping\Driver\SimplifiedYamlDriver; +use Doctrine\Persistence\Mapping\Driver\FileDriver; use Doctrine\Tests\VerifyDeprecations; use function array_flip; @@ -16,12 +17,12 @@ class YamlDriverTest extends AbstractDriverTest { use VerifyDeprecations; - protected function getFileExtension() + protected function getFileExtension(): string { return '.orm.yml'; } - protected function getDriver(array $paths = []) + protected function getDriver(array $paths = []): FileDriver { $driver = new SimplifiedYamlDriver(array_flip($paths)); $this->expectDeprecationMessageSame('YAML mapping driver is deprecated and will be removed in Doctrine ORM 3.0, please migrate to annotation or XML driver.'); diff --git a/tests/Doctrine/Tests/ORM/Mapping/XmlMappingDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/XmlMappingDriverTest.php index 84ae4095ad4..32f59939985 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/XmlMappingDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/XmlMappingDriverTest.php @@ -32,7 +32,7 @@ class XmlMappingDriverTest extends AbstractMappingDriverTest { - protected function _loadDriver() + protected function _loadDriver(): XmlDriver { return new XmlDriver(__DIR__ . DIRECTORY_SEPARATOR . 'xml'); } diff --git a/tests/Doctrine/Tests/ORM/Mapping/YamlMappingDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/YamlMappingDriverTest.php index e0d0ad5eaaf..ed56dfd7d88 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/YamlMappingDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/YamlMappingDriverTest.php @@ -21,7 +21,7 @@ class YamlMappingDriverTest extends AbstractMappingDriverTest { use VerifyDeprecations; - protected function _loadDriver() + protected function _loadDriver(): YamlDriver { if (! class_exists(Yaml::class, true)) { $this->markTestSkipped('Please install Symfony YAML Component into the include path of your PHP installation.'); diff --git a/tests/Doctrine/Tests/ORM/Tools/Export/AbstractClassMetadataExporterTest.php b/tests/Doctrine/Tests/ORM/Tools/Export/AbstractClassMetadataExporterTest.php index 43228cdf86d..cfb57aec23b 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Export/AbstractClassMetadataExporterTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Export/AbstractClassMetadataExporterTest.php @@ -49,7 +49,7 @@ abstract class AbstractClassMetadataExporterTest extends OrmTestCase protected $_extension; - abstract protected function _getType(): void; + abstract protected function _getType(): string; protected function _createEntityManager($metadataDriver) { diff --git a/tests/Doctrine/Tests/ORM/Tools/Export/AnnotationClassMetadataExporterTest.php b/tests/Doctrine/Tests/ORM/Tools/Export/AnnotationClassMetadataExporterTest.php index dde1ace412a..379853fd754 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Export/AnnotationClassMetadataExporterTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Export/AnnotationClassMetadataExporterTest.php @@ -11,7 +11,7 @@ */ class AnnotationClassMetadataExporterTest extends AbstractClassMetadataExporterTest { - protected function _getType() + protected function _getType(): string { return 'annotation'; } diff --git a/tests/Doctrine/Tests/ORM/Tools/Export/PhpClassMetadataExporterTest.php b/tests/Doctrine/Tests/ORM/Tools/Export/PhpClassMetadataExporterTest.php index 3db0a8e3f53..95fdb3f91ee 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Export/PhpClassMetadataExporterTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Export/PhpClassMetadataExporterTest.php @@ -11,7 +11,7 @@ */ class PhpClassMetadataExporterTest extends AbstractClassMetadataExporterTest { - protected function _getType() + protected function _getType(): string { return 'php'; } diff --git a/tests/Doctrine/Tests/ORM/Tools/Export/XmlClassMetadataExporterTest.php b/tests/Doctrine/Tests/ORM/Tools/Export/XmlClassMetadataExporterTest.php index 7950beeb683..d49ccff47d9 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Export/XmlClassMetadataExporterTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Export/XmlClassMetadataExporterTest.php @@ -15,7 +15,7 @@ */ class XmlClassMetadataExporterTest extends AbstractClassMetadataExporterTest { - protected function _getType() + protected function _getType(): string { return 'xml'; } diff --git a/tests/Doctrine/Tests/ORM/Tools/Export/YamlClassMetadataExporterTest.php b/tests/Doctrine/Tests/ORM/Tools/Export/YamlClassMetadataExporterTest.php index 3eb8b8ddaa1..2ff2583ead1 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Export/YamlClassMetadataExporterTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Export/YamlClassMetadataExporterTest.php @@ -13,7 +13,7 @@ */ class YamlClassMetadataExporterTest extends AbstractClassMetadataExporterTest { - protected function _getType() + protected function _getType(): string { if (! class_exists('Symfony\Component\Yaml\Yaml', true)) { $this->markTestSkipped('Please install Symfony YAML Component into the include path of your PHP installation.'); diff --git a/tests/Doctrine/Tests/ORM/Tools/ResolveTargetEntityListenerTest.php b/tests/Doctrine/Tests/ORM/Tools/ResolveTargetEntityListenerTest.php index b13dada1f0f..a1d6433eeea 100644 --- a/tests/Doctrine/Tests/ORM/Tools/ResolveTargetEntityListenerTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/ResolveTargetEntityListenerTest.php @@ -109,7 +109,7 @@ public function testDoesResolveTargetEntitiesInDQLAlsoWithInterfaces(): void interface ResolveTargetInterface { - public function getId(): void; + public function getId(): int; } interface TargetInterface extends ResolveTargetInterface @@ -122,6 +122,7 @@ interface TargetInterface extends ResolveTargetInterface class ResolveTargetEntity implements ResolveTargetInterface { /** + * @var int * @Id * @Column(type="integer") * @GeneratedValue(strategy="AUTO") @@ -143,7 +144,7 @@ class ResolveTargetEntity implements ResolveTargetInterface */ private $oneToOne; - public function getId() + public function getId(): int { return $this->id; } @@ -161,7 +162,7 @@ class TargetEntity implements TargetInterface */ private $id; - public function getId() + public function getId(): int { return $this->id; } From dd2120cd4105b0fd8338f5a4aaf75c86b956c54c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Fri, 29 Jan 2021 21:57:14 +0100 Subject: [PATCH 06/22] Make default value compatible with phpdoc --- tests/Doctrine/Tests/ORM/ConfigurationTest.php | 4 ++-- tests/Doctrine/Tests/ORM/Tools/EntityGeneratorTest.php | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/Doctrine/Tests/ORM/ConfigurationTest.php b/tests/Doctrine/Tests/ORM/ConfigurationTest.php index 4ec7145bb97..28c69a93ce8 100644 --- a/tests/Doctrine/Tests/ORM/ConfigurationTest.php +++ b/tests/Doctrine/Tests/ORM/ConfigurationTest.php @@ -157,9 +157,9 @@ public function testAddGetNamedNativeQuery(): void /** * Configures $this->configuration to use production settings. * - * @param string $skipCache Do not configure a cache of this type, either "query" or "metadata". + * @param string|null $skipCache Do not configure a cache of this type, either "query" or "metadata". */ - protected function setProductionSettings(string $skipCache = false): void + protected function setProductionSettings(?string $skipCache = null): void { $this->configuration->setAutoGenerateProxyClasses(AbstractProxyFactory::AUTOGENERATE_NEVER); diff --git a/tests/Doctrine/Tests/ORM/Tools/EntityGeneratorTest.php b/tests/Doctrine/Tests/ORM/Tools/EntityGeneratorTest.php index 0df1d884024..e28aa681bba 100644 --- a/tests/Doctrine/Tests/ORM/Tools/EntityGeneratorTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/EntityGeneratorTest.php @@ -193,7 +193,7 @@ private function mapEmbedded( string $fieldName, ClassMetadataInfo $classMetadata, ClassMetadataInfo $embeddableMetadata, - ?string $columnPrefix = false + ?string $columnPrefix = null ): void { $classMetadata->mapEmbedded( ['fieldName' => $fieldName, 'class' => $embeddableMetadata->name, 'columnPrefix' => $columnPrefix] From 32266c54f9e8ed52ba29e208ca5482a281f2dedb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Fri, 29 Jan 2021 22:14:29 +0100 Subject: [PATCH 07/22] Fix compatibility with parent signature --- tests/Doctrine/Tests/Mocks/EntityPersisterMock.php | 2 +- tests/Doctrine/Tests/Mocks/HydratorMockStatement.php | 2 +- tests/Doctrine/Tests/ORM/Functional/Ticket/DDC736Test.php | 6 +++++- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/tests/Doctrine/Tests/Mocks/EntityPersisterMock.php b/tests/Doctrine/Tests/Mocks/EntityPersisterMock.php index 9bdf26822b2..b455f360df5 100644 --- a/tests/Doctrine/Tests/Mocks/EntityPersisterMock.php +++ b/tests/Doctrine/Tests/Mocks/EntityPersisterMock.php @@ -39,7 +39,7 @@ class EntityPersisterMock extends BasicEntityPersister /** * @return mixed */ - public function addInsert(object $entity) + public function addInsert($entity) { $this->inserts[] = $entity; if ( diff --git a/tests/Doctrine/Tests/Mocks/HydratorMockStatement.php b/tests/Doctrine/Tests/Mocks/HydratorMockStatement.php index e308925df18..9e24e63689c 100644 --- a/tests/Doctrine/Tests/Mocks/HydratorMockStatement.php +++ b/tests/Doctrine/Tests/Mocks/HydratorMockStatement.php @@ -39,7 +39,7 @@ public function __construct(array $resultSet) * * @return array */ - public function fetchAll(?int $fetchMode = null, ?int $fetchArgument = null, ?array $ctorArgs = null): array + public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = null): array { return $this->_resultSet; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC736Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC736Test.php index 2e66e91605a..aff73ffde13 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC736Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC736Test.php @@ -90,8 +90,12 @@ public function walkSelectStatement(AST\SelectStatement $AST): void $this->walkSelectClause($AST->selectClause); } - public function walkSelectClause(SelectClause $selectClause): void + /** + * {@inheritdoc} + */ + public function walkSelectClause($selectClause): void { + assert($selectClause instanceof SelectClause); foreach ($selectClause->selectExpressions as $key => $selectExpr) { assert($selectExpr instanceof SelectExpression); if ($selectExpr->expression === 'c') { From ab0e4007a5441c69bd212476bbeb52353882c4da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Fri, 29 Jan 2021 23:54:53 +0100 Subject: [PATCH 08/22] Use interface instead of concretion --- tests/Doctrine/Tests/Models/Cache/Travel.php | 3 ++- .../Tests/ORM/Functional/AdvancedAssociationTest.php | 7 ++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/tests/Doctrine/Tests/Models/Cache/Travel.php b/tests/Doctrine/Tests/Models/Cache/Travel.php index 7e8bdc0c631..2c62c619c75 100644 --- a/tests/Doctrine/Tests/Models/Cache/Travel.php +++ b/tests/Doctrine/Tests/Models/Cache/Travel.php @@ -6,6 +6,7 @@ use DateTime; use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\Common\Collections\Collection; /** * @Cache @@ -67,7 +68,7 @@ public function setTraveler(Traveler $traveler): void $this->traveler = $traveler; } - public function getVisitedCities(): ArrayCollection + public function getVisitedCities(): Collection { return $this->visitedCities; } diff --git a/tests/Doctrine/Tests/ORM/Functional/AdvancedAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/AdvancedAssociationTest.php index 64ab4d792df..1f6d14e7974 100644 --- a/tests/Doctrine/Tests/ORM/Functional/AdvancedAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/AdvancedAssociationTest.php @@ -5,6 +5,7 @@ namespace Doctrine\Tests\ORM\Functional; use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\Common\Collections\Collection; use Doctrine\ORM\PersistentCollection; use Doctrine\Tests\IterableTester; use Doctrine\Tests\OrmFunctionalTestCase; @@ -214,7 +215,7 @@ public function removeType(Type $type): void } } - public function getTypes(): kateglo\application\helpers\collections\ArrayCollection + public function getTypes(): Collection { return $this->types; } @@ -380,7 +381,7 @@ public function getType(): PhraseType return $this->type; } - public function getDefinitions(): ArrayCollection + public function getDefinitions(): Collection { return $this->definitions; } @@ -445,7 +446,7 @@ public function setPhrases(ArrayCollection $phrases): void $this->phrases = $phrases; } - public function getPhrases(): ArrayCollection + public function getPhrases(): Collection { return $this->phrases; } From e00dba94f485e4e9a165d2f56a615ded2079103f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Fri, 29 Jan 2021 23:55:09 +0100 Subject: [PATCH 09/22] Remove strict types --- tests/Doctrine/Tests/ORM/Cache/FileLockRegionTest.php | 2 -- tests/Doctrine/Tests/ORM/Functional/Locking/OptimisticTest.php | 2 -- tests/Doctrine/Tests/ORM/Functional/QueryDqlFunctionTest.php | 2 -- tests/Doctrine/Tests/ORM/Functional/ResultCacheTest.php | 2 -- tests/Doctrine/Tests/ORM/Functional/Ticket/GH5887Test.php | 2 -- tests/Doctrine/Tests/ORM/Mapping/Symfony/AbstractDriverTest.php | 2 -- tests/Doctrine/Tests/OrmFunctionalTestCase.php | 2 -- 7 files changed, 14 deletions(-) diff --git a/tests/Doctrine/Tests/ORM/Cache/FileLockRegionTest.php b/tests/Doctrine/Tests/ORM/Cache/FileLockRegionTest.php index 0f251da9272..94ef4fae015 100644 --- a/tests/Doctrine/Tests/ORM/Cache/FileLockRegionTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/FileLockRegionTest.php @@ -1,7 +1,5 @@ Date: Fri, 29 Jan 2021 23:55:17 +0100 Subject: [PATCH 10/22] Fix type declarations --- .../ORM/Tools/Console/ConsoleRunner.php | 1 - .../Tests/Mocks/DriverConnectionMock.php | 6 +- tests/Doctrine/Tests/Models/CMS/CmsUser.php | 2 +- .../Tests/Models/DDC1590/DDC1590User.php | 2 + .../Entity/AbstractEntityPersisterTest.php | 2 +- ...OneToOneSelfReferentialAssociationTest.php | 2 +- .../Tests/ORM/Functional/ResultCacheTest.php | 11 ++-- .../SingleTableCompositeKeyTest.php | 3 +- .../ORM/Functional/Ticket/DDC1080Test.php | 59 ++++++++++--------- .../ORM/Functional/Ticket/DDC1925Test.php | 3 +- .../ORM/Functional/Ticket/DDC2862Test.php | 7 +-- .../ORM/Functional/Ticket/DDC3634Test.php | 7 ++- .../ORM/Functional/Ticket/DDC501Test.php | 2 +- .../Tests/ORM/Tools/EntityGeneratorTest.php | 5 +- 14 files changed, 59 insertions(+), 53 deletions(-) diff --git a/lib/Doctrine/ORM/Tools/Console/ConsoleRunner.php b/lib/Doctrine/ORM/Tools/Console/ConsoleRunner.php index b7696710adb..96744e887de 100644 --- a/lib/Doctrine/ORM/Tools/Console/ConsoleRunner.php +++ b/lib/Doctrine/ORM/Tools/Console/ConsoleRunner.php @@ -26,7 +26,6 @@ use OutOfBoundsException; use PackageVersions\Versions; use Symfony\Component\Console\Application; -use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Helper\HelperSet; /** diff --git a/tests/Doctrine/Tests/Mocks/DriverConnectionMock.php b/tests/Doctrine/Tests/Mocks/DriverConnectionMock.php index 5a4352d3f47..27983f43051 100644 --- a/tests/Doctrine/Tests/Mocks/DriverConnectionMock.php +++ b/tests/Doctrine/Tests/Mocks/DriverConnectionMock.php @@ -13,15 +13,15 @@ */ class DriverConnectionMock implements Connection { - /** @var Statement */ + /** @var Statement|null */ private $statementMock; - public function getStatementMock(): Statement + public function getStatementMock(): ?Statement { return $this->statementMock; } - public function setStatementMock(Statement $statementMock): void + public function setStatementMock(?Statement $statementMock): void { $this->statementMock = $statementMock; } diff --git a/tests/Doctrine/Tests/Models/CMS/CmsUser.php b/tests/Doctrine/Tests/Models/CMS/CmsUser.php index d52428c56b6..d417702cc2c 100644 --- a/tests/Doctrine/Tests/Models/CMS/CmsUser.php +++ b/tests/Doctrine/Tests/Models/CMS/CmsUser.php @@ -260,7 +260,7 @@ public function setAddress(CmsAddress $address): void } } - public function getEmail(): CmsEmail + public function getEmail(): ?CmsEmail { return $this->email; } diff --git a/tests/Doctrine/Tests/Models/DDC1590/DDC1590User.php b/tests/Doctrine/Tests/Models/DDC1590/DDC1590User.php index bd04239124a..7bac8b55a32 100644 --- a/tests/Doctrine/Tests/Models/DDC1590/DDC1590User.php +++ b/tests/Doctrine/Tests/Models/DDC1590/DDC1590User.php @@ -4,6 +4,8 @@ namespace Doctrine\Tests\Models\DDC1590; +use Doctrine\Tests\Models\DDC1590\DDC1590Entity; + /** * @Entity * @Table(name="users") diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/AbstractEntityPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/AbstractEntityPersisterTest.php index 104c92bcabe..acfca374720 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/AbstractEntityPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/AbstractEntityPersisterTest.php @@ -50,7 +50,7 @@ protected function createRegion(): Region return $this->createMock(Region::class); } - protected function createPersisterDefault(): \Doctrine\ORM\Cache\Persister\AbstractEntityPersister + protected function createPersisterDefault(): AbstractEntityPersister { return $this->createPersister($this->em, $this->entityPersister, $this->region, $this->em->getClassMetadata(Country::class)); } diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToOneSelfReferentialAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToOneSelfReferentialAssociationTest.php index 81ae61ed38e..ee847e5226f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToOneSelfReferentialAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToOneSelfReferentialAssociationTest.php @@ -75,7 +75,7 @@ public function testEagerLoadsAssociation(): void /** * @group mine */ - public function testLazyLoadsAssociation(): unknown_type + public function testLazyLoadsAssociation(): void { $this->_createFixture(); diff --git a/tests/Doctrine/Tests/ORM/Functional/ResultCacheTest.php b/tests/Doctrine/Tests/ORM/Functional/ResultCacheTest.php index 09a63af0dd3..7910fecbb46 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ResultCacheTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ResultCacheTest.php @@ -3,6 +3,7 @@ namespace Doctrine\Tests\ORM\Functional; use Doctrine\Common\Cache\ArrayCache; +use Doctrine\ORM\NativeQuery; use Doctrine\ORM\Query; use Doctrine\ORM\Query\ResultSetMapping; use Doctrine\Tests\Models\CMS\CmsArticle; @@ -244,7 +245,7 @@ public function testNativeQueryResultCaching() /** * @depends testNativeQueryResultCaching */ - public function testResultCacheNotDependsOnQueryHints(string $query): void + public function testResultCacheNotDependsOnQueryHints(NativeQuery $query): void { $cache = $query->getResultCacheDriver(); $cacheCount = $this->getCacheSize($cache); @@ -256,11 +257,9 @@ public function testResultCacheNotDependsOnQueryHints(string $query): void } /** - * @param $query - * * @depends testNativeQueryResultCaching */ - public function testResultCacheDependsOnParameters($query): void + public function testResultCacheDependsOnParameters(NativeQuery $query): void { $cache = $query->getResultCacheDriver(); $cacheCount = $this->getCacheSize($cache); @@ -272,11 +271,9 @@ public function testResultCacheDependsOnParameters($query): void } /** - * @param $query - * * @depends testNativeQueryResultCaching */ - public function testResultCacheNotDependsOnHydrationMode($query): void + public function testResultCacheNotDependsOnHydrationMode(NativeQuery $query): void { $cache = $query->getResultCacheDriver(); $cacheCount = $this->getCacheSize($cache); diff --git a/tests/Doctrine/Tests/ORM/Functional/SingleTableCompositeKeyTest.php b/tests/Doctrine/Tests/ORM/Functional/SingleTableCompositeKeyTest.php index 33ee05cb316..821b7f1d8e1 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SingleTableCompositeKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SingleTableCompositeKeyTest.php @@ -4,7 +4,6 @@ namespace Doctrine\Tests\ORM\Functional; -use Doctrine\Tests\Models\CompositeKeyInheritance\JoinedChildClass; use Doctrine\Tests\Models\CompositeKeyInheritance\SingleChildClass; use Doctrine\Tests\Models\CompositeKeyInheritance\SingleRootClass; use Doctrine\Tests\OrmFunctionalTestCase; @@ -51,7 +50,7 @@ public function testUpdateWithCompositeKey(): void $this->assertEquals($entity, $persistedEntity); } - private function findEntity(): JoinedChildClass + private function findEntity(): SingleChildClass { return $this->_em->find(SingleRootClass::class, ['keyPart1' => 'part-1', 'keyPart2' => 'part-2']); } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1080Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1080Test.php index e2377c02fd4..859a4a25ac8 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1080Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1080Test.php @@ -5,6 +5,7 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\Common\Collections\Collection; use Doctrine\Tests\OrmFunctionalTestCase; use function count; @@ -79,14 +80,21 @@ public function testHydration(): void class DDC1080Foo { /** + * @var int * @Id * @Column(name="fooID", type="integer") * @GeneratedValue(strategy="AUTO") */ protected $_fooID; - /** @Column(name="fooTitle", type="string") */ + + /** + * @var string + * @Column(name="fooTitle", type="string") + */ protected $_fooTitle; + /** + * @psalm-var Collection * @OneToMany(targetEntity="DDC1080FooBar", mappedBy="_foo", * cascade={"persist"}) * @OrderBy({"_orderNr"="ASC"}) @@ -98,41 +106,35 @@ public function __construct() $this->_fooBars = new ArrayCollection(); } - /** - * @return the $fooID - */ - public function getFooID(): the + public function getFooID(): int { return $this->_fooID; } - /** - * @return the $fooTitle - */ - public function getFooTitle(): the + public function getFooTitle(): string { return $this->_fooTitle; } /** - * @return the $fooBars + * @psalm-return Collection */ - public function getFooBars(): the + public function getFooBars(): Collection { return $this->_fooBars; } - public function setFooID(field_type $fooID): void + public function setFooID(int $fooID): void { $this->_fooID = $fooID; } - public function setFooTitle(field_type $fooTitle): void + public function setFooTitle(string $fooTitle): void { $this->_fooTitle = $fooTitle; } - public function setFooBars(field_type $fooBars): void + public function setFooBars(array $fooBars): void { $this->_fooBars = $fooBars; } @@ -144,14 +146,21 @@ public function setFooBars(field_type $fooBars): void class DDC1080Bar { /** + * @var int * @Id * @Column(name="barID", type="integer") * @GeneratedValue(strategy="AUTO") */ protected $_barID; - /** @Column(name="barTitle", type="string") */ + + /** + * @var string + * @Column(name="barTitle", type="string") + */ protected $_barTitle; + /** + * @psalm-var Collection * @OneToMany(targetEntity="DDC1080FooBar", mappedBy="_bar", * cascade={"persist"}) * @OrderBy({"_orderNr"="ASC"}) @@ -163,41 +172,35 @@ public function __construct() $this->_fooBars = new ArrayCollection(); } - /** - * @return the $barID - */ - public function getBarID(): the + public function getBarID(): int { return $this->_barID; } - /** - * @return the $barTitle - */ - public function getBarTitle(): the + public function getBarTitle(): string { return $this->_barTitle; } /** - * @return the $fooBars + * @psalm-return Collection */ - public function getFooBars(): the + public function getFooBars(): Collection { return $this->_fooBars; } - public function setBarID(field_type $barID): void + public function setBarID(int $barID): void { $this->_barID = $barID; } - public function setBarTitle(field_type $barTitle): void + public function setBarTitle(string $barTitle): void { $this->_barTitle = $barTitle; } - public function setFooBars(field_type $fooBars): void + public function setFooBars(array $fooBars): void { $this->_fooBars = $fooBars; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1925Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1925Test.php index 461560b2419..345b23a8edf 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1925Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1925Test.php @@ -5,6 +5,7 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\Common\Collections\Collection; use Doctrine\Tests\OrmFunctionalTestCase; use function assert; @@ -106,7 +107,7 @@ public function getTitle(): string return $this->title; } - public function getBuyers(): ArrayCollection + public function getBuyers(): Collection { return $this->buyers; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2862Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2862Test.php index 914d882a35e..189a5f9c806 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2862Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2862Test.php @@ -6,7 +6,6 @@ use Doctrine\ORM\Tools\ToolsException; use Doctrine\Tests\OrmFunctionalTestCase; -use Entities\User; /** * @group DDC-2862 @@ -139,7 +138,7 @@ class DDC2862Driver /** * @Cache() * @OneToOne(targetEntity="DDC2862User") - * @var User + * @var DDC2862User */ protected $userProfile; @@ -164,12 +163,12 @@ public function getName(): string return $this->name; } - public function setUserProfile(User $userProfile): void + public function setUserProfile(DDC2862User $userProfile): void { $this->userProfile = $userProfile; } - public function getUserProfile(): User + public function getUserProfile(): DDC2862User { return $this->userProfile; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3634Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3634Test.php index b42af6f62ee..46eb0df75d6 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3634Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3634Test.php @@ -111,10 +111,13 @@ class DDC3634LastInsertIdMockingConnection extends Connection /** @var Connection */ private $realConnection; - /** @var int */ + /** @var int|string */ private $identifier; - public function __construct(int $identifier, Connection $realConnection) + /** + * @param int|string $identifier + */ + public function __construct($identifier, Connection $realConnection) { $this->realConnection = $realConnection; $this->identifier = $identifier; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC501Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC501Test.php index 86c7b03834f..b1c425291ef 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC501Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC501Test.php @@ -115,7 +115,7 @@ protected function createAndPersistUser() return $user; } - protected function loadUserFromEntityManager(): Doctrine\Tests\Models\CMS\CmsUser + protected function loadUserFromEntityManager(): CmsUser { return $this->_em ->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name like :name') diff --git a/tests/Doctrine/Tests/ORM/Tools/EntityGeneratorTest.php b/tests/Doctrine/Tests/ORM/Tools/EntityGeneratorTest.php index e28aa681bba..6a47fe15ca0 100644 --- a/tests/Doctrine/Tests/ORM/Tools/EntityGeneratorTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/EntityGeneratorTest.php @@ -189,11 +189,14 @@ private function generateTestEmbeddableFixture(): ClassMetadataInfo return $metadata; } + /** + * @param string|bool $columnPrefix + */ private function mapEmbedded( string $fieldName, ClassMetadataInfo $classMetadata, ClassMetadataInfo $embeddableMetadata, - ?string $columnPrefix = null + $columnPrefix = false ): void { $classMetadata->mapEmbedded( ['fieldName' => $fieldName, 'class' => $embeddableMetadata->name, 'columnPrefix' => $columnPrefix] From 15eacd787be9bbb7f1bd02c144417a3ac3b833d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Fri, 29 Jan 2021 23:55:30 +0100 Subject: [PATCH 11/22] Remove weird extra argument --- .../ORM/Cache/Persister/Entity/AbstractEntityPersisterTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/AbstractEntityPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/AbstractEntityPersisterTest.php index acfca374720..16793812357 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/AbstractEntityPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/AbstractEntityPersisterTest.php @@ -283,7 +283,7 @@ public function testInvokeRefresh(): void ->with($this->equalTo(['id' => 1]), $this->equalTo($entity), $this->equalTo(0)) ->will($this->returnValue($entity)); - $this->assertNull($persister->refresh(['id' => 1], $entity), 0); + $this->assertNull($persister->refresh(['id' => 1], $entity)); } public function testInvokeLoadCriteria(): void From 36d0352c017772a76c7a4f8af0ebd50bdc70ad12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Fri, 29 Jan 2021 23:55:40 +0100 Subject: [PATCH 12/22] Add missing use statements --- .../Cache/Persister/Collection/AbstractCollectionPersister.php | 1 + lib/Doctrine/ORM/Tools/Console/ConsoleRunner.php | 3 ++- tests/Doctrine/Tests/ORM/Functional/QueryTest.php | 2 ++ 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/Doctrine/ORM/Cache/Persister/Collection/AbstractCollectionPersister.php b/lib/Doctrine/ORM/Cache/Persister/Collection/AbstractCollectionPersister.php index 03675f59d18..56cfd06b8dd 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Collection/AbstractCollectionPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Collection/AbstractCollectionPersister.php @@ -26,6 +26,7 @@ use Doctrine\ORM\Cache\CollectionHydrator; use Doctrine\ORM\Cache\EntityCacheKey; use Doctrine\ORM\Cache\Logging\CacheLogger; +use Doctrine\ORM\Cache\Persister\Entity\CachedEntityPersister; use Doctrine\ORM\Cache\Region; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Mapping\ClassMetadata; diff --git a/lib/Doctrine/ORM/Tools/Console/ConsoleRunner.php b/lib/Doctrine/ORM/Tools/Console/ConsoleRunner.php index 96744e887de..fd265c8b102 100644 --- a/lib/Doctrine/ORM/Tools/Console/ConsoleRunner.php +++ b/lib/Doctrine/ORM/Tools/Console/ConsoleRunner.php @@ -26,6 +26,7 @@ use OutOfBoundsException; use PackageVersions\Versions; use Symfony\Component\Console\Application; +use Symfony\Component\Console\Command\Command as SymfonyCommand; use Symfony\Component\Console\Helper\HelperSet; /** @@ -49,7 +50,7 @@ public static function createHelperSet(EntityManagerInterface $entityManager): H /** * Runs console with the given helper set. * - * @param Command[] $commands + * @param SymfonyCommand[] $commands */ public static function run(HelperSet $helperSet, array $commands = []): void { diff --git a/tests/Doctrine/Tests/ORM/Functional/QueryTest.php b/tests/Doctrine/Tests/ORM/Functional/QueryTest.php index 2e6fbb1441a..fb4c92c203f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/QueryTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/QueryTest.php @@ -13,6 +13,8 @@ use Doctrine\ORM\Query\QueryException; use Doctrine\ORM\UnexpectedResultException; use Doctrine\Tests\IterableTester; +use Doctrine\Tests\Models\CMS\CmsArticle; +use Doctrine\Tests\Models\CMS\CmsPhonenumber; use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\OrmFunctionalTestCase; use Exception; From 1687d9c479fbbf794eedcc6c35128bb16ec8d2b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Sat, 30 Jan 2021 10:12:45 +0100 Subject: [PATCH 13/22] Restore version annotation, but capitalized @version is commonly used for svn ids and is forbidden --- .../Tests/ORM/Functional/Ticket/DDC832Test.php | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC832Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC832Test.php index e20932651a8..d637678b2a9 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC832Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC832Test.php @@ -161,7 +161,10 @@ class DDC832Like /** @Column(type="string") */ public $word; - /** @Column(type="integer") */ + /** + * @Version + * @Column(type="integer") + */ public $version; public function __construct($word) @@ -185,7 +188,10 @@ class DDC832JoinedIndex /** @Column(type="string") */ public $name; - /** @Column(type="integer") */ + /** + * @Version + * @Column(type="integer") + */ public $version; public function __construct($name) From 9a40ac6e2a0d261706745315812e20f9f99c01bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Sat, 30 Jan 2021 10:57:52 +0100 Subject: [PATCH 14/22] Restore weird phpdoc Tests do not pass when I format that phpdoc nicely. --- tests/Doctrine/Tests/ORM/Tools/SchemaValidatorTest.php | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/tests/Doctrine/Tests/ORM/Tools/SchemaValidatorTest.php b/tests/Doctrine/Tests/ORM/Tools/SchemaValidatorTest.php index 284d9c3d4a0..23292c2071a 100644 --- a/tests/Doctrine/Tests/ORM/Tools/SchemaValidatorTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/SchemaValidatorTest.php @@ -325,9 +325,7 @@ class DDC1649Two { /** * @var DDC1649One - * @Id - * @ManyToOne(targetEntity="DDC1649One") - * @JoinColumn(name="id", referencedColumnName="id") + * @Id @ManyToOne(targetEntity="DDC1649One")@JoinColumn(name="id", referencedColumnName="id") */ public $one; } From d9f0e2a27f0f66394d0a420665f34288cd58e744 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Sat, 30 Jan 2021 11:13:10 +0100 Subject: [PATCH 15/22] Add exclude rules for tricky cases --- phpcs.xml.dist | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/phpcs.xml.dist b/phpcs.xml.dist index f59a3243899..6eb21c5f57b 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -29,6 +29,12 @@ */lib/* + + tests/Doctrine/Tests/Mocks/HydratorMockStatement.php @@ -166,4 +172,12 @@ tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1301Test.php tests/Doctrine/Tests/ORM/Functional/ExtraLazyCollectionTest.php + + + + tests/Doctrine/Tests/Models/DDC1590/DDC1590User.php + From 497dfd1a845a48ce7a79ad3acf1a12bb14da682e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Sat, 30 Jan 2021 11:28:21 +0100 Subject: [PATCH 16/22] Avoid covariant return types It's not supported by PHP 7.2/7.3 --- tests/Doctrine/Tests/ORM/Cache/DefaultRegionTest.php | 3 ++- tests/Doctrine/Tests/ORM/Cache/MultiGetRegionTest.php | 3 ++- .../NonStrictReadWriteCachedCollectionPersisterTest.php | 3 ++- .../Collection/ReadOnlyCachedCollectionPersisterTest.php | 3 ++- .../Collection/ReadWriteCachedCollectionPersisterTest.php | 3 ++- .../Entity/NonStrictReadWriteCachedEntityPersisterTest.php | 3 ++- .../Persister/Entity/ReadOnlyCachedEntityPersisterTest.php | 3 ++- .../Persister/Entity/ReadWriteCachedEntityPersisterTest.php | 3 ++- tests/Doctrine/Tests/ORM/Mapping/AnnotationDriverTest.php | 3 ++- tests/Doctrine/Tests/ORM/Mapping/PHPMappingDriverTest.php | 3 ++- .../Doctrine/Tests/ORM/Mapping/StaticPHPMappingDriverTest.php | 3 ++- tests/Doctrine/Tests/ORM/Mapping/XmlMappingDriverTest.php | 3 ++- tests/Doctrine/Tests/ORM/Mapping/YamlMappingDriverTest.php | 3 ++- 13 files changed, 26 insertions(+), 13 deletions(-) diff --git a/tests/Doctrine/Tests/ORM/Cache/DefaultRegionTest.php b/tests/Doctrine/Tests/ORM/Cache/DefaultRegionTest.php index 8c3391b6428..eada93fe3e9 100644 --- a/tests/Doctrine/Tests/ORM/Cache/DefaultRegionTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/DefaultRegionTest.php @@ -9,6 +9,7 @@ use Doctrine\Common\Cache\Cache; use Doctrine\Common\Cache\CacheProvider; use Doctrine\ORM\Cache\CollectionCacheEntry; +use Doctrine\ORM\Cache\Region; use Doctrine\ORM\Cache\Region\DefaultRegion; use Doctrine\Tests\Mocks\CacheEntryMock; use Doctrine\Tests\Mocks\CacheKeyMock; @@ -20,7 +21,7 @@ */ class DefaultRegionTest extends AbstractRegionTest { - protected function createRegion(): DefaultRegion + protected function createRegion(): Region { return new DefaultRegion('default.region.test', $this->cache); } diff --git a/tests/Doctrine/Tests/ORM/Cache/MultiGetRegionTest.php b/tests/Doctrine/Tests/ORM/Cache/MultiGetRegionTest.php index fba59e04ef9..0228ce6b846 100644 --- a/tests/Doctrine/Tests/ORM/Cache/MultiGetRegionTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/MultiGetRegionTest.php @@ -5,13 +5,14 @@ namespace Doctrine\Tests\ORM\Cache; use Doctrine\ORM\Cache\CollectionCacheEntry; +use Doctrine\ORM\Cache\Region; use Doctrine\ORM\Cache\Region\DefaultMultiGetRegion; use Doctrine\Tests\Mocks\CacheEntryMock; use Doctrine\Tests\Mocks\CacheKeyMock; class MultiGetRegionTest extends AbstractRegionTest { - protected function createRegion(): DefaultMultiGetRegion + protected function createRegion(): Region { return new DefaultMultiGetRegion('default.region.test', $this->cache); } diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersisterTest.php index d3178d9034f..a36a4a8b9bc 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersisterTest.php @@ -4,6 +4,7 @@ namespace Doctrine\Tests\ORM\Cache\Persister\Collection; +use Doctrine\ORM\Cache\Persister\Collection\AbstractCollectionPersister; use Doctrine\ORM\Cache\Persister\Collection\NonStrictReadWriteCachedCollectionPersister; use Doctrine\ORM\Cache\Region; use Doctrine\ORM\EntityManager; @@ -17,7 +18,7 @@ class NonStrictReadWriteCachedCollectionPersisterTest extends AbstractCollection /** * {@inheritdoc} */ - protected function createPersister(EntityManager $em, CollectionPersister $persister, Region $region, array $mapping): NonStrictReadWriteCachedCollectionPersister + protected function createPersister(EntityManager $em, CollectionPersister $persister, Region $region, array $mapping): AbstractCollectionPersister { return new NonStrictReadWriteCachedCollectionPersister($persister, $region, $em, $mapping); } diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/ReadOnlyCachedCollectionPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/ReadOnlyCachedCollectionPersisterTest.php index 183e3f88f60..e074409bb2e 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/ReadOnlyCachedCollectionPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/ReadOnlyCachedCollectionPersisterTest.php @@ -4,6 +4,7 @@ namespace Doctrine\Tests\ORM\Cache\Persister\Collection; +use Doctrine\ORM\Cache\Persister\Collection\AbstractCollectionPersister; use Doctrine\ORM\Cache\Persister\Collection\ReadOnlyCachedCollectionPersister; use Doctrine\ORM\Cache\Region; use Doctrine\ORM\EntityManager; @@ -14,7 +15,7 @@ */ class ReadOnlyCachedCollectionPersisterTest extends AbstractCollectionPersisterTest { - protected function createPersister(EntityManager $em, CollectionPersister $persister, Region $region, array $mapping): ReadOnlyCachedCollectionPersister + protected function createPersister(EntityManager $em, CollectionPersister $persister, Region $region, array $mapping): AbstractCollectionPersister { return new ReadOnlyCachedCollectionPersister($persister, $region, $em, $mapping); } diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersisterTest.php index bc9d8f5985b..9cca407f578 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersisterTest.php @@ -7,6 +7,7 @@ use Doctrine\ORM\Cache\CollectionCacheKey; use Doctrine\ORM\Cache\ConcurrentRegion; use Doctrine\ORM\Cache\Lock; +use Doctrine\ORM\Cache\Persister\Collection\AbstractCollectionPersister; use Doctrine\ORM\Cache\Persister\Collection\ReadWriteCachedCollectionPersister; use Doctrine\ORM\Cache\Region; use Doctrine\ORM\EntityManager; @@ -31,7 +32,7 @@ class ReadWriteCachedCollectionPersisterTest extends AbstractCollectionPersister 'unlock', ]; - protected function createPersister(EntityManager $em, CollectionPersister $persister, Region $region, array $mapping): ReadWriteCachedCollectionPersister + protected function createPersister(EntityManager $em, CollectionPersister $persister, Region $region, array $mapping): AbstractCollectionPersister { return new ReadWriteCachedCollectionPersister($persister, $region, $em, $mapping); } diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersisterTest.php index 35e9d5ae583..4dc5c7c0e6f 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersisterTest.php @@ -6,6 +6,7 @@ use Doctrine\ORM\Cache\EntityCacheEntry; use Doctrine\ORM\Cache\EntityCacheKey; +use Doctrine\ORM\Cache\Persister\Entity\AbstractEntityPersister; use Doctrine\ORM\Cache\Persister\Entity\NonStrictReadWriteCachedEntityPersister; use Doctrine\ORM\Cache\Region; use Doctrine\ORM\EntityManager; @@ -19,7 +20,7 @@ */ class NonStrictReadWriteCachedEntityPersisterTest extends AbstractEntityPersisterTest { - protected function createPersister(EntityManager $em, EntityPersister $persister, Region $region, ClassMetadata $metadata): NonStrictReadWriteCachedEntityPersister + protected function createPersister(EntityManager $em, EntityPersister $persister, Region $region, ClassMetadata $metadata): AbstractEntityPersister { return new NonStrictReadWriteCachedEntityPersister($persister, $region, $em, $metadata); } diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadOnlyCachedEntityPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadOnlyCachedEntityPersisterTest.php index f80b0bf349c..4ba4e372a2f 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadOnlyCachedEntityPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadOnlyCachedEntityPersisterTest.php @@ -4,6 +4,7 @@ namespace Doctrine\Tests\ORM\Cache\Persister\Entity; +use Doctrine\ORM\Cache\Persister\Entity\AbstractEntityPersister; use Doctrine\ORM\Cache\Persister\Entity\ReadOnlyCachedEntityPersister; use Doctrine\ORM\Cache\Region; use Doctrine\ORM\EntityManager; @@ -16,7 +17,7 @@ */ class ReadOnlyCachedEntityPersisterTest extends AbstractEntityPersisterTest { - protected function createPersister(EntityManager $em, EntityPersister $persister, Region $region, ClassMetadata $metadata): ReadOnlyCachedEntityPersister + protected function createPersister(EntityManager $em, EntityPersister $persister, Region $region, ClassMetadata $metadata): AbstractEntityPersister { return new ReadOnlyCachedEntityPersister($persister, $region, $em, $metadata); } diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersisterTest.php index 18e662c7d61..3cb28c5604f 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersisterTest.php @@ -7,6 +7,7 @@ use Doctrine\ORM\Cache\ConcurrentRegion; use Doctrine\ORM\Cache\EntityCacheKey; use Doctrine\ORM\Cache\Lock; +use Doctrine\ORM\Cache\Persister\Entity\AbstractEntityPersister; use Doctrine\ORM\Cache\Persister\Entity\ReadWriteCachedEntityPersister; use Doctrine\ORM\Cache\Region; use Doctrine\ORM\EntityManager; @@ -20,7 +21,7 @@ */ class ReadWriteCachedEntityPersisterTest extends AbstractEntityPersisterTest { - protected function createPersister(EntityManager $em, EntityPersister $persister, Region $region, ClassMetadata $metadata): ReadWriteCachedEntityPersister + protected function createPersister(EntityManager $em, EntityPersister $persister, Region $region, ClassMetadata $metadata): AbstractEntityPersister { return new ReadWriteCachedEntityPersister($persister, $region, $em, $metadata); } diff --git a/tests/Doctrine/Tests/ORM/Mapping/AnnotationDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/AnnotationDriverTest.php index 2b9bac6803f..c9ad0f61cf6 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/AnnotationDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/AnnotationDriverTest.php @@ -11,6 +11,7 @@ use Doctrine\ORM\Mapping\ClassMetadataFactory; use Doctrine\ORM\Mapping\Driver\AnnotationDriver; use Doctrine\ORM\Mapping\MappingException; +use Doctrine\Persistence\Mapping\Driver\MappingDriver; use Doctrine\Persistence\Mapping\RuntimeReflectionService; use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\Models\DDC1872\DDC1872ExampleEntityWithoutOverride; @@ -120,7 +121,7 @@ protected function _loadDriverForCMSModels() return $annotationDriver; } - protected function _loadDriver(): AnnotationDriver + protected function _loadDriver(): MappingDriver { return $this->createAnnotationDriver(); } diff --git a/tests/Doctrine/Tests/ORM/Mapping/PHPMappingDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/PHPMappingDriverTest.php index 2bb168752c8..28acde5497c 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/PHPMappingDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/PHPMappingDriverTest.php @@ -5,6 +5,7 @@ namespace Doctrine\Tests\ORM\Mapping; use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\Persistence\Mapping\Driver\MappingDriver; use Doctrine\Persistence\Mapping\Driver\PHPDriver; use Doctrine\Tests\Models\DDC889\DDC889Class; use Doctrine\Tests\ORM\Mapping; @@ -13,7 +14,7 @@ class PHPMappingDriverTest extends AbstractMappingDriverTest { - protected function _loadDriver(): PHPDriver + protected function _loadDriver(): MappingDriver { $path = __DIR__ . DIRECTORY_SEPARATOR . 'php'; diff --git a/tests/Doctrine/Tests/ORM/Mapping/StaticPHPMappingDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/StaticPHPMappingDriverTest.php index f7ab2b22e4d..21db295c1f2 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/StaticPHPMappingDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/StaticPHPMappingDriverTest.php @@ -5,6 +5,7 @@ namespace Doctrine\Tests\ORM\Mapping; use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\Persistence\Mapping\Driver\MappingDriver; use Doctrine\Persistence\Mapping\Driver\StaticPHPDriver; use Doctrine\Tests\Models\DDC889\DDC889Class; @@ -12,7 +13,7 @@ class StaticPHPMappingDriverTest extends AbstractMappingDriverTest { - protected function _loadDriver(): StaticPHPDriver + protected function _loadDriver(): MappingDriver { return new StaticPHPDriver(__DIR__ . DIRECTORY_SEPARATOR . 'php'); } diff --git a/tests/Doctrine/Tests/ORM/Mapping/XmlMappingDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/XmlMappingDriverTest.php index 32f59939985..60cbdc64b44 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/XmlMappingDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/XmlMappingDriverTest.php @@ -8,6 +8,7 @@ use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Mapping\ClassMetadataFactory; use Doctrine\ORM\Mapping\Driver\XmlDriver; +use Doctrine\Persistence\Mapping\Driver\MappingDriver; use Doctrine\Persistence\Mapping\RuntimeReflectionService; use Doctrine\Tests\Models\DDC117\DDC117Translation; use Doctrine\Tests\Models\DDC3293\DDC3293User; @@ -32,7 +33,7 @@ class XmlMappingDriverTest extends AbstractMappingDriverTest { - protected function _loadDriver(): XmlDriver + protected function _loadDriver(): MappingDriver { return new XmlDriver(__DIR__ . DIRECTORY_SEPARATOR . 'xml'); } diff --git a/tests/Doctrine/Tests/ORM/Mapping/YamlMappingDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/YamlMappingDriverTest.php index ed56dfd7d88..502f07dc448 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/YamlMappingDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/YamlMappingDriverTest.php @@ -7,6 +7,7 @@ use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Mapping\ClassMetadataFactory; use Doctrine\ORM\Mapping\Driver\YamlDriver; +use Doctrine\Persistence\Mapping\Driver\MappingDriver; use Doctrine\Tests\Models\DirectoryTree\Directory; use Doctrine\Tests\Models\DirectoryTree\File; use Doctrine\Tests\Models\Generic\SerializationModel; @@ -21,7 +22,7 @@ class YamlMappingDriverTest extends AbstractMappingDriverTest { use VerifyDeprecations; - protected function _loadDriver(): YamlDriver + protected function _loadDriver(): MappingDriver { if (! class_exists(Yaml::class, true)) { $this->markTestSkipped('Please install Symfony YAML Component into the include path of your PHP installation.'); From 210c2ee6a443d76bbe48f1d5d357bc43ed9ecf13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Sat, 30 Jan 2021 11:32:03 +0100 Subject: [PATCH 17/22] Remove strict types --- .../Tests/ORM/Functional/SecondLevelCacheAbstractTest.php | 2 -- .../ORM/Functional/SecondLevelCacheCompositePrimaryKeyTest.php | 2 -- tests/Doctrine/Tests/ORM/Functional/Ticket/GH6531Test.php | 2 -- 3 files changed, 6 deletions(-) diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheAbstractTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheAbstractTest.php index 6e43bd8b263..9fd3524e403 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheAbstractTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheAbstractTest.php @@ -1,7 +1,5 @@ Date: Sat, 30 Jan 2021 13:15:19 +0100 Subject: [PATCH 18/22] Fix or remove wrong assertions --- lib/Doctrine/ORM/Tools/Console/Command/InfoCommand.php | 4 ++-- lib/Doctrine/ORM/Tools/SchemaTool.php | 4 ++-- .../Tests/ORM/Mapping/BasicInheritanceMappingTest.php | 9 +++++---- .../Tests/ORM/Mapping/ClassMetadataFactoryTest.php | 2 -- tests/Doctrine/Tests/ORM/Mapping/ClassMetadataTest.php | 2 -- 5 files changed, 9 insertions(+), 12 deletions(-) diff --git a/lib/Doctrine/ORM/Tools/Console/Command/InfoCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/InfoCommand.php index 832cd5aee95..dfef06ad4e0 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/InfoCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/InfoCommand.php @@ -20,7 +20,7 @@ namespace Doctrine\ORM\Tools\Console\Command; -use Doctrine\ORM\EntityManager; +use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Mapping\MappingException; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; @@ -61,7 +61,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $ui = new SymfonyStyle($input, $output); $entityManager = $this->getHelper('em')->getEntityManager(); - assert($entityManager instanceof EntityManager); + assert($entityManager instanceof EntityManagerInterface); $entityClassNames = $entityManager->getConfiguration() ->getMetadataDriverImpl() diff --git a/lib/Doctrine/ORM/Tools/SchemaTool.php b/lib/Doctrine/ORM/Tools/SchemaTool.php index c565276de09..f9037c25d6b 100644 --- a/lib/Doctrine/ORM/Tools/SchemaTool.php +++ b/lib/Doctrine/ORM/Tools/SchemaTool.php @@ -30,7 +30,6 @@ use Doctrine\DBAL\Schema\Visitor\RemoveNamespacedAssets; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Mapping\ClassMetadata; -use Doctrine\ORM\Mapping\OneToOne; use Doctrine\ORM\Mapping\QuoteStrategy; use Doctrine\ORM\ORMException; use Doctrine\ORM\Tools\Event\GenerateSchemaEventArgs; @@ -47,6 +46,7 @@ use function current; use function implode; use function in_array; +use function is_array; use function is_numeric; use function strtolower; @@ -282,7 +282,7 @@ static function (ClassMetadata $class) use ($idMapping): bool { $pkColumns[] = $this->quoteStrategy->getColumnName($identifierField, $class, $this->platform); } elseif (isset($class->associationMappings[$identifierField])) { $assoc = $class->associationMappings[$identifierField]; - assert($assoc instanceof OneToOne); + assert(is_array($assoc)); foreach ($assoc['joinColumns'] as $joinColumn) { $pkColumns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform); diff --git a/tests/Doctrine/Tests/ORM/Mapping/BasicInheritanceMappingTest.php b/tests/Doctrine/Tests/ORM/Mapping/BasicInheritanceMappingTest.php index ec67766a224..e2b65261d82 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/BasicInheritanceMappingTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/BasicInheritanceMappingTest.php @@ -6,6 +6,7 @@ use Doctrine\ORM\EntityRepository; use Doctrine\ORM\Id\SequenceGenerator; +use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Mapping\ClassMetadataFactory; use Doctrine\ORM\Mapping\MappingException; use Doctrine\Persistence\Mapping\RuntimeReflectionService; @@ -155,7 +156,7 @@ public function testMappedSuperclassWithId(): void public function testGeneratedValueFromMappedSuperclass(): void { $class = $this->cmf->getMetadataFor(SuperclassEntity::class); - assert($class instanceof ClassMetadataInfo); + assert($class instanceof ClassMetadata); $this->assertInstanceOf(SequenceGenerator::class, $class->idGenerator); $this->assertEquals( @@ -171,7 +172,7 @@ public function testGeneratedValueFromMappedSuperclass(): void public function testSequenceDefinitionInHierarchyWithSandwichMappedSuperclass(): void { $class = $this->cmf->getMetadataFor(HierarchyD::class); - assert($class instanceof ClassMetadataInfo); + assert($class instanceof ClassMetadata); $this->assertInstanceOf(SequenceGenerator::class, $class->idGenerator); $this->assertEquals( @@ -187,7 +188,7 @@ public function testSequenceDefinitionInHierarchyWithSandwichMappedSuperclass(): public function testMultipleMappedSuperclasses(): void { $class = $this->cmf->getMetadataFor(MediumSuperclassEntity::class); - assert($class instanceof ClassMetadataInfo); + assert($class instanceof ClassMetadata); $this->assertInstanceOf(SequenceGenerator::class, $class->idGenerator); $this->assertEquals( @@ -204,7 +205,7 @@ public function testMultipleMappedSuperclasses(): void public function testMappedSuperclassIndex(): void { $class = $this->cmf->getMetadataFor(EntityIndexSubClass::class); - assert($class instanceof ClassMetadataInfo); + assert($class instanceof ClassMetadata); $this->assertArrayHasKey('mapped1', $class->fieldMappings); $this->assertArrayHasKey('IDX_NAME_INDEX', $class->table['uniqueConstraints']); diff --git a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataFactoryTest.php b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataFactoryTest.php index 17ad44b70c2..e015aba8cbe 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataFactoryTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataFactoryTest.php @@ -407,8 +407,6 @@ public function testAcceptsEntityManagerInterfaceInstances(): void $classMetadataFactory = new ClassMetadataFactory(); $entityManager = $this->createMock(EntityManagerInterface::class); - assert($entityManager instanceof EntityManager); - $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. diff --git a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataTest.php b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataTest.php index cc2cce062aa..75ad5e28432 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataTest.php @@ -8,7 +8,6 @@ use Doctrine\ORM\Events; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Mapping\DefaultNamingStrategy; -use Doctrine\ORM\Mapping\ManyToMany; use Doctrine\ORM\Mapping\MappingException; use Doctrine\ORM\Mapping\UnderscoreNamingStrategy; use Doctrine\Persistence\Mapping\RuntimeReflectionService; @@ -167,7 +166,6 @@ public function testSerializeManyToManyJoinTableCascade(): void ); $assoc = $cm->associationMappings['groups']; - assert($assoc instanceof ManyToMany); $assoc = unserialize(serialize($assoc)); $this->assertTrue($assoc['isOnDeleteCascade']); From 7f30cd310206200563aeaf0b7b873788ae723df8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Sat, 30 Jan 2021 18:15:54 +0100 Subject: [PATCH 19/22] Require doctrine/common ^3.0.3 That release comes with a fix for a bug that affects us since we are using return type declarations for wakeUp() in proxyfied classes in on of our tests. --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 1e5ddefee7e..bd40c081a9f 100644 --- a/composer.json +++ b/composer.json @@ -22,7 +22,7 @@ "doctrine/annotations": "^1.11.1", "doctrine/cache": "^1.9.1", "doctrine/collections": "^1.5", - "doctrine/common": "^3.0", + "doctrine/common": "^3.0.3", "doctrine/dbal": "^2.10.0", "doctrine/event-manager": "^1.1", "doctrine/inflector": "^1.4|^2.0", From 8f1911a4fe138c1bc8071eda949a87d3057e950d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Fri, 15 May 2020 19:43:32 +0200 Subject: [PATCH 20/22] Fix cs by hand --- lib/Doctrine/ORM/AbstractQuery.php | 4 +- lib/Doctrine/ORM/Cache/CacheFactory.php | 4 +- lib/Doctrine/ORM/Cache/CollectionHydrator.php | 2 +- .../ORM/Cache/DefaultCollectionHydrator.php | 2 +- .../ORM/Cache/DefaultEntityHydrator.php | 2 +- lib/Doctrine/ORM/Cache/DefaultQueryCache.php | 9 +- .../AbstractCollectionPersister.php | 6 +- .../Collection/CachedCollectionPersister.php | 2 +- .../ReadWriteCachedCollectionPersister.php | 2 +- .../Entity/AbstractEntityPersister.php | 2 +- lib/Doctrine/ORM/Cache/QueryCache.php | 6 +- .../ORM/Cache/Region/FileLockRegion.php | 14 +- .../ORM/Cache/RegionsConfiguration.php | 4 +- lib/Doctrine/ORM/EntityManager.php | 2 +- lib/Doctrine/ORM/EntityRepository.php | 14 +- lib/Doctrine/ORM/Event/PreUpdateEventArgs.php | 6 +- .../Internal/Hydration/AbstractHydrator.php | 10 +- .../ORM/Internal/Hydration/ArrayHydrator.php | 10 +- .../ORM/Internal/Hydration/ObjectHydrator.php | 12 +- .../ORM/Internal/HydrationCompleteHandler.php | 2 +- .../Mapping/Builder/AssociationBuilder.php | 8 +- .../ORM/Mapping/Builder/EmbeddedBuilder.php | 4 +- .../Mapping/Builder/EntityListenerBuilder.php | 2 +- .../ORM/Mapping/Builder/FieldBuilder.php | 6 +- .../Builder/ManyToManyAssociationBuilder.php | 2 +- .../ORM/Mapping/ClassMetadataFactory.php | 2 +- .../ORM/Mapping/ClassMetadataInfo.php | 6 +- .../ORM/Mapping/Driver/AnnotationDriver.php | 215 +++++++++++------- .../ORM/Mapping/Driver/DatabaseDriver.php | 10 +- lib/Doctrine/ORM/Mapping/MappingException.php | 26 ++- lib/Doctrine/ORM/Mapping/QuoteStrategy.php | 24 +- .../ORM/ORMInvalidArgumentException.php | 4 +- .../Entity/BasicEntityPersister.php | 44 ++-- .../ORM/Persisters/Entity/EntityPersister.php | 16 +- .../ORM/Persisters/SqlValueVisitor.php | 4 +- lib/Doctrine/ORM/Query.php | 3 +- lib/Doctrine/ORM/Query/AST/ArithmeticTerm.php | 4 +- .../ORM/Query/AST/CoalesceExpression.php | 4 +- .../ORM/Query/AST/ConditionalExpression.php | 4 +- .../ORM/Query/AST/ConditionalTerm.php | 4 +- lib/Doctrine/ORM/Query/AST/FromClause.php | 4 +- .../Query/AST/Functions/DateAddFunction.php | 10 +- .../ORM/Query/AST/GeneralCaseExpression.php | 6 +- lib/Doctrine/ORM/Query/AST/GroupByClause.php | 4 +- .../AST/IdentificationVariableDeclaration.php | 4 +- lib/Doctrine/ORM/Query/AST/InExpression.php | 2 +- .../ORM/Query/AST/InstanceOfExpression.php | 2 +- .../ORM/Query/AST/NewObjectExpression.php | 6 +- lib/Doctrine/ORM/Query/AST/OrderByClause.php | 4 +- .../ORM/Query/AST/PartialObjectExpression.php | 6 +- lib/Doctrine/ORM/Query/AST/SelectClause.php | 6 +- .../Query/AST/SimpleArithmeticExpression.php | 4 +- .../ORM/Query/AST/SimpleCaseExpression.php | 4 +- .../ORM/Query/AST/SubselectFromClause.php | 4 +- lib/Doctrine/ORM/Query/AST/UpdateClause.php | 6 +- .../Query/Exec/MultiTableUpdateExecutor.php | 2 +- lib/Doctrine/ORM/Query/Expr/Andx.php | 2 +- lib/Doctrine/ORM/Query/Expr/Base.php | 10 +- lib/Doctrine/ORM/Query/Expr/Func.php | 2 +- lib/Doctrine/ORM/Query/Expr/OrderBy.php | 4 +- lib/Doctrine/ORM/Query/Expr/Orx.php | 2 +- lib/Doctrine/ORM/Query/Expr/Select.php | 2 +- lib/Doctrine/ORM/Query/Filter/SQLFilter.php | 6 +- lib/Doctrine/ORM/Query/Parser.php | 25 +- .../ORM/Query/QueryExpressionVisitor.php | 8 +- .../ORM/Query/ResultSetMappingBuilder.php | 17 +- lib/Doctrine/ORM/Query/SqlWalker.php | 5 +- lib/Doctrine/ORM/Query/TreeWalker.php | 2 +- lib/Doctrine/ORM/QueryBuilder.php | 2 +- .../Tools/AttachEntityListenersListener.php | 2 +- .../Command/ConvertDoctrine1SchemaCommand.php | 2 +- .../Console/Command/ConvertMappingCommand.php | 3 +- .../Command/SchemaTool/AbstractCommand.php | 2 +- .../ORM/Tools/Console/ConsoleRunner.php | 2 +- .../ORM/Tools/Console/MetadataFilter.php | 4 +- .../ORM/Tools/ConvertDoctrine1Schema.php | 26 +-- lib/Doctrine/ORM/Tools/EntityGenerator.php | 6 +- .../Tools/Export/ClassMetadataExporter.php | 2 +- .../Tools/Export/Driver/AbstractExporter.php | 2 +- .../ORM/Tools/Export/Driver/PhpExporter.php | 7 +- .../ORM/Tools/Export/Driver/XmlExporter.php | 30 ++- .../ORM/Tools/Export/Driver/YamlExporter.php | 11 +- .../Tools/Pagination/CountOutputWalker.php | 4 +- .../Pagination/LimitSubqueryOutputWalker.php | 10 +- .../ORM/Tools/ResolveTargetEntityListener.php | 4 +- lib/Doctrine/ORM/Tools/SchemaTool.php | 12 +- lib/Doctrine/ORM/Tools/Setup.php | 20 +- lib/Doctrine/ORM/UnitOfWork.php | 10 +- .../ORM/Utility/IdentifierFlattener.php | 2 +- phpcs.xml.dist | 8 + tests/Doctrine/Tests/Mocks/CacheKeyMock.php | 2 +- .../Tests/Mocks/ConcurrentRegionMock.php | 2 - tests/Doctrine/Tests/Mocks/TaskMock.php | 2 +- .../Tests/Models/DDC3597/DDC3597Image.php | 2 +- .../Tests/Models/DDC3597/DDC3597Media.php | 2 +- .../DDC3597/Embeddable/DDC3597Dimension.php | 2 +- .../Models/ECommerce/ECommerceCustomer.php | 2 +- .../Tests/Models/Legacy/LegacyCar.php | 2 +- .../Tests/Models/Navigation/NavCountry.php | 2 +- .../Tests/Models/Navigation/NavPhotos.php | 2 +- .../Tests/ORM/Cache/DefaultQueryCacheTest.php | 12 +- .../ORM/Functional/LifecycleCallbackTest.php | 2 +- .../Tests/ORM/Functional/NotifyPolicyTest.php | 20 +- .../Tests/ORM/Functional/PaginationTest.php | 30 +-- .../SecondLevelCacheConcurrentTest.php | 2 +- .../ORM/Functional/Ticket/DDC1690Test.php | 20 +- .../ORM/Functional/Ticket/DDC1918Test.php | 4 +- .../ORM/Functional/Ticket/DDC2230Test.php | 2 +- .../ORM/Functional/Ticket/DDC3582Test.php | 2 +- .../ORM/Functional/Ticket/DDC3699Test.php | 6 +- .../ORM/Functional/Ticket/DDC618Test.php | 2 +- .../ORM/Functional/Ticket/GH5762Test.php | 2 +- .../ORM/Mapping/ClassMetadataFactoryTest.php | 6 +- .../Pagination/CountOutputWalkerTest.php | 4 +- 114 files changed, 542 insertions(+), 429 deletions(-) diff --git a/lib/Doctrine/ORM/AbstractQuery.php b/lib/Doctrine/ORM/AbstractQuery.php index c16eb1f9cd0..2ba30bc4fa8 100644 --- a/lib/Doctrine/ORM/AbstractQuery.php +++ b/lib/Doctrine/ORM/AbstractQuery.php @@ -1007,8 +1007,8 @@ public function toIterable(iterable $parameters = [], $hydrationMode = null): it /** * Executes the query. * - * @param ArrayCollection|array|null $parameters Query parameters. - * @param string|int|null $hydrationMode Processing mode to be used during the hydration process. + * @param ArrayCollection|mixed[]|null $parameters Query parameters. + * @param string|int|null $hydrationMode Processing mode to be used during the hydration process. * * @return mixed */ diff --git a/lib/Doctrine/ORM/Cache/CacheFactory.php b/lib/Doctrine/ORM/Cache/CacheFactory.php index 259c82a2757..6839b043d81 100644 --- a/lib/Doctrine/ORM/Cache/CacheFactory.php +++ b/lib/Doctrine/ORM/Cache/CacheFactory.php @@ -49,7 +49,7 @@ public function buildCachedEntityPersister(EntityManagerInterface $em, EntityPer * * @param EntityManagerInterface $em The entity manager. * @param CollectionPersister $persister The collection persister that will be cached. - * @param array $mapping The association mapping. + * @param mixed[] $mapping The association mapping. * * @return CachedCollectionPersister */ @@ -79,7 +79,7 @@ public function buildEntityHydrator(EntityManagerInterface $em, ClassMetadata $m * Build a collection hydrator * * @param EntityManagerInterface $em The Entity manager. - * @param array $mapping The association mapping. + * @param mixed[] $mapping The association mapping. * * @return CollectionHydrator The built collection hydrator. */ diff --git a/lib/Doctrine/ORM/Cache/CollectionHydrator.php b/lib/Doctrine/ORM/Cache/CollectionHydrator.php index e4a901b9462..87a042eff9b 100644 --- a/lib/Doctrine/ORM/Cache/CollectionHydrator.php +++ b/lib/Doctrine/ORM/Cache/CollectionHydrator.php @@ -32,7 +32,7 @@ interface CollectionHydrator /** * @param ClassMetadata $metadata The entity metadata. * @param CollectionCacheKey $key The cached collection key. - * @param array|Collection $collection The collection. + * @param mixed[]|Collection $collection The collection. * * @return CollectionCacheEntry */ diff --git a/lib/Doctrine/ORM/Cache/DefaultCollectionHydrator.php b/lib/Doctrine/ORM/Cache/DefaultCollectionHydrator.php index b7c39209598..a4b16451ba6 100644 --- a/lib/Doctrine/ORM/Cache/DefaultCollectionHydrator.php +++ b/lib/Doctrine/ORM/Cache/DefaultCollectionHydrator.php @@ -41,7 +41,7 @@ class DefaultCollectionHydrator implements CollectionHydrator /** @var UnitOfWork */ private $uow; - /** @var array */ + /** @var array */ private static $hints = [Query::HINT_CACHE_ENABLED => true]; /** diff --git a/lib/Doctrine/ORM/Cache/DefaultEntityHydrator.php b/lib/Doctrine/ORM/Cache/DefaultEntityHydrator.php index 78be12e3b01..b54b310d539 100644 --- a/lib/Doctrine/ORM/Cache/DefaultEntityHydrator.php +++ b/lib/Doctrine/ORM/Cache/DefaultEntityHydrator.php @@ -50,7 +50,7 @@ class DefaultEntityHydrator implements EntityHydrator */ private $identifierFlattener; - /** @var array */ + /** @var array */ private static $hints = [Query::HINT_CACHE_ENABLED => true]; /** diff --git a/lib/Doctrine/ORM/Cache/DefaultQueryCache.php b/lib/Doctrine/ORM/Cache/DefaultQueryCache.php index 1760c2a0076..f2884b2f29a 100644 --- a/lib/Doctrine/ORM/Cache/DefaultQueryCache.php +++ b/lib/Doctrine/ORM/Cache/DefaultQueryCache.php @@ -62,7 +62,7 @@ class DefaultQueryCache implements QueryCache /** @var CacheLogger */ protected $cacheLogger; - /** @var array */ + /** @var array */ private static $hints = [Query::HINT_CACHE_ENABLED => true]; /** @@ -304,7 +304,8 @@ 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) { + $assocInfo = $this->storeAssociationCache($key, $assoc, $assocValue); + if ($assocInfo === null) { return false; } @@ -337,8 +338,8 @@ public function put(QueryCacheKey $key, ResultSetMapping $rsm, $result, array $h } /** - * @param array $assoc - * @param mixed $assocValue + * @param array $assoc + * @param mixed $assocValue * * @return mixed[]|null * diff --git a/lib/Doctrine/ORM/Cache/Persister/Collection/AbstractCollectionPersister.php b/lib/Doctrine/ORM/Cache/Persister/Collection/AbstractCollectionPersister.php index 56cfd06b8dd..941a9b8a2e2 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Collection/AbstractCollectionPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Collection/AbstractCollectionPersister.php @@ -57,10 +57,10 @@ abstract class AbstractCollectionPersister implements CachedCollectionPersister /** @var ClassMetadata */ protected $targetEntity; - /** @var array */ + /** @var mixed[] */ protected $association; - /** @var array */ + /** @var mixed[] */ protected $queuedCache = []; /** @var Region */ @@ -79,7 +79,7 @@ abstract class AbstractCollectionPersister implements CachedCollectionPersister * @param CollectionPersister $persister The collection persister that will be cached. * @param Region $region The collection region. * @param EntityManagerInterface $em The entity manager. - * @param array $association The association mapping. + * @param mixed[] $association The association mapping. */ public function __construct(CollectionPersister $persister, Region $region, EntityManagerInterface $em, array $association) { diff --git a/lib/Doctrine/ORM/Cache/Persister/Collection/CachedCollectionPersister.php b/lib/Doctrine/ORM/Cache/Persister/Collection/CachedCollectionPersister.php index 67147024398..76962ff53b5 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Collection/CachedCollectionPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Collection/CachedCollectionPersister.php @@ -52,7 +52,7 @@ public function loadCollectionCache(PersistentCollection $collection, Collection /** * Stores a collection into cache * - * @param array|Collection $elements + * @param mixed[]|Collection $elements * * @return void */ diff --git a/lib/Doctrine/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersister.php b/lib/Doctrine/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersister.php index 3ceea169855..86bd341845a 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersister.php @@ -34,7 +34,7 @@ class ReadWriteCachedCollectionPersister extends AbstractCollectionPersister * @param CollectionPersister $persister The collection persister that will be cached. * @param ConcurrentRegion $region The collection region. * @param EntityManagerInterface $em The entity manager. - * @param array $association The association mapping. + * @param mixed[] $association The association mapping. */ public function __construct(CollectionPersister $persister, ConcurrentRegion $region, EntityManagerInterface $em, array $association) { diff --git a/lib/Doctrine/ORM/Cache/Persister/Entity/AbstractEntityPersister.php b/lib/Doctrine/ORM/Cache/Persister/Entity/AbstractEntityPersister.php index 7fcf4bd4cab..53d8c7614e9 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Entity/AbstractEntityPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Entity/AbstractEntityPersister.php @@ -57,7 +57,7 @@ abstract class AbstractEntityPersister implements CachedEntityPersister /** @var ClassMetadata */ protected $class; - /** @var array */ + /** @var mixed[] */ protected $queuedCache = []; /** @var Region */ diff --git a/lib/Doctrine/ORM/Cache/QueryCache.php b/lib/Doctrine/ORM/Cache/QueryCache.php index 7aeb168c090..9a3c6e82701 100644 --- a/lib/Doctrine/ORM/Cache/QueryCache.php +++ b/lib/Doctrine/ORM/Cache/QueryCache.php @@ -34,15 +34,15 @@ interface QueryCache public function clear(); /** - * @param mixed $result - * @param array $hints + * @param mixed $result + * @param mixed[] $hints * * @return bool */ public function put(QueryCacheKey $key, ResultSetMapping $rsm, $result, array $hints = []); /** - * @param array $hints + * @param mixed[] $hints * * @return array|null */ diff --git a/lib/Doctrine/ORM/Cache/Region/FileLockRegion.php b/lib/Doctrine/ORM/Cache/Region/FileLockRegion.php index cd4111540d2..2a09b3c1b0c 100644 --- a/lib/Doctrine/ORM/Cache/Region/FileLockRegion.php +++ b/lib/Doctrine/ORM/Cache/Region/FileLockRegion.php @@ -53,17 +53,13 @@ class FileLockRegion implements ConcurrentRegion { public const LOCK_EXTENSION = 'lock'; - /** - * var \Doctrine\ORM\Cache\Region - */ + /** @var Region */ private $region; /** @var string */ private $directory; - /** - * var integer - */ + /** @var int */ private $lockLifetime; /** @@ -267,10 +263,6 @@ public function unlock(CacheKey $key, Lock $lock) return false; } - if (! @unlink($this->getLockFileName($key))) { - return false; - } - - return true; + return @unlink($this->getLockFileName($key)); } } diff --git a/lib/Doctrine/ORM/Cache/RegionsConfiguration.php b/lib/Doctrine/ORM/Cache/RegionsConfiguration.php index 0609ed1aa2f..99ada98f6ad 100644 --- a/lib/Doctrine/ORM/Cache/RegionsConfiguration.php +++ b/lib/Doctrine/ORM/Cache/RegionsConfiguration.php @@ -25,10 +25,10 @@ */ class RegionsConfiguration { - /** @var array */ + /** @var array */ private $lifetimes = []; - /** @var array */ + /** @var array */ private $lockLifetimes = []; /** @var int */ diff --git a/lib/Doctrine/ORM/EntityManager.php b/lib/Doctrine/ORM/EntityManager.php index 52c311e881c..81da7f6957b 100644 --- a/lib/Doctrine/ORM/EntityManager.php +++ b/lib/Doctrine/ORM/EntityManager.php @@ -354,7 +354,7 @@ 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 object|array|null $entity + * @param object|mixed[]|null $entity * * @return void * diff --git a/lib/Doctrine/ORM/EntityRepository.php b/lib/Doctrine/ORM/EntityRepository.php index f94d43a9103..0f92ba662df 100644 --- a/lib/Doctrine/ORM/EntityRepository.php +++ b/lib/Doctrine/ORM/EntityRepository.php @@ -32,6 +32,7 @@ use function array_slice; use function lcfirst; +use function sprintf; use function strpos; use function substr; use function trigger_error; @@ -238,7 +239,7 @@ public function count(array $criteria) * @return mixed The returned value from the resolved method. * * @throws ORMException - * @throws BadMethodCallException If the method called is invalid + * @throws BadMethodCallException If the method called is invalid. */ public function __call($method, $arguments) { @@ -254,10 +255,11 @@ public function __call($method, $arguments) return $this->resolveMagicCall('count', substr($method, 7), $arguments); } - throw new BadMethodCallException( - "Undefined method '$method'. The method name must start with " . - 'either findBy, findOneBy or countBy!' - ); + throw new BadMethodCallException(sprintf( + 'Undefined method "%s". The method name must start with ' . + 'either findBy, findOneBy or countBy!', + $method + )); } /** @@ -316,7 +318,7 @@ public function matching(Criteria $criteria) * * @return mixed * - * @throws ORMException If the method called is invalid or the requested field/association does not exist + * @throws ORMException If the method called is invalid or the requested field/association does not exist. */ private function resolveMagicCall($method, $by, array $arguments) { diff --git a/lib/Doctrine/ORM/Event/PreUpdateEventArgs.php b/lib/Doctrine/ORM/Event/PreUpdateEventArgs.php index 520fcf1df41..ca0a116e0f8 100644 --- a/lib/Doctrine/ORM/Event/PreUpdateEventArgs.php +++ b/lib/Doctrine/ORM/Event/PreUpdateEventArgs.php @@ -31,12 +31,12 @@ */ class PreUpdateEventArgs extends LifecycleEventArgs { - /** @var array */ + /** @var array> */ private $entityChangeSet; /** - * @param object $entity - * @param array $changeSet + * @param object $entity + * @param array> $changeSet */ public function __construct($entity, EntityManagerInterface $em, array &$changeSet) { diff --git a/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php b/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php index 0be65fe6328..f84b1355411 100644 --- a/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php +++ b/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php @@ -307,9 +307,9 @@ abstract protected function hydrateAllData(); * field names during this procedure as well as any necessary conversions on * the values applied. Scalar values are kept in a specific key 'scalars'. * - * @param array $data SQL Result Row. - * @param array &$id Dql-Alias => ID-Hash. - * @param array &$nonemptyComponents Does this DQL-Alias has at least one non NULL value? + * @param mixed[] $data SQL Result Row. + * @param array &$id Dql-Alias => ID-Hash. + * @param array &$nonemptyComponents Does this DQL-Alias has at least one non NULL value? * * @return array> An array with all the fields * (name => value) of the data @@ -560,8 +560,8 @@ protected function getClassMetadata($className) /** * Register entity as managed in UnitOfWork. * - * @param object $entity - * @param array $data + * @param object $entity + * @param mixed[] $data * * @return void * diff --git a/lib/Doctrine/ORM/Internal/Hydration/ArrayHydrator.php b/lib/Doctrine/ORM/Internal/Hydration/ArrayHydrator.php index 7e46315fa83..80772e8e0d9 100644 --- a/lib/Doctrine/ORM/Internal/Hydration/ArrayHydrator.php +++ b/lib/Doctrine/ORM/Internal/Hydration/ArrayHydrator.php @@ -35,19 +35,19 @@ */ class ArrayHydrator extends AbstractHydrator { - /** @var array */ + /** @var array */ private $_rootAliases = []; /** @var bool */ private $_isSimpleQuery = false; - /** @var array */ + /** @var mixed[] */ private $_identifierMap = []; - /** @var array */ + /** @var mixed[] */ private $_resultPointers = []; - /** @var array */ + /** @var array */ private $_idTemplate = []; /** @var int */ @@ -259,7 +259,7 @@ protected function hydrateRowData(array $row, array &$result) * Updates the result pointer for an Entity. The result pointers point to the * last seen instance of each Entity type. This is used for graph construction. * - * @param array $coll The element. + * @param mixed[] $coll The element. * @param bool|int $index Index of the element in the collection. * @param string $dqlAlias * @param bool $oneToOne Whether it is a single-valued association or not. diff --git a/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php b/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php index e3804b3d4c8..03ea08523ac 100644 --- a/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php +++ b/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php @@ -43,25 +43,25 @@ */ class ObjectHydrator extends AbstractHydrator { - /** @var array */ + /** @var mixed[] */ private $identifierMap = []; - /** @var array */ + /** @var mixed[] */ private $resultPointers = []; - /** @var array */ + /** @var mixed[] */ private $idTemplate = []; /** @var int */ private $resultCounter = 0; - /** @var array */ + /** @var mixed[] */ private $rootAliases = []; - /** @var array */ + /** @var mixed[] */ private $initializedCollections = []; - /** @var array */ + /** @var mixed[] */ private $existingCollections = []; /** diff --git a/lib/Doctrine/ORM/Internal/HydrationCompleteHandler.php b/lib/Doctrine/ORM/Internal/HydrationCompleteHandler.php index ee5af437cb8..01185aa777e 100644 --- a/lib/Doctrine/ORM/Internal/HydrationCompleteHandler.php +++ b/lib/Doctrine/ORM/Internal/HydrationCompleteHandler.php @@ -38,7 +38,7 @@ final class HydrationCompleteHandler /** @var EntityManagerInterface */ private $em; - /** @var array[] */ + /** @var mixed[][] */ private $deferredPostLoadInvocations = []; /** diff --git a/lib/Doctrine/ORM/Mapping/Builder/AssociationBuilder.php b/lib/Doctrine/ORM/Mapping/Builder/AssociationBuilder.php index 356d196491f..b7ea9df7ad1 100644 --- a/lib/Doctrine/ORM/Mapping/Builder/AssociationBuilder.php +++ b/lib/Doctrine/ORM/Mapping/Builder/AssociationBuilder.php @@ -28,18 +28,18 @@ class AssociationBuilder /** @var ClassMetadataBuilder */ protected $builder; - /** @var array */ + /** @var mixed[] */ protected $mapping; - /** @var array|null */ + /** @var mixed[]|null */ protected $joinColumns; /** @var int */ protected $type; /** - * @param array $mapping - * @param int $type + * @param mixed[] $mapping + * @param int $type */ public function __construct(ClassMetadataBuilder $builder, array $mapping, $type) { diff --git a/lib/Doctrine/ORM/Mapping/Builder/EmbeddedBuilder.php b/lib/Doctrine/ORM/Mapping/Builder/EmbeddedBuilder.php index 94bebe1d3ef..a8ad055252d 100644 --- a/lib/Doctrine/ORM/Mapping/Builder/EmbeddedBuilder.php +++ b/lib/Doctrine/ORM/Mapping/Builder/EmbeddedBuilder.php @@ -30,11 +30,11 @@ class EmbeddedBuilder /** @var ClassMetadataBuilder */ private $builder; - /** @var array */ + /** @var mixed[] */ private $mapping; /** - * @param array $mapping + * @param mixed[] $mapping */ public function __construct(ClassMetadataBuilder $builder, array $mapping) { diff --git a/lib/Doctrine/ORM/Mapping/Builder/EntityListenerBuilder.php b/lib/Doctrine/ORM/Mapping/Builder/EntityListenerBuilder.php index dfa507d14e3..1590fdc490a 100644 --- a/lib/Doctrine/ORM/Mapping/Builder/EntityListenerBuilder.php +++ b/lib/Doctrine/ORM/Mapping/Builder/EntityListenerBuilder.php @@ -32,7 +32,7 @@ */ class EntityListenerBuilder { - /** @var array Hash-map to handle event names. */ + /** @var array Hash-map to handle event names. */ private static $events = [ Events::preRemove => true, Events::postRemove => true, diff --git a/lib/Doctrine/ORM/Mapping/Builder/FieldBuilder.php b/lib/Doctrine/ORM/Mapping/Builder/FieldBuilder.php index 84595c43376..037e103a073 100644 --- a/lib/Doctrine/ORM/Mapping/Builder/FieldBuilder.php +++ b/lib/Doctrine/ORM/Mapping/Builder/FieldBuilder.php @@ -32,7 +32,7 @@ class FieldBuilder /** @var ClassMetadataBuilder */ private $builder; - /** @var array */ + /** @var mixed[] */ private $mapping; /** @var bool */ @@ -41,14 +41,14 @@ class FieldBuilder /** @var string */ private $generatedValue; - /** @var array */ + /** @var mixed[] */ private $sequenceDef; /** @var string|null */ private $customIdGenerator; /** - * @param array $mapping + * @param mixed[] $mapping */ public function __construct(ClassMetadataBuilder $builder, array $mapping) { diff --git a/lib/Doctrine/ORM/Mapping/Builder/ManyToManyAssociationBuilder.php b/lib/Doctrine/ORM/Mapping/Builder/ManyToManyAssociationBuilder.php index 2d0ff7d088a..5c1b044c405 100644 --- a/lib/Doctrine/ORM/Mapping/Builder/ManyToManyAssociationBuilder.php +++ b/lib/Doctrine/ORM/Mapping/Builder/ManyToManyAssociationBuilder.php @@ -30,7 +30,7 @@ class ManyToManyAssociationBuilder extends OneToManyAssociationBuilder /** @var string|null */ private $joinTableName; - /** @var array */ + /** @var mixed[] */ private $inverseJoinColumns = []; /** diff --git a/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php b/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php index 14be21209a3..c788e2914ba 100644 --- a/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php +++ b/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php @@ -68,7 +68,7 @@ class ClassMetadataFactory extends AbstractClassMetadataFactory /** @var EventManager */ private $evm; - /** @var array */ + /** @var mixed[] */ private $embeddablesActiveNesting = []; /** diff --git a/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php b/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php index e78b029f95e..71005a9ac20 100644 --- a/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php +++ b/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php @@ -436,7 +436,7 @@ class ClassMetadataInfo implements ClassMetadata * * @deprecated 3.0 Remove this. * - * @var array + * @var mixed[] */ public $columnNames = []; @@ -629,7 +629,7 @@ class ClassMetadataInfo implements ClassMetadata */ public $versionField; - /** @var array */ + /** @var mixed[] */ public $cache = null; /** @@ -3273,7 +3273,7 @@ public function getQuotedTableName($platform) * * @deprecated Deprecated since version 2.3 in favor of \Doctrine\ORM\Mapping\QuoteStrategy * - * @param array $assoc + * @param mixed[] $assoc * @param AbstractPlatform $platform * * @return string diff --git a/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php b/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php index 307fb52c4bf..a60be5eebe3 100644 --- a/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php +++ b/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php @@ -30,6 +30,7 @@ use Doctrine\Persistence\Mapping\Driver\AnnotationDriver as AbstractAnnotationDriver; use ReflectionClass; use ReflectionMethod; +use ReflectionProperty; use UnexpectedValueException; use function class_exists; @@ -312,9 +313,12 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) if ($joinColumnAnnot = $this->reader->getPropertyAnnotation($property, Mapping\JoinColumn::class)) { $joinColumns[] = $this->joinColumnToArray($joinColumnAnnot); - } elseif ($joinColumnsAnnot = $this->reader->getPropertyAnnotation($property, Mapping\JoinColumns::class)) { - foreach ($joinColumnsAnnot->value as $joinColumn) { - $joinColumns[] = $this->joinColumnToArray($joinColumn); + } else { + $joinColumnsAnnot = $this->reader->getPropertyAnnotation($property, Mapping\JoinColumns::class); + if ($joinColumnsAnnot) { + foreach ($joinColumnsAnnot->value as $joinColumn) { + $joinColumns[] = $this->joinColumnToArray($joinColumn); + } } } @@ -352,87 +356,24 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) ); } elseif ($this->reader->getPropertyAnnotation($property, 'Doctrine\ORM\Id\TableGenerator')) { throw MappingException::tableIdGeneratorNotImplemented($className); - } elseif ($customGeneratorAnnot = $this->reader->getPropertyAnnotation($property, Mapping\CustomIdGenerator::class)) { - $metadata->setCustomGeneratorDefinition( - [ - 'class' => $customGeneratorAnnot->class, - ] - ); - } - } elseif ($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); - } elseif ($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); - } elseif ($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); - } elseif ($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); - } - - foreach ($joinTableAnnot->inverseJoinColumns as $joinColumn) { - $joinTable['inverseJoinColumns'][] = $this->joinColumnToArray($joinColumn); + } else { + $customGeneratorAnnot = $this->reader->getPropertyAnnotation($property, Mapping\CustomIdGenerator::class); + if ($customGeneratorAnnot) { + $metadata->setCustomGeneratorDefinition( + [ + 'class' => $customGeneratorAnnot->class, + ] + ); } } - - $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); - } elseif ($embeddedAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Embedded::class)) { - $mapping['class'] = $embeddedAnnot->class; - $mapping['columnPrefix'] = $embeddedAnnot->columnPrefix; - - $metadata->mapEmbedded($mapping); + } else { + $this->loadRelationShipMapping( + $property, + $mapping, + $metadata, + $joinColumns, + $className + ); } } @@ -540,6 +481,114 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } } + /** + * @param mixed[] $mapping + * @param mixed[] $joinColumns + */ + private function loadRelationShipMapping( + ReflectionProperty $property, + array &$mapping, + ClassMetadata $metadata, + array $joinColumns, + string $className + ): void { + $oneToOneAnnot = $this->reader->getPropertyAnnotation($property, Mapping\OneToOne::class); + if ($oneToOneAnnot) { + $idAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Id::class); + if ($idAnnot) { + $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); + + return; + } + + $oneToManyAnnot = $this->reader->getPropertyAnnotation($property, Mapping\OneToMany::class); + if ($oneToManyAnnot) { + $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); + + $orderByAnnot = $this->reader->getPropertyAnnotation($property, Mapping\OrderBy::class); + if ($orderByAnnot) { + $mapping['orderBy'] = $orderByAnnot->value; + } + + $metadata->mapOneToMany($mapping); + } + + $manyToOneAnnot = $this->reader->getPropertyAnnotation($property, Mapping\ManyToOne::class); + if ($manyToOneAnnot) { + $idAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Id::class); + if ($idAnnot) { + $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); + } + + $manyToManyAnnot = $this->reader->getPropertyAnnotation($property, Mapping\ManyToMany::class); + if ($manyToManyAnnot) { + $joinTable = []; + + $joinTableAnnot = $this->reader->getPropertyAnnotation($property, Mapping\JoinTable::class); + if ($joinTableAnnot) { + $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); + } + } + + $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); + + $orderByAnnot = $this->reader->getPropertyAnnotation($property, Mapping\OrderBy::class); + if ($orderByAnnot) { + $mapping['orderBy'] = $orderByAnnot->value; + } + + $metadata->mapManyToMany($mapping); + } + + $embeddedAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Embedded::class); + if ($embeddedAnnot) { + $mapping['class'] = $embeddedAnnot->class; + $mapping['columnPrefix'] = $embeddedAnnot->columnPrefix; + + $metadata->mapEmbedded($mapping); + } + } + /** * Attempts to resolve the fetch mode. * @@ -682,7 +731,7 @@ private function columnToArray($fieldName, Mapping\Column $column) /** * Factory method for the Annotation Driver. * - * @param array|string $paths + * @param mixed[]|string $paths * * @return AnnotationDriver */ diff --git a/lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php b/lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php index 23c16a6673d..86e5adcdd93 100644 --- a/lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php +++ b/lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php @@ -54,19 +54,19 @@ class DatabaseDriver implements MappingDriver /** @var AbstractSchemaManager */ private $_sm; - /** @var array|null */ + /** @var array|null */ private $tables = null; - /** @var array */ + /** @var mixed[] */ private $classToTableNames = []; - /** @var array */ + /** @var mixed[] */ private $manyToManyTables = []; - /** @var array */ + /** @var mixed[] */ private $classNamesForTables = []; - /** @var array */ + /** @var mixed[] */ private $fieldNamesForColumns = []; /** diff --git a/lib/Doctrine/ORM/Mapping/MappingException.php b/lib/Doctrine/ORM/Mapping/MappingException.php index 46310b8f296..d3695593270 100644 --- a/lib/Doctrine/ORM/Mapping/MappingException.php +++ b/lib/Doctrine/ORM/Mapping/MappingException.php @@ -51,7 +51,8 @@ public static function pathRequired() */ public static function identifierRequired($entityName) { - if (($parent = get_parent_class($entityName)) !== false) { + $parent = get_parent_class($entityName); + if ($parent !== false) { return new self(sprintf( 'No identifier/primary key specified for Entity "%s" sub class of "%s". Every Entity must have an identifier/primary key.', $entityName, @@ -344,7 +345,8 @@ public static function joinColumnMustPointToMappedField($className, $joinColumn) */ public static function classIsNotAValidEntityOrMappedSuperClass($className) { - if (($parent = get_parent_class($className)) !== false) { + $parent = get_parent_class($className); + if ($parent !== false) { return new self(sprintf( 'Class "%s" sub class of "%s" is not a valid entity or mapped super class.', $className, @@ -484,10 +486,12 @@ public static function fileMappingDriversRequireConfiguredDirectoryPath($path = */ public static function invalidClassInDiscriminatorMap($className, $owningClass) { - return new self( - "Entity class '$className' used in the discriminator map of class '$owningClass' " . - 'does not exist.' - ); + return new self(sprintf( + "Entity class '%s' used in the discriminator map of class '%s' " . + 'does not exist.', + $className, + $owningClass + )); } /** @@ -504,7 +508,7 @@ public static function duplicateDiscriminatorEntry($className, array $entries, a 'If the discriminator map is automatically generated you have to convert it to an explicit discriminator map now. ' . 'The entries of the current map are: @DiscriminatorMap({' . implode(', ', array_map( static function ($a, $b) { - return "'$a': '$b'"; + return sprintf("'%s': '%s'", $a, $b); }, array_keys($map), array_values($map) @@ -630,8 +634,12 @@ public static function noSingleAssociationJoinColumnFound($className, $field) */ public static function noFieldNameFoundForColumn($className, $column) { - return new self("Cannot find a field on '$className' that is mapped to column '$column'. Either the " . - 'field does not exist or an association exists but it has multiple join columns.'); + return new self(sprintf( + "Cannot find a field on '%s' that is mapped to column '%s'. Either the " . + 'field does not exist or an association exists but it has multiple join columns.', + $className, + $column + )); } /** diff --git a/lib/Doctrine/ORM/Mapping/QuoteStrategy.php b/lib/Doctrine/ORM/Mapping/QuoteStrategy.php index a1e15d18441..a45fb35ee20 100644 --- a/lib/Doctrine/ORM/Mapping/QuoteStrategy.php +++ b/lib/Doctrine/ORM/Mapping/QuoteStrategy.php @@ -34,57 +34,57 @@ interface QuoteStrategy * * @return string */ - function getColumnName($fieldName, ClassMetadata $class, AbstractPlatform $platform); + public function getColumnName($fieldName, ClassMetadata $class, AbstractPlatform $platform); /** * Gets the (possibly quoted) primary table name for safe use in an SQL statement. * * @return string */ - function getTableName(ClassMetadata $class, AbstractPlatform $platform); + public function getTableName(ClassMetadata $class, AbstractPlatform $platform); /** * Gets the (possibly quoted) sequence name for safe use in an SQL statement. * - * @param array $definition + * @param mixed[] $definition * * @return string */ - function getSequenceName(array $definition, ClassMetadata $class, AbstractPlatform $platform); + public function getSequenceName(array $definition, ClassMetadata $class, AbstractPlatform $platform); /** * Gets the (possibly quoted) name of the join table. * - * @param array $association + * @param mixed[] $association * * @return string */ - function getJoinTableName(array $association, ClassMetadata $class, AbstractPlatform $platform); + public function getJoinTableName(array $association, ClassMetadata $class, AbstractPlatform $platform); /** * Gets the (possibly quoted) join column name. * - * @param array $joinColumn + * @param mixed[] $joinColumn * * @return string */ - function getJoinColumnName(array $joinColumn, ClassMetadata $class, AbstractPlatform $platform); + public function getJoinColumnName(array $joinColumn, ClassMetadata $class, AbstractPlatform $platform); /** * Gets the (possibly quoted) join column name. * - * @param array $joinColumn + * @param mixed[] $joinColumn * * @return string */ - function getReferencedJoinColumnName(array $joinColumn, ClassMetadata $class, AbstractPlatform $platform); + public function getReferencedJoinColumnName(array $joinColumn, ClassMetadata $class, AbstractPlatform $platform); /** * Gets the (possibly quoted) identifier column names for safe use in an SQL statement. * * @return array */ - function getIdentifierColumnNames(ClassMetadata $class, AbstractPlatform $platform); + public function getIdentifierColumnNames(ClassMetadata $class, AbstractPlatform $platform); /** * Gets the column alias. @@ -94,5 +94,5 @@ function getIdentifierColumnNames(ClassMetadata $class, AbstractPlatform $platfo * * @return string */ - function getColumnAlias($columnName, $counter, AbstractPlatform $platform, ?ClassMetadata $class = null); + public function getColumnAlias($columnName, $counter, AbstractPlatform $platform, ?ClassMetadata $class = null); } diff --git a/lib/Doctrine/ORM/ORMInvalidArgumentException.php b/lib/Doctrine/ORM/ORMInvalidArgumentException.php index d9be7fc5b34..40ac74e96b3 100644 --- a/lib/Doctrine/ORM/ORMInvalidArgumentException.php +++ b/lib/Doctrine/ORM/ORMInvalidArgumentException.php @@ -220,8 +220,8 @@ public static function invalidIdentifierBindingEntity() } /** - * @param array $assoc - * @param mixed $actualValue + * @param mixed[] $assoc + * @param mixed $actualValue * * @return self */ diff --git a/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php b/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php index fa085ed8b29..0adc93e77a5 100644 --- a/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php +++ b/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php @@ -99,7 +99,7 @@ */ class BasicEntityPersister implements EntityPersister { - /** @var array */ + /** @var array */ private static $comparisonMap = [ Comparison::EQ => '= %s', Comparison::NEQ => '!= %s', @@ -156,7 +156,7 @@ class BasicEntityPersister implements EntityPersister * @see prepareInsertData($entity) * @see prepareUpdateData($entity) * - * @var array + * @var mixed[] */ protected $columnTypes = []; @@ -166,7 +166,7 @@ class BasicEntityPersister implements EntityPersister * @see prepareInsertData($entity) * @see prepareUpdateData($entity) * - * @var array + * @var mixed[] */ protected $quotedColumns = []; @@ -329,7 +329,7 @@ protected function assignDefaultVersionValue($entity, array $id) * Fetches the current version value of a versioned entity. * * @param ClassMetadata $versionedClass - * @param array $id + * @param mixed[] $id * * @return mixed */ @@ -382,7 +382,13 @@ public function update($entity) $tableName = $this->class->getTableName(); $updateData = $this->prepareUpdateData($entity); - if (! isset($updateData[$tableName]) || ! ($data = $updateData[$tableName])) { + if (! isset($updateData[$tableName])) { + return; + } + + $data = $updateData[$tableName]; + + if (! $data) { return; } @@ -402,10 +408,10 @@ public function update($entity) * 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. * - * @param object $entity The entity object being updated. - * @param string $quotedTableName The quoted name of the table to apply the UPDATE on. - * @param array $updateData The map of columns to update (column => value). - * @param bool $versioned Whether the UPDATE should be versioned. + * @param object $entity The entity object being updated. + * @param string $quotedTableName The quoted name of the table to apply the UPDATE on. + * @param mixed[] $updateData The map of columns to update (column => value). + * @param bool $versioned Whether the UPDATE should be versioned. * * @return void * @@ -613,7 +619,8 @@ protected function prepareUpdateData($entity) $result = []; $uow = $this->em->getUnitOfWork(); - if (($versioned = $this->class->isVersioned) !== false) { + $versioned = $this->class->isVersioned; + if ($versioned !== false) { $versionField = $this->class->versionField; } @@ -746,7 +753,8 @@ public function loadById(array $identifier, $entity = null) */ public function loadOneToOneEntity(array $assoc, $sourceEntity, array $identifier = []) { - if (($foundEntity = $this->em->getUnitOfWork()->tryGetById($identifier, $assoc['targetEntity'])) !== false) { + $foundEntity = $this->em->getUnitOfWork()->tryGetById($identifier, $assoc['targetEntity']); + if ($foundEntity !== false) { return $foundEntity; } @@ -913,10 +921,10 @@ public function getManyToManyCollection(array $assoc, $sourceEntity, $offset = n /** * Loads an array of entities from a given DBAL statement. * - * @param array $assoc + * @param mixed[] $assoc * @param Statement $stmt * - * @return array + * @return mixed[] */ private function loadArrayFromStatement($assoc, $stmt) { @@ -934,11 +942,11 @@ private function loadArrayFromStatement($assoc, $stmt) /** * Hydrates a collection from a given DBAL statement. * - * @param array $assoc + * @param mixed[] $assoc * @param Statement $stmt * @param PersistentCollection $coll * - * @return array + * @return mixed[] */ private function loadCollectionFromStatement($assoc, $stmt, $coll) { @@ -1306,9 +1314,9 @@ protected function getSelectColumnsSQL() /** * Gets the SQL join fragment used when selecting entities from an association. * - * @param string $field - * @param array $assoc - * @param string $alias + * @param string $field + * @param mixed[] $assoc + * @param string $alias * * @return string */ diff --git a/lib/Doctrine/ORM/Persisters/Entity/EntityPersister.php b/lib/Doctrine/ORM/Persisters/Entity/EntityPersister.php index a3b1723c2e0..85bd6eb6ccc 100644 --- a/lib/Doctrine/ORM/Persisters/Entity/EntityPersister.php +++ b/lib/Doctrine/ORM/Persisters/Entity/EntityPersister.php @@ -64,12 +64,12 @@ public function getInsertSQL(); /** * Gets the SELECT SQL to select one or more entities by a set of field criteria. * - * @param array|Criteria $criteria - * @param array|null $assoc - * @param int|null $lockMode - * @param int|null $limit - * @param int|null $offset - * @param array|null $orderBy + * @param mixed[]|Criteria $criteria + * @param mixed[]|null $assoc + * @param int|null $lockMode + * @param int|null $limit + * @param int|null $offset + * @param mixed[]|null $orderBy * * @return string */ @@ -78,7 +78,7 @@ public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit /** * Get the COUNT SQL to count entities (optionally based on a criteria) * - * @param array|Criteria $criteria + * @param mixed[]|Criteria $criteria * * @return string */ @@ -160,7 +160,7 @@ public function delete($entity); /** * Count entities (optionally filtered by a criteria) * - * @param array|Criteria $criteria + * @param mixed[]|Criteria $criteria * * @return int */ diff --git a/lib/Doctrine/ORM/Persisters/SqlValueVisitor.php b/lib/Doctrine/ORM/Persisters/SqlValueVisitor.php index 82173a98a81..b5c8cc56353 100644 --- a/lib/Doctrine/ORM/Persisters/SqlValueVisitor.php +++ b/lib/Doctrine/ORM/Persisters/SqlValueVisitor.php @@ -30,10 +30,10 @@ */ class SqlValueVisitor extends ExpressionVisitor { - /** @var array */ + /** @var mixed[] */ private $values = []; - /** @var array */ + /** @var mixed[][] */ private $types = []; /** diff --git a/lib/Doctrine/ORM/Query.php b/lib/Doctrine/ORM/Query.php index 8925a3b6e20..7f5ad59bc07 100644 --- a/lib/Doctrine/ORM/Query.php +++ b/lib/Doctrine/ORM/Query.php @@ -247,8 +247,9 @@ private function _parse() $this->_state = self::STATE_CLEAN; $this->_parsedTypes = $types; + $queryCache = $this->getQueryCacheDriver(); // Check query cache. - if (! ($this->_useQueryCache && ($queryCache = $this->getQueryCacheDriver()))) { + if (! ($this->_useQueryCache && $queryCache)) { $parser = new Parser($this); $this->_parserResult = $parser->parse(); diff --git a/lib/Doctrine/ORM/Query/AST/ArithmeticTerm.php b/lib/Doctrine/ORM/Query/AST/ArithmeticTerm.php index 60e8f08bfec..0d0e112f2f8 100644 --- a/lib/Doctrine/ORM/Query/AST/ArithmeticTerm.php +++ b/lib/Doctrine/ORM/Query/AST/ArithmeticTerm.php @@ -27,11 +27,11 @@ */ class ArithmeticTerm extends Node { - /** @var array */ + /** @var mixed[] */ public $arithmeticFactors; /** - * @param array $arithmeticFactors + * @param mixed[] $arithmeticFactors */ public function __construct(array $arithmeticFactors) { diff --git a/lib/Doctrine/ORM/Query/AST/CoalesceExpression.php b/lib/Doctrine/ORM/Query/AST/CoalesceExpression.php index f5432b3bec3..54c8ac612f5 100644 --- a/lib/Doctrine/ORM/Query/AST/CoalesceExpression.php +++ b/lib/Doctrine/ORM/Query/AST/CoalesceExpression.php @@ -27,11 +27,11 @@ */ class CoalesceExpression extends Node { - /** @var array */ + /** @var mixed[] */ public $scalarExpressions = []; /** - * @param array $scalarExpressions + * @param mixed[] $scalarExpressions */ public function __construct(array $scalarExpressions) { diff --git a/lib/Doctrine/ORM/Query/AST/ConditionalExpression.php b/lib/Doctrine/ORM/Query/AST/ConditionalExpression.php index 02d5277246b..3b80b0d7e8a 100644 --- a/lib/Doctrine/ORM/Query/AST/ConditionalExpression.php +++ b/lib/Doctrine/ORM/Query/AST/ConditionalExpression.php @@ -27,11 +27,11 @@ */ class ConditionalExpression extends Node { - /** @var array */ + /** @var mixed[] */ public $conditionalTerms = []; /** - * @param array $conditionalTerms + * @param mixed[] $conditionalTerms */ public function __construct(array $conditionalTerms) { diff --git a/lib/Doctrine/ORM/Query/AST/ConditionalTerm.php b/lib/Doctrine/ORM/Query/AST/ConditionalTerm.php index d4d712afa66..7f8da17d92f 100644 --- a/lib/Doctrine/ORM/Query/AST/ConditionalTerm.php +++ b/lib/Doctrine/ORM/Query/AST/ConditionalTerm.php @@ -27,11 +27,11 @@ */ class ConditionalTerm extends Node { - /** @var array */ + /** @var mixed[] */ public $conditionalFactors = []; /** - * @param array $conditionalFactors + * @param mixed[] $conditionalFactors */ public function __construct(array $conditionalFactors) { diff --git a/lib/Doctrine/ORM/Query/AST/FromClause.php b/lib/Doctrine/ORM/Query/AST/FromClause.php index be1bac370a4..ccdfe742827 100644 --- a/lib/Doctrine/ORM/Query/AST/FromClause.php +++ b/lib/Doctrine/ORM/Query/AST/FromClause.php @@ -27,11 +27,11 @@ */ class FromClause extends Node { - /** @var array */ + /** @var mixed[] */ public $identificationVariableDeclarations = []; /** - * @param array $identificationVariableDeclarations + * @param mixed[] $identificationVariableDeclarations */ public function __construct(array $identificationVariableDeclarations) { diff --git a/lib/Doctrine/ORM/Query/AST/Functions/DateAddFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/DateAddFunction.php index d466f25b423..e69e4e2b204 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/DateAddFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/DateAddFunction.php @@ -20,6 +20,7 @@ namespace Doctrine\ORM\Query\AST\Functions; +use Doctrine\ORM\Query\AST\Node; use Doctrine\ORM\Query\Lexer; use Doctrine\ORM\Query\Parser; use Doctrine\ORM\Query\QueryException; @@ -34,9 +35,14 @@ */ class DateAddFunction extends FunctionNode { + /** @var Node */ public $firstDateExpression = null; - public $intervalExpression = null; - public $unit = null; + + /** @var Node */ + public $intervalExpression = null; + + /** @var Node */ + public $unit = null; /** * @override diff --git a/lib/Doctrine/ORM/Query/AST/GeneralCaseExpression.php b/lib/Doctrine/ORM/Query/AST/GeneralCaseExpression.php index 5f755d77a52..7897e5202c2 100644 --- a/lib/Doctrine/ORM/Query/AST/GeneralCaseExpression.php +++ b/lib/Doctrine/ORM/Query/AST/GeneralCaseExpression.php @@ -27,15 +27,15 @@ */ class GeneralCaseExpression extends Node { - /** @var array */ + /** @var mixed[] */ public $whenClauses = []; /** @var mixed */ public $elseScalarExpression = null; /** - * @param array $whenClauses - * @param mixed $elseScalarExpression + * @param mixed[] $whenClauses + * @param mixed $elseScalarExpression */ public function __construct(array $whenClauses, $elseScalarExpression) { diff --git a/lib/Doctrine/ORM/Query/AST/GroupByClause.php b/lib/Doctrine/ORM/Query/AST/GroupByClause.php index fa126f9e0ef..5c8db4e796b 100644 --- a/lib/Doctrine/ORM/Query/AST/GroupByClause.php +++ b/lib/Doctrine/ORM/Query/AST/GroupByClause.php @@ -27,11 +27,11 @@ */ class GroupByClause extends Node { - /** @var array */ + /** @var mixed[] */ public $groupByItems = []; /** - * @param array $groupByItems + * @param mixed[] $groupByItems */ public function __construct(array $groupByItems) { diff --git a/lib/Doctrine/ORM/Query/AST/IdentificationVariableDeclaration.php b/lib/Doctrine/ORM/Query/AST/IdentificationVariableDeclaration.php index a86c75975d1..95646acddd8 100644 --- a/lib/Doctrine/ORM/Query/AST/IdentificationVariableDeclaration.php +++ b/lib/Doctrine/ORM/Query/AST/IdentificationVariableDeclaration.php @@ -33,13 +33,13 @@ class IdentificationVariableDeclaration extends Node /** @var IndexBy|null */ public $indexBy = null; - /** @var array */ + /** @var mixed[] */ public $joins = []; /** * @param RangeVariableDeclaration|null $rangeVariableDecl * @param IndexBy|null $indexBy - * @param array $joins + * @param mixed[] $joins */ public function __construct($rangeVariableDecl, $indexBy, array $joins) { diff --git a/lib/Doctrine/ORM/Query/AST/InExpression.php b/lib/Doctrine/ORM/Query/AST/InExpression.php index 8e63f9605b8..010348fe505 100644 --- a/lib/Doctrine/ORM/Query/AST/InExpression.php +++ b/lib/Doctrine/ORM/Query/AST/InExpression.php @@ -33,7 +33,7 @@ class InExpression extends Node /** @var ArithmeticExpression */ public $expression; - /** @var array */ + /** @var mixed[] */ public $literals = []; /** @var Subselect|null */ diff --git a/lib/Doctrine/ORM/Query/AST/InstanceOfExpression.php b/lib/Doctrine/ORM/Query/AST/InstanceOfExpression.php index 73630f92d24..45576e5c188 100644 --- a/lib/Doctrine/ORM/Query/AST/InstanceOfExpression.php +++ b/lib/Doctrine/ORM/Query/AST/InstanceOfExpression.php @@ -34,7 +34,7 @@ class InstanceOfExpression extends Node /** @var string */ public $identificationVariable; - /** @var array */ + /** @var mixed[] */ public $value; /** diff --git a/lib/Doctrine/ORM/Query/AST/NewObjectExpression.php b/lib/Doctrine/ORM/Query/AST/NewObjectExpression.php index 90ceabe78ca..c79e79a4506 100644 --- a/lib/Doctrine/ORM/Query/AST/NewObjectExpression.php +++ b/lib/Doctrine/ORM/Query/AST/NewObjectExpression.php @@ -30,12 +30,12 @@ class NewObjectExpression extends Node /** @var string */ public $className; - /** @var array */ + /** @var mixed[] */ public $args; /** - * @param string $className - * @param array $args + * @param string $className + * @param mixed[] $args */ public function __construct($className, array $args) { diff --git a/lib/Doctrine/ORM/Query/AST/OrderByClause.php b/lib/Doctrine/ORM/Query/AST/OrderByClause.php index d4728346511..37aacebd723 100644 --- a/lib/Doctrine/ORM/Query/AST/OrderByClause.php +++ b/lib/Doctrine/ORM/Query/AST/OrderByClause.php @@ -27,11 +27,11 @@ */ class OrderByClause extends Node { - /** @var array */ + /** @var mixed[] */ public $orderByItems = []; /** - * @param array $orderByItems + * @param mixed[] $orderByItems */ public function __construct(array $orderByItems) { diff --git a/lib/Doctrine/ORM/Query/AST/PartialObjectExpression.php b/lib/Doctrine/ORM/Query/AST/PartialObjectExpression.php index 68048797585..dcde1934228 100644 --- a/lib/Doctrine/ORM/Query/AST/PartialObjectExpression.php +++ b/lib/Doctrine/ORM/Query/AST/PartialObjectExpression.php @@ -25,12 +25,12 @@ class PartialObjectExpression extends Node /** @var string */ public $identificationVariable; - /** @var array */ + /** @var mixed[] */ public $partialFieldSet; /** - * @param string $identificationVariable - * @param array $partialFieldSet + * @param string $identificationVariable + * @param mixed[] $partialFieldSet */ public function __construct($identificationVariable, array $partialFieldSet) { diff --git a/lib/Doctrine/ORM/Query/AST/SelectClause.php b/lib/Doctrine/ORM/Query/AST/SelectClause.php index a57e2a118d4..fff751521d0 100644 --- a/lib/Doctrine/ORM/Query/AST/SelectClause.php +++ b/lib/Doctrine/ORM/Query/AST/SelectClause.php @@ -30,12 +30,12 @@ class SelectClause extends Node /** @var bool */ public $isDistinct; - /** @var array */ + /** @var mixed[] */ public $selectExpressions = []; /** - * @param array $selectExpressions - * @param bool $isDistinct + * @param mixed[] $selectExpressions + * @param bool $isDistinct */ public function __construct(array $selectExpressions, $isDistinct) { diff --git a/lib/Doctrine/ORM/Query/AST/SimpleArithmeticExpression.php b/lib/Doctrine/ORM/Query/AST/SimpleArithmeticExpression.php index 1b3355b86ea..42a4f9ec2ec 100644 --- a/lib/Doctrine/ORM/Query/AST/SimpleArithmeticExpression.php +++ b/lib/Doctrine/ORM/Query/AST/SimpleArithmeticExpression.php @@ -27,11 +27,11 @@ */ class SimpleArithmeticExpression extends Node { - /** @var array */ + /** @var mixed[] */ public $arithmeticTerms = []; /** - * @param array $arithmeticTerms + * @param mixed[] $arithmeticTerms */ public function __construct(array $arithmeticTerms) { diff --git a/lib/Doctrine/ORM/Query/AST/SimpleCaseExpression.php b/lib/Doctrine/ORM/Query/AST/SimpleCaseExpression.php index 5d1861c0f57..3f7b5279c8c 100644 --- a/lib/Doctrine/ORM/Query/AST/SimpleCaseExpression.php +++ b/lib/Doctrine/ORM/Query/AST/SimpleCaseExpression.php @@ -30,7 +30,7 @@ class SimpleCaseExpression extends Node /** @var PathExpression */ public $caseOperand = null; - /** @var array */ + /** @var mixed[] */ public $simpleWhenClauses = []; /** @var mixed */ @@ -38,7 +38,7 @@ class SimpleCaseExpression extends Node /** * @param PathExpression $caseOperand - * @param array $simpleWhenClauses + * @param mixed[] $simpleWhenClauses * @param mixed $elseScalarExpression */ public function __construct($caseOperand, array $simpleWhenClauses, $elseScalarExpression) diff --git a/lib/Doctrine/ORM/Query/AST/SubselectFromClause.php b/lib/Doctrine/ORM/Query/AST/SubselectFromClause.php index 8053406ed0e..755416bbca8 100644 --- a/lib/Doctrine/ORM/Query/AST/SubselectFromClause.php +++ b/lib/Doctrine/ORM/Query/AST/SubselectFromClause.php @@ -27,11 +27,11 @@ */ class SubselectFromClause extends Node { - /** @var array */ + /** @var mixed[] */ public $identificationVariableDeclarations = []; /** - * @param array $identificationVariableDeclarations + * @param mixed[] $identificationVariableDeclarations */ public function __construct(array $identificationVariableDeclarations) { diff --git a/lib/Doctrine/ORM/Query/AST/UpdateClause.php b/lib/Doctrine/ORM/Query/AST/UpdateClause.php index 883c2231bbb..c8e134eba9c 100644 --- a/lib/Doctrine/ORM/Query/AST/UpdateClause.php +++ b/lib/Doctrine/ORM/Query/AST/UpdateClause.php @@ -33,12 +33,12 @@ class UpdateClause extends Node /** @var string */ public $aliasIdentificationVariable; - /** @var array */ + /** @var mixed[] */ public $updateItems = []; /** - * @param string $abstractSchemaName - * @param array $updateItems + * @param string $abstractSchemaName + * @param mixed[] $updateItems */ public function __construct($abstractSchemaName, array $updateItems) { diff --git a/lib/Doctrine/ORM/Query/Exec/MultiTableUpdateExecutor.php b/lib/Doctrine/ORM/Query/Exec/MultiTableUpdateExecutor.php index 3dbb34f836a..5f1526d8642 100644 --- a/lib/Doctrine/ORM/Query/Exec/MultiTableUpdateExecutor.php +++ b/lib/Doctrine/ORM/Query/Exec/MultiTableUpdateExecutor.php @@ -49,7 +49,7 @@ class MultiTableUpdateExecutor extends AbstractSqlExecutor /** @var string */ private $_insertSql; - /** @var array */ + /** @var mixed[] */ private $_sqlParameters = []; /** @var int */ diff --git a/lib/Doctrine/ORM/Query/Expr/Andx.php b/lib/Doctrine/ORM/Query/Expr/Andx.php index de6b1bc6507..fe706f419be 100644 --- a/lib/Doctrine/ORM/Query/Expr/Andx.php +++ b/lib/Doctrine/ORM/Query/Expr/Andx.php @@ -30,7 +30,7 @@ class Andx extends Composite /** @var string */ protected $separator = ' AND '; - /** @var array */ + /** @var string[] */ protected $allowedClasses = [ Comparison::class, Func::class, diff --git a/lib/Doctrine/ORM/Query/Expr/Base.php b/lib/Doctrine/ORM/Query/Expr/Base.php index b25c649ca07..6495159c934 100644 --- a/lib/Doctrine/ORM/Query/Expr/Base.php +++ b/lib/Doctrine/ORM/Query/Expr/Base.php @@ -27,6 +27,7 @@ use function implode; use function in_array; use function is_string; +use function sprintf; /** * Abstract base Expr class for building DQL parts. @@ -44,10 +45,10 @@ abstract class Base /** @var string */ protected $postSeparator = ')'; - /** @var array */ + /** @var string[] */ protected $allowedClasses = []; - /** @var array */ + /** @var mixed[] */ protected $parts = []; /** @@ -87,7 +88,10 @@ public function add($arg) $class = get_class($arg); if (! in_array($class, $this->allowedClasses)) { - throw new InvalidArgumentException("Expression of type '$class' not allowed in this context."); + throw new InvalidArgumentException(sprintf( + "Expression of type '%s' not allowed in this context.", + $class + )); } } diff --git a/lib/Doctrine/ORM/Query/Expr/Func.php b/lib/Doctrine/ORM/Query/Expr/Func.php index 6ae37bf24ff..740d84496ac 100644 --- a/lib/Doctrine/ORM/Query/Expr/Func.php +++ b/lib/Doctrine/ORM/Query/Expr/Func.php @@ -32,7 +32,7 @@ class Func /** @var string */ protected $name; - /** @var array */ + /** @var mixed[] */ protected $arguments; /** diff --git a/lib/Doctrine/ORM/Query/Expr/OrderBy.php b/lib/Doctrine/ORM/Query/Expr/OrderBy.php index 258db2c025d..c4a572badcd 100644 --- a/lib/Doctrine/ORM/Query/Expr/OrderBy.php +++ b/lib/Doctrine/ORM/Query/Expr/OrderBy.php @@ -39,10 +39,10 @@ class OrderBy /** @var string */ protected $postSeparator = ''; - /** @var array */ + /** @var string[] */ protected $allowedClasses = []; - /** @var array */ + /** @var mixed[] */ protected $parts = []; /** diff --git a/lib/Doctrine/ORM/Query/Expr/Orx.php b/lib/Doctrine/ORM/Query/Expr/Orx.php index 0b847353259..286799c0062 100644 --- a/lib/Doctrine/ORM/Query/Expr/Orx.php +++ b/lib/Doctrine/ORM/Query/Expr/Orx.php @@ -30,7 +30,7 @@ class Orx extends Composite /** @var string */ protected $separator = ' OR '; - /** @var array */ + /** @var string[] */ protected $allowedClasses = [ Comparison::class, Func::class, diff --git a/lib/Doctrine/ORM/Query/Expr/Select.php b/lib/Doctrine/ORM/Query/Expr/Select.php index 495fa7e0853..9a1d051550b 100644 --- a/lib/Doctrine/ORM/Query/Expr/Select.php +++ b/lib/Doctrine/ORM/Query/Expr/Select.php @@ -33,7 +33,7 @@ class Select extends Base /** @var string */ protected $postSeparator = ''; - /** @var array */ + /** @var string[] */ protected $allowedClasses = [Func::class]; /** diff --git a/lib/Doctrine/ORM/Query/Filter/SQLFilter.php b/lib/Doctrine/ORM/Query/Filter/SQLFilter.php index 3c7dcdbf548..ce4f09cdefd 100644 --- a/lib/Doctrine/ORM/Query/Filter/SQLFilter.php +++ b/lib/Doctrine/ORM/Query/Filter/SQLFilter.php @@ -120,11 +120,7 @@ final public function getParameter($name) */ final public function hasParameter($name) { - if (! isset($this->parameters[$name])) { - return false; - } - - return true; + return isset($this->parameters[$name]); } /** diff --git a/lib/Doctrine/ORM/Query/Parser.php b/lib/Doctrine/ORM/Query/Parser.php index 8ed2af6ebb0..6c3099391a4 100644 --- a/lib/Doctrine/ORM/Query/Parser.php +++ b/lib/Doctrine/ORM/Query/Parser.php @@ -506,8 +506,8 @@ public function syntaxError($expected = '', $token = null) $tokenPos = $token['position'] ?? '-1'; $message = "line 0, col {$tokenPos}: Error: "; - $message .= $expected !== '' ? "Expected {$expected}, got " : 'Unexpected '; - $message .= $this->lexer->lookahead === null ? 'end of string.' : "'{$token['value']}'"; + $message .= $expected !== '' ? sprintf('Expected %s, got ', $expected) : 'Unexpected '; + $message .= $this->lexer->lookahead === null ? 'end of string.' : sprintf("'%s'", $token['value']); throw QueryException::syntaxError($message, QueryException::dqlError($this->query->getDQL())); } @@ -646,7 +646,7 @@ private function processDeferredIdentificationVariables() // Check if IdentificationVariable exists in queryComponents if (! isset($this->queryComponents[$identVariable])) { $this->semanticalError( - "'$identVariable' is not defined.", + sprintf("'%s' is not defined.", $identVariable), $deferredItem['token'] ); } @@ -656,7 +656,7 @@ private function processDeferredIdentificationVariables() // Check if queryComponent points to an AbstractSchemaName or a ResultVariable if (! isset($qComp['metadata'])) { $this->semanticalError( - "'$identVariable' does not point to a Class.", + sprintf("'%s' does not point to a Class.", $identVariable), $deferredItem['token'] ); } @@ -664,7 +664,7 @@ private function processDeferredIdentificationVariables() // Validate if identification variable nesting level is lower or equal than the current one if ($qComp['nestingLevel'] > $deferredItem['nestingLevel']) { $this->semanticalError( - "'$identVariable' is used outside the scope of its declaration.", + sprintf("'%s' is used outside the scope of its declaration.", $identVariable), $deferredItem['token'] ); } @@ -743,10 +743,11 @@ private function processDeferredPartialObjectExpressions() continue; } - $this->semanticalError( - "There is no mapped field named '$field' on class " . $class->name . '.', - $deferredItem['token'] - ); + $this->semanticalError(sprintf( + "There is no mapped field named '%s' on class %s.", + $field, + $class->name + ), $deferredItem['token']); } if (array_intersect($class->identifier, $expr->partialFieldSet) !== $class->identifier) { @@ -772,7 +773,7 @@ private function processDeferredResultVariables() // Check if ResultVariable exists in queryComponents if (! isset($this->queryComponents[$resultVariable])) { $this->semanticalError( - "'$resultVariable' is not defined.", + sprintf("'%s' is not defined.", $resultVariable), $deferredItem['token'] ); } @@ -782,7 +783,7 @@ private function processDeferredResultVariables() // Check if queryComponent points to an AbstractSchemaName or a ResultVariable if (! isset($qComp['resultVariable'])) { $this->semanticalError( - "'$resultVariable' does not point to a ResultVariable.", + sprintf("'%s' does not point to a ResultVariable.", $resultVariable), $deferredItem['token'] ); } @@ -790,7 +791,7 @@ private function processDeferredResultVariables() // Validate if identification variable nesting level is lower or equal than the current one if ($qComp['nestingLevel'] > $deferredItem['nestingLevel']) { $this->semanticalError( - "'$resultVariable' is used outside the scope of its declaration.", + sprintf("'%s' is used outside the scope of its declaration.", $resultVariable), $deferredItem['token'] ); } diff --git a/lib/Doctrine/ORM/Query/QueryExpressionVisitor.php b/lib/Doctrine/ORM/Query/QueryExpressionVisitor.php index bb2901cf540..71f8db759fa 100644 --- a/lib/Doctrine/ORM/Query/QueryExpressionVisitor.php +++ b/lib/Doctrine/ORM/Query/QueryExpressionVisitor.php @@ -37,7 +37,7 @@ */ class QueryExpressionVisitor extends ExpressionVisitor { - /** @var array */ + /** @var array */ private static $operatorMap = [ Comparison::GT => Expr\Comparison::GT, Comparison::GTE => Expr\Comparison::GTE, @@ -45,19 +45,19 @@ class QueryExpressionVisitor extends ExpressionVisitor Comparison::LTE => Expr\Comparison::LTE, ]; - /** @var array */ + /** @var mixed[] */ private $queryAliases; /** @var Expr */ private $expr; - /** @var array */ + /** @var mixed[] */ private $parameters = []; /** * Constructor * - * @param array $queryAliases + * @param mixed[] $queryAliases */ public function __construct($queryAliases) { diff --git a/lib/Doctrine/ORM/Query/ResultSetMappingBuilder.php b/lib/Doctrine/ORM/Query/ResultSetMappingBuilder.php index 8fd3502b5a3..8df30e6a8be 100644 --- a/lib/Doctrine/ORM/Query/ResultSetMappingBuilder.php +++ b/lib/Doctrine/ORM/Query/ResultSetMappingBuilder.php @@ -28,6 +28,7 @@ use function explode; use function in_array; +use function sprintf; use function strpos; use function strtolower; @@ -146,7 +147,10 @@ protected function addAllClassFields($class, $alias, $columnAliasMap = []) $columnAlias = $platform->getSQLResultCasing($columnAliasMap[$columnName]); if (isset($this->fieldMappings[$columnAlias])) { - throw new InvalidArgumentException("The column '$columnName' conflicts with another column in the mapper."); + throw new InvalidArgumentException(sprintf( + "The column '%s' conflicts with another column in the mapper.", + $columnName + )); } $this->addFieldResult($alias, $columnAlias, $propertyName); @@ -163,7 +167,10 @@ protected function addAllClassFields($class, $alias, $columnAliasMap = []) $columnType = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em); if (isset($this->metaMappings[$columnAlias])) { - throw new InvalidArgumentException("The column '$columnAlias' conflicts with another column in the mapper."); + throw new InvalidArgumentException(sprintf( + "The column '%s' conflicts with another column in the mapper.", + $columnAlias + )); } $this->addMetaResult($alias, $columnAlias, $columnName, $isIdentifier, $columnType); @@ -248,7 +255,7 @@ private function getColumnAliasMap($className, $mode, array $customRenameColumns /** * Adds the mappings of the results of native SQL queries to the result set. * - * @param array $queryMapping + * @param mixed[] $queryMapping * * @return ResultSetMappingBuilder */ @@ -356,8 +363,8 @@ public function addNamedNativeQueryResultSetMapping(ClassMetadataInfo $class, $r /** * Adds the entity result mapping of the results of native SQL queries to the result set. * - * @param array $entityMapping - * @param string $alias + * @param mixed[] $entityMapping + * @param string $alias * * @return self * diff --git a/lib/Doctrine/ORM/Query/SqlWalker.php b/lib/Doctrine/ORM/Query/SqlWalker.php index 2de1d5c2b6d..bdd5ed864e7 100644 --- a/lib/Doctrine/ORM/Query/SqlWalker.php +++ b/lib/Doctrine/ORM/Query/SqlWalker.php @@ -116,7 +116,7 @@ class SqlWalker implements TreeWalker /** @var Query */ private $query; - /** @var array */ + /** @var mixed[] */ private $tableAliasMap = []; /** @@ -551,7 +551,8 @@ public function walkSelectStatement(AST\SelectStatement $AST) $sql .= $this->walkOrderByClause($AST->orderByClause); } - if (! $AST->orderByClause && ($orderBySql = $this->_generateOrderedCollectionOrderByItems())) { + $orderBySql = $this->_generateOrderedCollectionOrderByItems(); + if (! $AST->orderByClause && $orderBySql) { $sql .= ' ORDER BY ' . $orderBySql; } diff --git a/lib/Doctrine/ORM/Query/TreeWalker.php b/lib/Doctrine/ORM/Query/TreeWalker.php index 7e66e79e445..a8ab903912f 100644 --- a/lib/Doctrine/ORM/Query/TreeWalker.php +++ b/lib/Doctrine/ORM/Query/TreeWalker.php @@ -32,7 +32,7 @@ interface TreeWalker * * @param AbstractQuery $query The parsed Query. * @param ParserResult $parserResult The result of the parsing process. - * @param array $queryComponents The query components (symbol table). + * @param mixed[] $queryComponents The query components (symbol table). */ public function __construct($query, $parserResult, array $queryComponents); diff --git a/lib/Doctrine/ORM/QueryBuilder.php b/lib/Doctrine/ORM/QueryBuilder.php index 4e1d50b4f0f..f5da1fa4150 100644 --- a/lib/Doctrine/ORM/QueryBuilder.php +++ b/lib/Doctrine/ORM/QueryBuilder.php @@ -580,7 +580,7 @@ public function setParameter($key, $value, $type = null) * ))); * * - * @param ArrayCollection|array $parameters The query parameters to set. + * @param ArrayCollection|mixed[] $parameters The query parameters to set. * * @return self */ diff --git a/lib/Doctrine/ORM/Tools/AttachEntityListenersListener.php b/lib/Doctrine/ORM/Tools/AttachEntityListenersListener.php index 74e5a4cb804..1d1c0c5bc55 100644 --- a/lib/Doctrine/ORM/Tools/AttachEntityListenersListener.php +++ b/lib/Doctrine/ORM/Tools/AttachEntityListenersListener.php @@ -29,7 +29,7 @@ */ class AttachEntityListenersListener { - /** @var array[] */ + /** @var mixed[][] */ private $entityListeners = []; /** diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommand.php index 1c5b11f9609..303a6c58c3e 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommand.php @@ -137,7 +137,7 @@ protected function execute(InputInterface $input, OutputInterface $output) } /** - * @param array $fromPaths + * @param mixed[] $fromPaths * @param string $destPath * @param string $toType * @param int $numSpaces diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ConvertMappingCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ConvertMappingCommand.php index 6fa9f513ae0..5b86ae70190 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ConvertMappingCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ConvertMappingCommand.php @@ -121,7 +121,8 @@ protected function execute(InputInterface $input, OutputInterface $output) $metadata = MetadataFilter::filter($metadata, $input->getOption('filter')); // Process destination directory - if (! is_dir($destPath = $input->getArgument('dest-path'))) { + $destPath = $input->getArgument('dest-path'); + if (! is_dir($destPath)) { mkdir($destPath, 0775, true); } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/AbstractCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/AbstractCommand.php index 5e8c0f19c1e..5d5f7b2d9ef 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/AbstractCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/AbstractCommand.php @@ -37,7 +37,7 @@ abstract class AbstractCommand extends Command { /** - * @param array $metadatas + * @param mixed[] $metadatas * * @return int|null Null or 0 if everything went fine, or an error code. */ diff --git a/lib/Doctrine/ORM/Tools/Console/ConsoleRunner.php b/lib/Doctrine/ORM/Tools/Console/ConsoleRunner.php index fd265c8b102..3703d97df9b 100644 --- a/lib/Doctrine/ORM/Tools/Console/ConsoleRunner.php +++ b/lib/Doctrine/ORM/Tools/Console/ConsoleRunner.php @@ -62,7 +62,7 @@ public static function run(HelperSet $helperSet, array $commands = []): void * Creates a console application with the given helperset and * optional commands. * - * @param array $commands + * @param SymfonyCommand[] $commands * * @throws OutOfBoundsException */ diff --git a/lib/Doctrine/ORM/Tools/Console/MetadataFilter.php b/lib/Doctrine/ORM/Tools/Console/MetadataFilter.php index 78c41e6f60e..a5cde52943a 100644 --- a/lib/Doctrine/ORM/Tools/Console/MetadataFilter.php +++ b/lib/Doctrine/ORM/Tools/Console/MetadataFilter.php @@ -38,7 +38,7 @@ */ class MetadataFilter extends FilterIterator implements Countable { - /** @var array */ + /** @var mixed[] */ private $filter = []; /** @@ -57,7 +57,7 @@ public static function filter(array $metadatas, $filter) } /** - * @param array|string $filter + * @param mixed[]|string $filter */ public function __construct(ArrayIterator $metadata, $filter) { diff --git a/lib/Doctrine/ORM/Tools/ConvertDoctrine1Schema.php b/lib/Doctrine/ORM/Tools/ConvertDoctrine1Schema.php index f48e9bbaab5..7c5bdcf4feb 100644 --- a/lib/Doctrine/ORM/Tools/ConvertDoctrine1Schema.php +++ b/lib/Doctrine/ORM/Tools/ConvertDoctrine1Schema.php @@ -44,10 +44,10 @@ */ class ConvertDoctrine1Schema { - /** @var array */ + /** @var mixed[] */ private $from; - /** @var array */ + /** @var array */ private $legacyTypeMap = [ // TODO: This list may need to be updated 'clob' => 'text', @@ -115,8 +115,8 @@ private function convertToClassMetadataInfo($className, $mappingInformation) } /** - * @param string $className - * @param array $model + * @param string $className + * @param mixed[] $model * * @return void */ @@ -135,8 +135,8 @@ private function convertTableName($className, array $model, ClassMetadataInfo $m } /** - * @param string $className - * @param array $model + * @param string $className + * @param mixed[] $model * * @return void */ @@ -167,9 +167,9 @@ private function convertColumns($className, array $model, ClassMetadataInfo $met } /** - * @param string $className - * @param string $name - * @param string|array $column + * @param string $className + * @param string $name + * @param string|mixed[] $column * * @return mixed[] * @@ -257,8 +257,8 @@ private function convertColumn($className, $name, $column, ClassMetadataInfo $me } /** - * @param string $className - * @param array $model + * @param string $className + * @param mixed[] $model * * @return void */ @@ -279,8 +279,8 @@ private function convertIndexes($className, array $model, ClassMetadataInfo $met } /** - * @param string $className - * @param array $model + * @param string $className + * @param mixed[] $model * * @return void */ diff --git a/lib/Doctrine/ORM/Tools/EntityGenerator.php b/lib/Doctrine/ORM/Tools/EntityGenerator.php index 3e1dce35f82..cdfe5ad0478 100644 --- a/lib/Doctrine/ORM/Tools/EntityGenerator.php +++ b/lib/Doctrine/ORM/Tools/EntityGenerator.php @@ -134,7 +134,7 @@ class EntityGenerator */ protected $isNew = true; - /** @var array */ + /** @var mixed[] */ protected $staticReflection = []; /** @@ -1487,7 +1487,7 @@ protected function generateJoinColumnAnnotation(array $joinColumn) } /** - * @param array $associationMapping + * @param mixed[] $associationMapping * * @return string */ @@ -1653,7 +1653,7 @@ protected function generateAssociationMappingPropertyDocBlock(array $association } /** - * @param array $fieldMapping + * @param mixed[] $fieldMapping * * @return string */ diff --git a/lib/Doctrine/ORM/Tools/Export/ClassMetadataExporter.php b/lib/Doctrine/ORM/Tools/Export/ClassMetadataExporter.php index dae2d2e07bc..5853a191317 100644 --- a/lib/Doctrine/ORM/Tools/Export/ClassMetadataExporter.php +++ b/lib/Doctrine/ORM/Tools/Export/ClassMetadataExporter.php @@ -34,7 +34,7 @@ */ class ClassMetadataExporter { - /** @var array */ + /** @var array */ private static $_exporterDrivers = [ 'xml' => Driver\XmlExporter::class, 'yaml' => Driver\YamlExporter::class, diff --git a/lib/Doctrine/ORM/Tools/Export/Driver/AbstractExporter.php b/lib/Doctrine/ORM/Tools/Export/Driver/AbstractExporter.php index d83673b4b2e..d3725466ea6 100644 --- a/lib/Doctrine/ORM/Tools/Export/Driver/AbstractExporter.php +++ b/lib/Doctrine/ORM/Tools/Export/Driver/AbstractExporter.php @@ -44,7 +44,7 @@ */ abstract class AbstractExporter { - /** @var array */ + /** @var mixed[] */ protected $_metadata = []; /** @var string|null */ diff --git a/lib/Doctrine/ORM/Tools/Export/Driver/PhpExporter.php b/lib/Doctrine/ORM/Tools/Export/Driver/PhpExporter.php index f1d19dd54e0..29027689f7e 100644 --- a/lib/Doctrine/ORM/Tools/Export/Driver/PhpExporter.php +++ b/lib/Doctrine/ORM/Tools/Export/Driver/PhpExporter.php @@ -98,8 +98,11 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) $lines[] = '$metadata->mapField(' . $this->_varExport($fieldMapping) . ');'; } - if (! $metadata->isIdentifierComposite && $generatorType = $this->_getIdGeneratorTypeString($metadata->generatorType)) { - $lines[] = '$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_' . $generatorType . ');'; + if (! $metadata->isIdentifierComposite) { + $generatorType = $this->_getIdGeneratorTypeString($metadata->generatorType); + if ($generatorType) { + $lines[] = '$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_' . $generatorType . ');'; + } } foreach ($metadata->associationMappings as $associationMapping) { diff --git a/lib/Doctrine/ORM/Tools/Export/Driver/XmlExporter.php b/lib/Doctrine/ORM/Tools/Export/Driver/XmlExporter.php index 3585d8e0e27..88aaae95105 100644 --- a/lib/Doctrine/ORM/Tools/Export/Driver/XmlExporter.php +++ b/lib/Doctrine/ORM/Tools/Export/Driver/XmlExporter.php @@ -151,8 +151,11 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) } } - if (! $metadata->isIdentifierComposite && $idGeneratorType = $this->_getIdGeneratorTypeString($metadata->generatorType)) { - $id[$metadata->getSingleIdentifierFieldName()]['generator']['strategy'] = $idGeneratorType; + if (! $metadata->isIdentifierComposite) { + $idGeneratorType = $this->_getIdGeneratorTypeString($metadata->generatorType); + if ($idGeneratorType) { + $id[$metadata->getSingleIdentifierFieldName()]['generator']['strategy'] = $idGeneratorType; + } } if ($id) { @@ -408,7 +411,7 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) /** * Exports (nested) option elements. * - * @param array $options + * @param mixed[] $options */ private function exportTableOptions(SimpleXMLElement $parentXml, array $options): void { @@ -465,8 +468,14 @@ private function processEntityListeners(ClassMetadataInfo $metadata, SimpleXMLEl $this->generateEntityListenerXml($metadata, $entityListenersXmlMap, $entityListenersXml); } - private function generateEntityListenerXml(ClassMetadataInfo $metadata, array $entityListenersXmlMap, SimpleXMLElement $entityListenersXml): void - { + /** + * @param mixed[] $entityListenersXmlMap + */ + private function generateEntityListenerXml( + ClassMetadataInfo $metadata, + array $entityListenersXmlMap, + SimpleXMLElement $entityListenersXml + ): void { foreach ($metadata->entityListeners as $event => $entityListenerConfig) { foreach ($entityListenerConfig as $entityListener) { $entityListenerXml = $this->addClassToMapIfExists( @@ -482,8 +491,15 @@ private function generateEntityListenerXml(ClassMetadataInfo $metadata, array $e } } - private function addClassToMapIfExists(array $entityListenersXmlMap, array $entityListener, SimpleXMLElement $entityListenersXml): SimpleXMLElement - { + /** + * @param mixed[] $entityListenersXmlMap + * @param mixed[] $entityListener + */ + private function addClassToMapIfExists( + array $entityListenersXmlMap, + array $entityListener, + SimpleXMLElement $entityListenersXml + ): SimpleXMLElement { if (isset($entityListenersXmlMap[$entityListener['class']])) { return $entityListenersXmlMap[$entityListener['class']]; } diff --git a/lib/Doctrine/ORM/Tools/Export/Driver/YamlExporter.php b/lib/Doctrine/ORM/Tools/Export/Driver/YamlExporter.php index 13babe6a841..3877e8ee131 100644 --- a/lib/Doctrine/ORM/Tools/Export/Driver/YamlExporter.php +++ b/lib/Doctrine/ORM/Tools/Export/Driver/YamlExporter.php @@ -114,8 +114,11 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) $fieldMappings[$name] = $fieldMapping; } - if (! $metadata->isIdentifierComposite && $idGeneratorType = $this->_getIdGeneratorTypeString($metadata->generatorType)) { - $ids[$metadata->getSingleIdentifierFieldName()]['generator']['strategy'] = $idGeneratorType; + if (! $metadata->isIdentifierComposite) { + $idGeneratorType = $this->_getIdGeneratorTypeString($metadata->generatorType); + if ($idGeneratorType) { + $ids[$metadata->getSingleIdentifierFieldName()]['generator']['strategy'] = $idGeneratorType; + } } $array['id'] = $ids; @@ -228,8 +231,8 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) * 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 int $inline [optional] The level where you switch to inline YAML + * @param mixed[] $array PHP array + * @param int $inline [optional] The level where you switch to inline YAML * * @return string A YAML string representing the original PHP array */ diff --git a/lib/Doctrine/ORM/Tools/Pagination/CountOutputWalker.php b/lib/Doctrine/ORM/Tools/Pagination/CountOutputWalker.php index 93c4cbf4886..ded184d19c4 100644 --- a/lib/Doctrine/ORM/Tools/Pagination/CountOutputWalker.php +++ b/lib/Doctrine/ORM/Tools/Pagination/CountOutputWalker.php @@ -52,7 +52,7 @@ class CountOutputWalker extends SqlWalker /** @var ResultSetMapping */ private $rsm; - /** @var array */ + /** @var mixed[] */ private $queryComponents; /** @@ -62,7 +62,7 @@ class CountOutputWalker extends SqlWalker * * @param Query $query * @param ParserResult $parserResult - * @param array $queryComponents + * @param mixed[] $queryComponents */ public function __construct($query, $parserResult, array $queryComponents) { diff --git a/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryOutputWalker.php b/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryOutputWalker.php index 3605bfb7b69..69114d3703b 100644 --- a/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryOutputWalker.php +++ b/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryOutputWalker.php @@ -72,7 +72,7 @@ class LimitSubqueryOutputWalker extends SqlWalker /** @var ResultSetMapping */ private $rsm; - /** @var array */ + /** @var mixed[] */ private $queryComponents; /** @var int */ @@ -91,7 +91,7 @@ class LimitSubqueryOutputWalker extends SqlWalker */ private $quoteStrategy; - /** @var array */ + /** @var mixed[] */ private $orderByPathExpressions = []; /** @@ -107,7 +107,7 @@ class LimitSubqueryOutputWalker extends SqlWalker * * @param Query $query * @param ParserResult $parserResult - * @param array $queryComponents + * @param mixed[] $queryComponents */ public function __construct($query, $parserResult, array $queryComponents) { @@ -361,7 +361,7 @@ private function addMissingItemsFromOrderByToSelect(SelectStatement $AST) /** * Generates new SQL for statements with an order by clause * - * @param array $sqlIdentifier + * @param mixed[] $sqlIdentifier */ private function preserveSqlOrdering( array $sqlIdentifier, @@ -385,7 +385,7 @@ private function preserveSqlOrdering( /** * Generates a new SQL statement for the inner query to keep the correct sorting * - * @param array $identifiers + * @param mixed[] $identifiers */ private function recreateInnerSql( OrderByClause $orderByClause, diff --git a/lib/Doctrine/ORM/Tools/ResolveTargetEntityListener.php b/lib/Doctrine/ORM/Tools/ResolveTargetEntityListener.php index 29c6a3b3dcc..a25af243034 100644 --- a/lib/Doctrine/ORM/Tools/ResolveTargetEntityListener.php +++ b/lib/Doctrine/ORM/Tools/ResolveTargetEntityListener.php @@ -39,7 +39,7 @@ */ class ResolveTargetEntityListener implements EventSubscriber { - /** @var array[] indexed by original entity name */ + /** @var mixed[][] indexed by original entity name */ private $resolveTargetEntities = []; /** @@ -110,7 +110,7 @@ public function loadClassMetadata(LoadClassMetadataEventArgs $args) /** * @param ClassMetadataInfo $classMetadata - * @param array $mapping + * @param mixed[] $mapping * * @return void */ diff --git a/lib/Doctrine/ORM/Tools/SchemaTool.php b/lib/Doctrine/ORM/Tools/SchemaTool.php index f9037c25d6b..2d0e7a9c708 100644 --- a/lib/Doctrine/ORM/Tools/SchemaTool.php +++ b/lib/Doctrine/ORM/Tools/SchemaTool.php @@ -869,9 +869,9 @@ public function getDropSchemaSQL(array $classes) * Updates the database schema of the given classes by comparing the ClassMetadata * instances to the current database schema that is inspected. * - * @param array $classes - * @param bool $saveMode If TRUE, only performs a partial update - * without dropping assets which are scheduled for deletion. + * @param mixed[] $classes + * @param bool $saveMode If TRUE, only performs a partial update + * without dropping assets which are scheduled for deletion. * * @return void */ @@ -889,9 +889,9 @@ public function updateSchema(array $classes, $saveMode = false) * Gets the sequence of SQL statements that need to be performed in order * to bring the given class mappings in-synch with the relational schema. * - * @param array $classes The classes to consider. - * @param bool $saveMode If TRUE, only generates SQL for a partial update - * that does not include SQL for dropping assets which are scheduled for deletion. + * @param mixed[] $classes The classes to consider. + * @param bool $saveMode If TRUE, only generates SQL for a partial update + * that does not include SQL for dropping assets which are scheduled for deletion. * * @return string[] The sequence of SQL statements. */ diff --git a/lib/Doctrine/ORM/Tools/Setup.php b/lib/Doctrine/ORM/Tools/Setup.php index 1a47c402544..954ff003404 100644 --- a/lib/Doctrine/ORM/Tools/Setup.php +++ b/lib/Doctrine/ORM/Tools/Setup.php @@ -67,10 +67,10 @@ public static function registerAutoloadDirectory($directory) /** * Creates a configuration with an annotation metadata driver. * - * @param array $paths - * @param bool $isDevMode - * @param string $proxyDir - * @param bool $useSimpleAnnotationReader + * @param mixed[] $paths + * @param bool $isDevMode + * @param string $proxyDir + * @param bool $useSimpleAnnotationReader * * @return Configuration */ @@ -85,9 +85,9 @@ public static function createAnnotationMetadataConfiguration(array $paths, $isDe /** * Creates a configuration with a xml metadata driver. * - * @param array $paths - * @param bool $isDevMode - * @param string $proxyDir + * @param mixed[] $paths + * @param bool $isDevMode + * @param string $proxyDir * * @return Configuration */ @@ -102,9 +102,9 @@ public static function createXMLMetadataConfiguration(array $paths, $isDevMode = /** * Creates a configuration with a yaml metadata driver. * - * @param array $paths - * @param bool $isDevMode - * @param string $proxyDir + * @param mixed[] $paths + * @param bool $isDevMode + * @param string $proxyDir * * @return Configuration */ diff --git a/lib/Doctrine/ORM/UnitOfWork.php b/lib/Doctrine/ORM/UnitOfWork.php index ed4566f08a0..4fbe3636f71 100644 --- a/lib/Doctrine/ORM/UnitOfWork.php +++ b/lib/Doctrine/ORM/UnitOfWork.php @@ -340,7 +340,7 @@ public function __construct(EntityManagerInterface $em) * 4) All collection updates * 5) All entity deletions * - * @param object|array|null $entity + * @param object|mixed[]|null $entity * * @return void * @@ -2118,9 +2118,9 @@ public function detach($entity) /** * Executes a detach operation on the given entity. * - * @param object $entity - * @param array $visited - * @param bool $noCascade if true, don't cascade detach operation. + * @param object $entity + * @param mixed[] $visited + * @param bool $noCascade if true, don't cascade detach operation. * * @return void */ @@ -3653,7 +3653,7 @@ private function clearEntityInsertionsForEntityName($entityName) * * @return mixed the identifier after type conversion * - * @throws MappingException if the entity has more than a single identifier + * @throws MappingException if the entity has more than a single identifier. */ private function convertSingleFieldIdentifierToPHPValue(ClassMetadata $class, $identifierValue) { diff --git a/lib/Doctrine/ORM/Utility/IdentifierFlattener.php b/lib/Doctrine/ORM/Utility/IdentifierFlattener.php index 9f2c40ee32d..fac5bdfd619 100644 --- a/lib/Doctrine/ORM/Utility/IdentifierFlattener.php +++ b/lib/Doctrine/ORM/Utility/IdentifierFlattener.php @@ -60,7 +60,7 @@ public function __construct(UnitOfWork $unitOfWork, ClassMetadataFactory $metada /** * convert foreign identifiers into scalar foreign key values to avoid object to string conversion failures. * - * @param array $id + * @param mixed[] $id * * @return array */ diff --git a/phpcs.xml.dist b/phpcs.xml.dist index 6eb21c5f57b..0acedba6ddf 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -180,4 +180,12 @@ tests/Doctrine/Tests/Models/DDC1590/DDC1590User.php + + + tests/Doctrine/Tests/ORM/Functional/Ticket/DDC832Test.php + + + + lib/Doctrine/ORM/Tools/EntityGenerator.php + diff --git a/tests/Doctrine/Tests/Mocks/CacheKeyMock.php b/tests/Doctrine/Tests/Mocks/CacheKeyMock.php index 98aec4df0f3..c36dacd7a51 100644 --- a/tests/Doctrine/Tests/Mocks/CacheKeyMock.php +++ b/tests/Doctrine/Tests/Mocks/CacheKeyMock.php @@ -16,7 +16,7 @@ class CacheKeyMock extends CacheKey /** * @param string $hash The string hash that represend this cache key */ - function __construct(string $hash) + public function __construct(string $hash) { $this->hash = $hash; } diff --git a/tests/Doctrine/Tests/Mocks/ConcurrentRegionMock.php b/tests/Doctrine/Tests/Mocks/ConcurrentRegionMock.php index 52bd727b6de..b0698c13b4d 100644 --- a/tests/Doctrine/Tests/Mocks/ConcurrentRegionMock.php +++ b/tests/Doctrine/Tests/Mocks/ConcurrentRegionMock.php @@ -37,8 +37,6 @@ public function __construct(Region $region) /** * Dequeue an exception for a specific method invocation * - * @param mixed $default - * * @return mixed */ private function throwException(string $method) diff --git a/tests/Doctrine/Tests/Mocks/TaskMock.php b/tests/Doctrine/Tests/Mocks/TaskMock.php index 0270010d646..5a3c7b26637 100644 --- a/tests/Doctrine/Tests/Mocks/TaskMock.php +++ b/tests/Doctrine/Tests/Mocks/TaskMock.php @@ -29,7 +29,7 @@ class TaskMock extends AbstractTask * * @param AbstractNamespace $namespace CLI Namespace, passed to parent constructor. */ - function __construct(AbstractNamespace $namespace) + public function __construct(AbstractNamespace $namespace) { self::$instances[] = $this; diff --git a/tests/Doctrine/Tests/Models/DDC3597/DDC3597Image.php b/tests/Doctrine/Tests/Models/DDC3597/DDC3597Image.php index dbed620a68e..b93ca2d4c5f 100644 --- a/tests/Doctrine/Tests/Models/DDC3597/DDC3597Image.php +++ b/tests/Doctrine/Tests/Models/DDC3597/DDC3597Image.php @@ -19,7 +19,7 @@ class DDC3597Image extends DDC3597Media */ private $dimension; - function __construct(string $distributionHash) + public function __construct(string $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 fba27c689fc..f46e8b2759a 100644 --- a/tests/Doctrine/Tests/Models/DDC3597/DDC3597Media.php +++ b/tests/Doctrine/Tests/Models/DDC3597/DDC3597Media.php @@ -29,7 +29,7 @@ abstract class DDC3597Media extends DDC3597Root */ private $format; - function __construct($distributionHash) + public function __construct($distributionHash) { $this->distributionHash = $distributionHash; } diff --git a/tests/Doctrine/Tests/Models/DDC3597/Embeddable/DDC3597Dimension.php b/tests/Doctrine/Tests/Models/DDC3597/Embeddable/DDC3597Dimension.php index fac422ad97c..8bbe81933aa 100644 --- a/tests/Doctrine/Tests/Models/DDC3597/Embeddable/DDC3597Dimension.php +++ b/tests/Doctrine/Tests/Models/DDC3597/Embeddable/DDC3597Dimension.php @@ -23,7 +23,7 @@ class DDC3597Dimension */ private $height; - function __construct($width = 0, $height = 0) + public function __construct($width = 0, $height = 0) { $this->setWidth($width); $this->setHeight($height); diff --git a/tests/Doctrine/Tests/Models/ECommerce/ECommerceCustomer.php b/tests/Doctrine/Tests/Models/ECommerce/ECommerceCustomer.php index 0d299264491..47fd90924ad 100644 --- a/tests/Doctrine/Tests/Models/ECommerce/ECommerceCustomer.php +++ b/tests/Doctrine/Tests/Models/ECommerce/ECommerceCustomer.php @@ -59,7 +59,7 @@ public function setCart(ECommerceCart $cart): void } } - /* Does not properly maintain the bidirectional association! */ + /** Does not properly maintain the bidirectional association! */ public function brokenSetCart(ECommerceCart $cart): void { $this->cart = $cart; diff --git a/tests/Doctrine/Tests/Models/Legacy/LegacyCar.php b/tests/Doctrine/Tests/Models/Legacy/LegacyCar.php index 483aab6c064..88b498bc856 100644 --- a/tests/Doctrine/Tests/Models/Legacy/LegacyCar.php +++ b/tests/Doctrine/Tests/Models/Legacy/LegacyCar.php @@ -22,7 +22,7 @@ class LegacyCar /** @Column(name="sDescription", type="string", length=255, unique=true) */ public $_description; - function getDescription() + public function getDescription() { return $this->_description; } diff --git a/tests/Doctrine/Tests/Models/Navigation/NavCountry.php b/tests/Doctrine/Tests/Models/Navigation/NavCountry.php index cefaf97b8dd..99fd67d8d38 100644 --- a/tests/Doctrine/Tests/Models/Navigation/NavCountry.php +++ b/tests/Doctrine/Tests/Models/Navigation/NavCountry.php @@ -23,7 +23,7 @@ class NavCountry /** @OneToMany(targetEntity="NavPointOfInterest", mappedBy="country") */ private $pois; - function __construct($name) + public function __construct($name) { $this->name = $name; } diff --git a/tests/Doctrine/Tests/Models/Navigation/NavPhotos.php b/tests/Doctrine/Tests/Models/Navigation/NavPhotos.php index b76ab52375d..bc096b66e6f 100644 --- a/tests/Doctrine/Tests/Models/Navigation/NavPhotos.php +++ b/tests/Doctrine/Tests/Models/Navigation/NavPhotos.php @@ -29,7 +29,7 @@ class NavPhotos /** @column(type="string", name="file_name") */ private $file; - function __construct($poi, $file) + public function __construct($poi, $file) { $this->poi = $poi; $this->file = $file; diff --git a/tests/Doctrine/Tests/ORM/Cache/DefaultQueryCacheTest.php b/tests/Doctrine/Tests/ORM/Cache/DefaultQueryCacheTest.php index 852c6b25eb0..d856dbf4e5a 100644 --- a/tests/Doctrine/Tests/ORM/Cache/DefaultQueryCacheTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/DefaultQueryCacheTest.php @@ -89,7 +89,7 @@ public function testPutBasicQueryResult(): void $rsm->addRootEntityFromClassMetadata(Country::class, 'c'); for ($i = 0; $i < 4; $i++) { - $name = "Country $i"; + $name = 'Country ' . $i; $entity = new Country($name); $result[] = $entity; @@ -168,9 +168,9 @@ public function testPutToOneAssociation2LevelsQueryResult(): void $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); + $country = new Country('Country ' . $i); + $state = new State('State ' . $i, $country); + $city = new City('City ' . $i, $state); $result[] = $city; @@ -384,7 +384,7 @@ public function testCancelPutResultIfEntityPutFails(): void $rsm->addRootEntityFromClassMetadata(Country::class, 'c'); for ($i = 0; $i < 4; $i++) { - $name = "Country $i"; + $name = 'Country ' . $i; $entity = new Country($name); $result[] = $entity; @@ -491,7 +491,7 @@ public function testIgnoreCacheNonPutMode(): void $rsm->addRootEntityFromClassMetadata(Country::class, 'c'); for ($i = 0; $i < 4; $i++) { - $name = "Country $i"; + $name = 'Country ' . $i; $entity = new Country($name); $result[] = $entity; diff --git a/tests/Doctrine/Tests/ORM/Functional/LifecycleCallbackTest.php b/tests/Doctrine/Tests/ORM/Functional/LifecycleCallbackTest.php index 812e799976b..650718cb6a4 100644 --- a/tests/Doctrine/Tests/ORM/Functional/LifecycleCallbackTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/LifecycleCallbackTest.php @@ -562,7 +562,7 @@ public function getId() class LifecycleCallbackParentEntity { /** @PrePersist */ - function doStuff(): void + public function doStuff(): void { } } diff --git a/tests/Doctrine/Tests/ORM/Functional/NotifyPolicyTest.php b/tests/Doctrine/Tests/ORM/Functional/NotifyPolicyTest.php index 22c9c6cfdd3..2290e0d06c6 100644 --- a/tests/Doctrine/Tests/ORM/Functional/NotifyPolicyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/NotifyPolicyTest.php @@ -124,28 +124,28 @@ class NotifyUser extends NotifyBaseEntity /** @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): void + public function setName($name): void { $this->onPropertyChanged('name', $this->name, $name); $this->name = $name; } - function getGroups() + public function getGroups() { return $this->groups; } @@ -163,28 +163,28 @@ class NotifyGroup extends NotifyBaseEntity /** @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): void + public function setName($name): void { $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/PaginationTest.php b/tests/Doctrine/Tests/ORM/Functional/PaginationTest.php index 823f5c11d79..4ef5d1872cf 100644 --- a/tests/Doctrine/Tests/ORM/Functional/PaginationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/PaginationTest.php @@ -139,7 +139,7 @@ public function testIterateSimpleWithoutJoin($useOutputWalkers, $fetchJoinCollec private function iterateWithOrderAsc($useOutputWalkers, $fetchJoinCollection, $baseDql, $checkField): void { // Ascending - $dql = "$baseDql ASC"; + $dql = $baseDql . ' ASC'; $query = $this->_em->createQuery($dql); $paginator = new Paginator($query, $fetchJoinCollection); @@ -153,7 +153,7 @@ private function iterateWithOrderAsc($useOutputWalkers, $fetchJoinCollection, $b private function iterateWithOrderAscWithLimit($useOutputWalkers, $fetchJoinCollection, $baseDql, $checkField): void { // Ascending - $dql = "$baseDql ASC"; + $dql = $baseDql . ' ASC'; $query = $this->_em->createQuery($dql); // With limit @@ -169,7 +169,7 @@ private function iterateWithOrderAscWithLimit($useOutputWalkers, $fetchJoinColle private function iterateWithOrderAscWithLimitAndOffset($useOutputWalkers, $fetchJoinCollection, $baseDql, $checkField): void { // Ascending - $dql = "$baseDql ASC"; + $dql = $baseDql . ' ASC'; $query = $this->_em->createQuery($dql); // With offset @@ -184,7 +184,7 @@ private function iterateWithOrderAscWithLimitAndOffset($useOutputWalkers, $fetch private function iterateWithOrderDesc($useOutputWalkers, $fetchJoinCollection, $baseDql, $checkField): void { - $dql = "$baseDql DESC"; + $dql = $baseDql . ' DESC'; $query = $this->_em->createQuery($dql); $paginator = new Paginator($query, $fetchJoinCollection); @@ -197,7 +197,7 @@ private function iterateWithOrderDesc($useOutputWalkers, $fetchJoinCollection, $ private function iterateWithOrderDescWithLimit($useOutputWalkers, $fetchJoinCollection, $baseDql, $checkField): void { - $dql = "$baseDql DESC"; + $dql = $baseDql . ' DESC'; $query = $this->_em->createQuery($dql); // With limit @@ -212,7 +212,7 @@ private function iterateWithOrderDescWithLimit($useOutputWalkers, $fetchJoinColl private function iterateWithOrderDescWithLimitAndOffset($useOutputWalkers, $fetchJoinCollection, $baseDql, $checkField): void { - $dql = "$baseDql DESC"; + $dql = $baseDql . ' DESC'; $query = $this->_em->createQuery($dql); // With offset @@ -746,8 +746,8 @@ public function populate(): void for ($i = 0; $i < 9; $i++) { $user = new CmsUser(); - $user->name = "Name$i"; - $user->username = "username$i"; + $user->name = 'Name' . $i; + $user->username = 'username' . $i; $user->status = 'active'; $user->email = new CmsEmail(); $user->email->user = $user; @@ -759,8 +759,8 @@ public function populate(): void $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->topic = 'topic' . $i . $j; + $article->text = 'text' . $i . $j; $article->setAuthor($user); $article->version = 0; $this->_em->persist($article); @@ -769,15 +769,15 @@ public function populate(): void for ($i = 0; $i < 9; $i++) { $company = new Company(); - $company->name = "name$i"; + $company->name = 'name' . $i; $company->logo = new Logo(); - $company->logo->image = "image$i"; + $company->logo->image = 'image' . $i; $company->logo->image_width = 100 + $i; $company->logo->image_height = 100 + $i; $company->logo->company = $company; for ($j = 0; $j < 3; $j++) { $department = new Department(); - $department->name = "name$i$j"; + $department->name = 'name' . $i . $j; $department->company = $company; $company->departments[] = $department; } @@ -787,8 +787,8 @@ public function populate(): void for ($i = 0; $i < 9; $i++) { $user = new User1(); - $user->name = "name$i"; - $user->email = "email$i"; + $user->name = 'name' . $i; + $user->email = 'email' . $i; $this->_em->persist($user); } diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheConcurrentTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheConcurrentTest.php index 139b5a58723..4811be824e5 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheConcurrentTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheConcurrentTest.php @@ -63,7 +63,7 @@ public function testBasicConcurrentEntityReadLock(): void $this->assertTrue($this->cache->containsEntity(Country::class, $countryId)); - /** @var ConcurrentRegionMock */ + /** @var ConcurrentRegionMock $region */ $region->setLock($cacheId, Lock::createLockRead()); // another proc lock the entity cache $this->assertFalse($this->cache->containsEntity(Country::class, $countryId)); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1690Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1690Test.php index 32b3a9c6b10..fa098f24ab6 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1690Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1690Test.php @@ -114,28 +114,28 @@ class DDC1690Parent extends NotifyBaseEntity /** @OneToOne(targetEntity="DDC1690Child") */ private $child; - function getId() + public function getId() { return $this->id; } - function getName() + public function getName() { return $this->name; } - function setName($name): void + public function setName($name): void { $this->onPropertyChanged('name', $this->name, $name); $this->name = $name; } - function setChild($child): void + public function setChild($child): void { $this->child = $child; } - function getChild() + public function getChild() { return $this->child; } @@ -153,28 +153,28 @@ class DDC1690Child extends NotifyBaseEntity /** @OneToOne(targetEntity="DDC1690Parent", mappedBy="child") */ private $parent; - function getId() + public function getId() { return $this->id; } - function getName() + public function getName() { return $this->name; } - function setName($name): void + public function setName($name): void { $this->onPropertyChanged('name', $this->name, $name); $this->name = $name; } - function setParent($parent): void + public function setParent($parent): void { $this->parent = $parent; } - function getParent() + public function getParent() { return $this->parent; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1918Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1918Test.php index 9ce6f9af622..15a1d0c9996 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1918Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1918Test.php @@ -36,8 +36,8 @@ public function testLastPageCorrect(): void for ($i = 0; $i < 10; $i++) { $user = new CmsUser(); - $user->username = "user$i"; - $user->name = "user$i"; + $user->username = 'user' . $i; + $user->name = 'user' . $i; $user->status = 'active'; $user->groups = $groups; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2230Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2230Test.php index c041bf93d17..1d5b9967b1f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2230Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2230Test.php @@ -103,7 +103,7 @@ class DDC2230Address implements NotifyPropertyChanged public $listener; /** {@inheritDoc} */ - function addPropertyChangedListener(PropertyChangedListener $listener) + public function addPropertyChangedListener(PropertyChangedListener $listener) { $this->listener = $listener; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3582Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3582Test.php index d2ec7ae4825..1d76c2e5d23 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3582Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3582Test.php @@ -10,7 +10,7 @@ class DDC3582Test extends OrmFunctionalTestCase { - function testNestedEmbeddablesAreHydratedWithProperClass(): void + public function testNestedEmbeddablesAreHydratedWithProperClass(): void { $this->_schemaTool->createSchema([$this->_em->getClassMetadata(DDC3582Entity::class)]); $this->_em->persist(new DDC3582Entity('foo')); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3699Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3699Test.php index b6bcca11fe0..97cdacb4b07 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3699Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3699Test.php @@ -2,16 +2,20 @@ declare(strict_types=1); +namespace Doctrine\Tests\ORM\Functional\Ticket; + use Doctrine\Tests\Models\DDC3699\DDC3699Child; use Doctrine\Tests\Models\DDC3699\DDC3699RelationMany; use Doctrine\Tests\Models\DDC3699\DDC3699RelationOne; use Doctrine\Tests\OrmFunctionalTestCase; use Doctrine\Tests\VerifyDeprecations; +use function assert; + /** * @group DDC-3699 */ -class DDC3597Test extends OrmFunctionalTestCase +class DDC3699Test extends OrmFunctionalTestCase { use VerifyDeprecations; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC618Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC618Test.php index eab4beb0524..c865e3ed331 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC618Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC618Test.php @@ -181,7 +181,7 @@ class DDC618Book /** @ManyToOne(targetEntity="DDC618Author", inversedBy="books") */ public $author; - function __construct($title, $author) + public function __construct($title, $author) { $this->title = $title; $this->author = $author; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5762Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5762Test.php index 72755c48915..e8ff6816c64 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5762Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5762Test.php @@ -148,7 +148,7 @@ class GH5762DriverRide */ public $car; - function __construct(GH5762Driver $driver, GH5762Car $car) + public function __construct(GH5762Driver $driver, GH5762Car $car) { $this->driver = $driver; $this->car = $car; diff --git a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataFactoryTest.php b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataFactoryTest.php index e015aba8cbe..2938ca16035 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataFactoryTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataFactoryTest.php @@ -39,6 +39,7 @@ use function array_search; use function assert; use function count; +use function sprintf; class ClassMetadataFactoryTest extends OrmTestCase { @@ -498,7 +499,10 @@ protected function newClassMetadataInstance($className) { $this->requestedClasses[] = $className; if (! isset($this->mockMetadata[$className])) { - throw new InvalidArgumentException("No mock metadata found for class $className."); + throw new InvalidArgumentException(sprintf( + 'No mock metadata found for class %s.', + $className + )); } return $this->mockMetadata[$className]; diff --git a/tests/Doctrine/Tests/ORM/Tools/Pagination/CountOutputWalkerTest.php b/tests/Doctrine/Tests/ORM/Tools/Pagination/CountOutputWalkerTest.php index db9d2f751e5..5499a4540ea 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Pagination/CountOutputWalkerTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Pagination/CountOutputWalkerTest.php @@ -37,7 +37,7 @@ public function testCountQuery_MixedResultsWithName(): void ); } - public function testCountQuery_GroupBy(): void + public function testCountQueryGroupBy(): void { $query = $this->entityManager->createQuery( 'SELECT p.name FROM Doctrine\Tests\ORM\Tools\Pagination\Person p GROUP BY p.name' @@ -51,7 +51,7 @@ public function testCountQuery_GroupBy(): void ); } - public function testCountQuery_Having(): void + public function testCountQueryHaving(): void { $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' From d6aca8e1463a320e2494d92a87f492f49c2904af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Sat, 30 Jan 2021 23:45:46 +0100 Subject: [PATCH 21/22] Fix proxy file exclude pattern __CG__ is a file prefix, not a directory --- phpcs.xml.dist | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/phpcs.xml.dist b/phpcs.xml.dist index 0acedba6ddf..16bb4c1140d 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -15,7 +15,7 @@ tests tools - */tests/Doctrine/Tests/Proxies/__CG__/* + */tests/Doctrine/Tests/Proxies/__CG__* From bcbd4401b84477f3bdcf42ad511912514ab14e1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Sat, 30 Jan 2021 23:50:15 +0100 Subject: [PATCH 22/22] Ignore export directory --- phpcs.xml.dist | 1 + 1 file changed, 1 insertion(+) diff --git a/phpcs.xml.dist b/phpcs.xml.dist index 16bb4c1140d..edefbf8c6bc 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -16,6 +16,7 @@ tools */tests/Doctrine/Tests/Proxies/__CG__* + */tests/Doctrine/Tests/ORM/Tools/Export/export/*