diff --git a/src/APM/Command.php b/src/APM/Command.php index ab706afcf4..ce057d8912 100644 --- a/src/APM/Command.php +++ b/src/APM/Command.php @@ -41,8 +41,7 @@ public static function createForFailedCommand(CommandStartedEvent $startedEvent, return $instance; } - /** @param CommandSucceededEvent|CommandFailedEvent $finishedEvent */ - private static function checkRequestIds(CommandStartedEvent $startedEvent, $finishedEvent): void + private static function checkRequestIds(CommandStartedEvent $startedEvent, CommandSucceededEvent|CommandFailedEvent $finishedEvent): void { if ($startedEvent->getRequestId() !== $finishedEvent->getRequestId()) { throw new LogicException('Cannot create APM command for events with different request IDs'); diff --git a/src/Aggregation/Stage.php b/src/Aggregation/Stage.php index 82550a907f..d9810b0456 100644 --- a/src/Aggregation/Stage.php +++ b/src/Aggregation/Stage.php @@ -18,12 +18,8 @@ */ abstract class Stage { - /** @var Builder */ - protected $builder; - - public function __construct(Builder $builder) + public function __construct(protected Builder $builder) { - $this->builder = $builder; } /** diff --git a/src/Aggregation/Stage/AbstractBucket.php b/src/Aggregation/Stage/AbstractBucket.php index 478914f65c..f58aa9cfc4 100644 --- a/src/Aggregation/Stage/AbstractBucket.php +++ b/src/Aggregation/Stage/AbstractBucket.php @@ -24,11 +24,10 @@ */ abstract class AbstractBucket extends Stage { - /** @var Bucket\AbstractOutput|null */ - protected $output; + protected ?Bucket\AbstractOutput $output = null; /** @var Expr|array|string */ - protected $groupBy; + protected Expr|array|string $groupBy; public function __construct(Builder $builder, private DocumentManager $dm, private ClassMetadata $class) { @@ -41,7 +40,7 @@ public function __construct(Builder $builder, private DocumentManager $dm, priva * * @param array|Expr|string $expression */ - public function groupBy($expression): static + public function groupBy(array|Expr|string $expression): static { $this->groupBy = $expression; @@ -71,12 +70,7 @@ abstract protected function getExtraPipelineFields(): array; */ abstract protected function getStageName(): string; - /** - * @param array|mixed|string $expression - * - * @return array|mixed|string - */ - private function convertExpression($expression) + private function convertExpression(mixed $expression): mixed { if (is_array($expression)) { return array_map($this->convertExpression(...), $expression); diff --git a/src/Aggregation/Stage/AbstractReplace.php b/src/Aggregation/Stage/AbstractReplace.php index 589ff2ae4e..acf20d1545 100644 --- a/src/Aggregation/Stage/AbstractReplace.php +++ b/src/Aggregation/Stage/AbstractReplace.php @@ -19,7 +19,7 @@ abstract class AbstractReplace extends Operator { /** @param string|mixed[]|Expr|null $expression */ - final public function __construct(Builder $builder, protected DocumentManager $dm, protected ClassMetadata $class, protected $expression = null) + final public function __construct(Builder $builder, protected DocumentManager $dm, protected ClassMetadata $class, protected string|array|Expr|null $expression = null) { Operator::__construct($builder); } @@ -30,17 +30,12 @@ private function getDocumentPersister(): DocumentPersister } /** @return array|string */ - protected function getReplaceExpression() + protected function getReplaceExpression(): array|string { return $this->expression !== null ? $this->convertExpression($this->expression) : $this->expr->getExpression(); } - /** - * @param mixed[]|string|mixed $expression - * - * @return mixed[]|string|mixed - */ - private function convertExpression($expression) + private function convertExpression(mixed $expression): mixed { if (is_array($expression)) { return array_map($this->convertExpression(...), $expression); diff --git a/src/Aggregation/Stage/Bucket/AbstractOutput.php b/src/Aggregation/Stage/Bucket/AbstractOutput.php index c9942abc82..124d974f15 100644 --- a/src/Aggregation/Stage/Bucket/AbstractOutput.php +++ b/src/Aggregation/Stage/Bucket/AbstractOutput.php @@ -19,17 +19,13 @@ abstract class AbstractOutput extends Stage implements GroupAccumulatorOperators { use ProvidesGroupAccumulatorOperators; - /** @var Stage\AbstractBucket */ - protected $bucket; - private Expr $expr; - public function __construct(Builder $builder, Stage\AbstractBucket $bucket) + public function __construct(Builder $builder, protected Stage\AbstractBucket $bucket) { parent::__construct($builder); - $this->bucket = $bucket; - $this->expr = $builder->expr(); + $this->expr = $builder->expr(); } public function getExpression(): array @@ -43,11 +39,9 @@ public function getExpression(): array * @see https://docs.mongodb.com/manual/meta/aggregation-quick-reference/#aggregation-expressions * @see Expr::expression * - * @param mixed|Expr $value - * * @return $this */ - public function expression($value): static + public function expression(mixed $value): static { $this->expr->expression($value); @@ -59,11 +53,9 @@ public function expression($value): static * * @see Expr::field * - * @param string $fieldName - * * @return $this */ - public function field($fieldName): static + public function field(string $fieldName): static { $this->expr->field($fieldName); diff --git a/src/Aggregation/Stage/Group.php b/src/Aggregation/Stage/Group.php index bac1690ac4..40509731db 100644 --- a/src/Aggregation/Stage/Group.php +++ b/src/Aggregation/Stage/Group.php @@ -4,7 +4,6 @@ namespace Doctrine\ODM\MongoDB\Aggregation\Stage; -use Doctrine\ODM\MongoDB\Aggregation\Builder; use Doctrine\ODM\MongoDB\Aggregation\Expr; use Doctrine\ODM\MongoDB\Aggregation\Operator\GroupAccumulatorOperators; use Doctrine\ODM\MongoDB\Aggregation\Operator\ProvidesGroupAccumulatorOperators; @@ -18,16 +17,6 @@ class Group extends Operator implements GroupAccumulatorOperators { use ProvidesGroupAccumulatorOperators; - /** @var Expr */ - protected $expr; - - public function __construct(Builder $builder) - { - parent::__construct($builder); - - $this->expr = $builder->expr(); - } - /** @phpstan-return GroupStageExpression */ public function getExpression(): array { diff --git a/src/Aggregation/Stage/MatchStage.php b/src/Aggregation/Stage/MatchStage.php index 64dd69e4b7..5827517fca 100644 --- a/src/Aggregation/Stage/MatchStage.php +++ b/src/Aggregation/Stage/MatchStage.php @@ -16,8 +16,7 @@ */ class MatchStage extends Stage { - /** @var Expr */ - protected $query; + protected Expr $query; public function __construct(Builder $builder) { @@ -26,7 +25,7 @@ public function __construct(Builder $builder) $this->query = $this->expr(); } - public function __clone() + public function __clone(): void { $this->query = clone $this->query; } @@ -43,7 +42,7 @@ public function __clone() * @param mixed[]|Expr $expression * @param mixed[]|Expr ...$expressions */ - public function addAnd($expression, ...$expressions): static + public function addAnd(array|Expr $expression, array|Expr ...$expressions): static { $this->query->addAnd(...func_get_args()); @@ -62,7 +61,7 @@ public function addAnd($expression, ...$expressions): static * @param mixed[]|Expr $expression * @param mixed[]|Expr ...$expressions */ - public function addNor($expression, ...$expressions): static + public function addNor(array|Expr $expression, array|Expr ...$expressions): static { $this->query->addNor(...func_get_args()); @@ -81,7 +80,7 @@ public function addNor($expression, ...$expressions): static * @param mixed[]|Expr $expression * @param mixed[]|Expr ...$expressions */ - public function addOr($expression, ...$expressions): static + public function addOr(array|Expr $expression, array|Expr ...$expressions): static { $this->query->addOr(...func_get_args()); @@ -114,7 +113,7 @@ public function all(array $values): static * * @param mixed[]|Expr $expression */ - public function elemMatch($expression): static + public function elemMatch(array|Expr $expression): static { $this->query->elemMatch($expression); @@ -125,10 +124,8 @@ public function elemMatch($expression): static * Specify an equality match for the current field. * * @see Expr::equals() - * - * @param mixed $value */ - public function equals($value): static + public function equals(mixed $value): static { $this->query->equals($value); @@ -180,7 +177,7 @@ public function field(string $field): static * * @param array|Geometry $geometry */ - public function geoIntersects($geometry): static + public function geoIntersects(array|Geometry $geometry): static { $this->query->geoIntersects($geometry); @@ -272,7 +269,7 @@ public function geoWithinCenterSphere(float $x, float $y, float $radius): static * @param array{int|float, int|float} $point3 Third point of the polygon * @param array{int|float, int|float} ...$points Additional points of the polygon */ - public function geoWithinPolygon($point1, $point2, $point3, ...$points): static + public function geoWithinPolygon(array $point1, array $point2, array $point3, array ...$points): static { $this->query->geoWithinPolygon(...func_get_args()); @@ -295,10 +292,8 @@ public function getExpression(): ?array * * @see Expr::gt() * @see https://docs.mongodb.com/manual/reference/operator/gt/ - * - * @param mixed $value */ - public function gt($value): static + public function gt(mixed $value): static { $this->query->gt($value); @@ -310,10 +305,8 @@ public function gt($value): static * * @see Expr::gte() * @see https://docs.mongodb.com/manual/reference/operator/gte/ - * - * @param mixed $value */ - public function gte($value): static + public function gte(mixed $value): static { $this->query->gte($value); @@ -362,10 +355,8 @@ public function language(string $language): static * * @see Expr::lte() * @see https://docs.mongodb.com/manual/reference/operator/lte/ - * - * @param mixed $value */ - public function lt($value): static + public function lt(mixed $value): static { $this->query->lt($value); @@ -377,10 +368,8 @@ public function lt($value): static * * @see Expr::lte() * @see https://docs.mongodb.com/manual/reference/operator/lte/ - * - * @param mixed $value */ - public function lte($value): static + public function lte(mixed $value): static { $this->query->lte($value); @@ -392,11 +381,8 @@ public function lte($value): static * * @see Expr::mod() * @see https://docs.mongodb.com/manual/reference/operator/mod/ - * - * @param float|int $divisor - * @param float|int $remainder */ - public function mod($divisor, $remainder = 0): static + public function mod(float|int $divisor, float|int $remainder = 0): static { $this->query->mod($divisor, $remainder); @@ -414,7 +400,7 @@ public function mod($divisor, $remainder = 0): static * * @param mixed[]|Expr $expression */ - public function not($expression): static + public function not(array|Expr $expression): static { $this->query->not($expression); @@ -426,10 +412,8 @@ public function not($expression): static * * @see Expr::notEqual() * @see https://docs.mongodb.com/manual/reference/operator/ne/ - * - * @param mixed $value */ - public function notEqual($value): static + public function notEqual(mixed $value): static { $this->query->notEqual($value); @@ -458,11 +442,8 @@ public function notIn(array $values): static * and $lt criteria on the upper bound. The upper bound is not inclusive. * * @see Expr::range() - * - * @param mixed $start - * @param mixed $end */ - public function range($start, $end): static + public function range(mixed $start, mixed $end): static { $this->query->range($start, $end); @@ -511,10 +492,8 @@ public function text(string $search): static * * @see Expr::type() * @see https://docs.mongodb.com/manual/reference/operator/type/ - * - * @param int|string $type */ - public function type($type): static + public function type(int|string $type): static { $this->query->type($type); diff --git a/src/Aggregation/Stage/Operator.php b/src/Aggregation/Stage/Operator.php index 452828b5c1..766956f9df 100644 --- a/src/Aggregation/Stage/Operator.php +++ b/src/Aggregation/Stage/Operator.php @@ -47,8 +47,7 @@ abstract class Operator extends Stage implements TrigonometryOperators, TypeOperators { - /** @var Expr */ - protected $expr; + protected Expr $expr; public function __construct(Builder $builder) { @@ -94,7 +93,7 @@ public function add($expression1, $expression2, ...$expressions): static * @param mixed[]|Expr $expression * @param mixed[]|Expr ...$expressions */ - public function addAnd($expression, ...$expressions): static + public function addAnd(array|Expr $expression, array|Expr ...$expressions): static { $this->expr->addAnd(...func_get_args()); @@ -110,7 +109,7 @@ public function addAnd($expression, ...$expressions): static * @param mixed[]|Expr $expression * @param mixed[]|Expr ...$expressions */ - public function addOr($expression, ...$expressions): static + public function addOr(array|Expr $expression, array|Expr ...$expressions): static { $this->expr->addOr(...func_get_args()); diff --git a/src/Configuration.php b/src/Configuration.php index ab30197880..6539d3b3a3 100644 --- a/src/Configuration.php +++ b/src/Configuration.php @@ -67,7 +67,7 @@ class Configuration * it was generated by some process before deployment. Copied from * \Doctrine\Common\Proxy\AbstractProxyFactory. */ - public const AUTOGENERATE_NEVER = 0; + public const int AUTOGENERATE_NEVER = 0; /** * Always generates a new proxy/hydrator/persistent collection in every request. @@ -75,7 +75,7 @@ class Configuration * This is only sane during development. * Copied from \Doctrine\Common\Proxy\AbstractProxyFactory. */ - public const AUTOGENERATE_ALWAYS = 1; + public const int AUTOGENERATE_ALWAYS = 1; /** * Autogenerate the proxy/hydrator/persistent collection class when the file does not exist. @@ -83,7 +83,7 @@ class Configuration * This strategy causes a file exists call whenever any proxy/hydrator is used the * first time in a request. Copied from \Doctrine\Common\Proxy\AbstractProxyFactory. */ - public const AUTOGENERATE_FILE_NOT_EXISTS = 2; + public const int AUTOGENERATE_FILE_NOT_EXISTS = 2; /** * Generate the proxy/hydrator/persistent collection classes using eval(). @@ -91,7 +91,7 @@ class Configuration * This strategy is only sane for development. * Copied from \Doctrine\Common\Proxy\AbstractProxyFactory. */ - public const AUTOGENERATE_EVAL = 3; + public const int AUTOGENERATE_EVAL = 3; /** * Autogenerate the proxy class when the proxy file does not exist or @@ -101,7 +101,7 @@ class Configuration * first time in a request. When the proxied file is changed, the proxy will * be updated. */ - public const AUTOGENERATE_FILE_NOT_EXISTS_OR_CHANGED = 4; + public const int AUTOGENERATE_FILE_NOT_EXISTS_OR_CHANGED = 4; /** * Array of attributes for this configuration instance. diff --git a/src/DocumentManager.php b/src/DocumentManager.php index 62085a936b..90d909b493 100644 --- a/src/DocumentManager.php +++ b/src/DocumentManager.php @@ -37,7 +37,6 @@ use function array_search; use function assert; -use function gettype; use function is_object; use function ltrim; use function sprintf; @@ -57,7 +56,7 @@ */ class DocumentManager implements ObjectManager { - public const CLIENT_TYPEMAP = ['root' => 'array', 'document' => 'array']; + public const array CLIENT_TYPEMAP = ['root' => 'array', 'document' => 'array']; /** * The Doctrine MongoDB connection instance. @@ -264,10 +263,8 @@ public function getMetadataFactory(): ClassmetadataFactoryInterface * Helper method to initialize a lazy loading proxy or persistent collection. * * This method is a no-op for other objects. - * - * @param object $obj */ - public function initializeObject($obj): void + public function initializeObject(object $obj): void { $this->unitOfWork->initializeObject($obj); } @@ -332,7 +329,7 @@ public function getClassNameResolver(): ClassNameResolver * * @template T of object */ - public function getClassMetadata($className): ClassMetadata + public function getClassMetadata(string $className): ClassMetadata { return $this->metadataFactory->getMetadataFor($className); } @@ -451,7 +448,7 @@ public function getDocumentCollections(): array * * @param string[]|string|null $documentName (optional) an array of document names, the document name, or none */ - public function createQueryBuilder($documentName = null): Query\Builder + public function createQueryBuilder(array|string|null $documentName = null): Query\Builder { return new Query\Builder($this, $documentName); } @@ -477,12 +474,8 @@ public function createAggregationBuilder(string $documentName): Aggregation\Buil * * @throws InvalidArgumentException When the given $object param is not an object. */ - public function persist($object): void + public function persist(object $object): void { - if (! is_object($object)) { - throw new InvalidArgumentException(gettype($object)); - } - $this->errorIfClosed(); $this->unitOfWork->persist($object); } @@ -497,12 +490,8 @@ public function persist($object): void * * @throws InvalidArgumentException When the $object param is not an object. */ - public function remove($object): void + public function remove(object $object): void { - if (! is_object($object)) { - throw new InvalidArgumentException(gettype($object)); - } - $this->errorIfClosed(); $this->unitOfWork->remove($object); } @@ -515,12 +504,8 @@ public function remove($object): void * * @throws InvalidArgumentException When the given $object param is not an object. */ - public function refresh($object): void + public function refresh(object $object): void { - if (! is_object($object)) { - throw new InvalidArgumentException(gettype($object)); - } - $this->errorIfClosed(); $this->unitOfWork->refresh($object); } @@ -536,12 +521,8 @@ public function refresh($object): void * * @throws InvalidArgumentException When the $object param is not an object. */ - public function detach($object): void + public function detach(object $object): void { - if (! is_object($object)) { - throw new InvalidArgumentException(gettype($object)); - } - $this->unitOfWork->detach($object); } @@ -557,12 +538,8 @@ public function detach($object): void * @throws LockException * @throws InvalidArgumentException If the $object param is not an object. */ - public function merge($object) + public function merge(object $object): object { - if (! is_object($object)) { - throw new InvalidArgumentException(gettype($object)); - } - $this->errorIfClosed(); return $this->unitOfWork->merge($object); @@ -596,7 +573,7 @@ public function unlock(object $document): void * * @template T of object */ - public function getRepository($className): ObjectRepository + public function getRepository(string $className): ObjectRepository { return $this->repositoryFactory->getRepository($this, $className); } @@ -626,14 +603,13 @@ public function flush(array $options = []): void * has its identifier populated. Otherwise a proxy is returned that automatically * loads itself on first access. * - * @param mixed $identifier * @param class-string $documentName * * @return T * * @template T of object */ - public function getReference(string $documentName, $identifier): object + public function getReference(string $documentName, mixed $identifier): object { /** @var ClassMetadata $class */ $class = $this->metadataFactory->getMetadataFor(ltrim($documentName, '\\')); @@ -669,7 +645,7 @@ public function getReference(string $documentName, $identifier): object * * @param mixed $identifier The document identifier. */ - public function getPartialReference(string $documentName, $identifier): object + public function getPartialReference(string $documentName, mixed $identifier): object { $class = $this->metadataFactory->getMetadataFor(ltrim($documentName, '\\')); @@ -693,15 +669,12 @@ public function getPartialReference(string $documentName, $identifier): object * This is just a convenient shortcut for getRepository($documentName)->find($id). * * @param class-string $className - * @param mixed $id - * @param int $lockMode - * @param int $lockVersion * * @return T|null * * @template T of object */ - public function find($className, $id, $lockMode = LockMode::NONE, $lockVersion = null): ?object + public function find(string $className, mixed $id, int $lockMode = LockMode::NONE, ?int $lockVersion = null): ?object { $repository = $this->getRepository($className); if ($repository instanceof DocumentRepository) { @@ -726,10 +699,8 @@ public function clear(): void * Closes the DocumentManager. All documents that are currently managed * by this DocumentManager become detached. The DocumentManager may no longer * be used after it is closed. - * - * @return void */ - public function close() + public function close(): void { $this->clear(); $this->closed = true; @@ -738,18 +709,12 @@ public function close() /** * Determines whether a document instance is managed in this DocumentManager. * - * @param object $object - * * @return bool TRUE if this DocumentManager currently manages the given document, FALSE otherwise. * * @throws InvalidArgumentException When the $object param is not an object. */ - public function contains($object): bool + public function contains(object $object): bool { - if (! is_object($object)) { - throw new InvalidArgumentException(gettype($object)); - } - return $this->unitOfWork->isScheduledForInsert($object) || $this->unitOfWork->isInIdentityMap($object) && ! $this->unitOfWork->isScheduledForDelete($object); @@ -773,7 +738,7 @@ public function getConfiguration(): Configuration * @throws MappingException * @throws RuntimeException */ - public function createReference(object $document, array $referenceMapping) + public function createReference(object $document, array $referenceMapping): mixed { $class = $this->getClassMetadata($document::class); $id = $this->unitOfWork->getDocumentIdentifier($document); @@ -914,7 +879,7 @@ public function getFilterCollection(): FilterCollection * * @return class-string */ - public function getClassNameForAssociation(array $mapping, $data): string + public function getClassNameForAssociation(array $mapping, mixed $data): string { $discriminatorField = $mapping['discriminatorField'] ?? null; diff --git a/src/DocumentNotFoundException.php b/src/DocumentNotFoundException.php index a32c9965f6..56bae5e876 100644 --- a/src/DocumentNotFoundException.php +++ b/src/DocumentNotFoundException.php @@ -17,8 +17,7 @@ */ final class DocumentNotFoundException extends MongoDBException { - /** @param mixed $identifier */ - public static function documentNotFound(string $className, $identifier): self + public static function documentNotFound(string $className, mixed $identifier): self { try { $id = json_encode($identifier, JSON_THROW_ON_ERROR); diff --git a/src/Event/DocumentNotFoundEventArgs.php b/src/Event/DocumentNotFoundEventArgs.php index 3a31a1ffbb..704c7a1920 100644 --- a/src/Event/DocumentNotFoundEventArgs.php +++ b/src/Event/DocumentNotFoundEventArgs.php @@ -13,17 +13,15 @@ final class DocumentNotFoundEventArgs extends LifecycleEventArgs { private bool $disableException = false; - public function __construct(object $document, DocumentManager $dm, private mixed $identifier) + public function __construct(object $document, DocumentManager $dm, private readonly mixed $identifier) { parent::__construct($document, $dm); } /** * Retrieve associated identifier. - * - * @return mixed */ - public function getIdentifier() + public function getIdentifier(): mixed { return $this->identifier; } diff --git a/src/Event/PreUpdateEventArgs.php b/src/Event/PreUpdateEventArgs.php index a82a0fb1e5..076664e96a 100644 --- a/src/Event/PreUpdateEventArgs.php +++ b/src/Event/PreUpdateEventArgs.php @@ -27,8 +27,6 @@ public function __construct( ?Session $session = null, ) { parent::__construct($document, $dm, $session); - - $this->changeSet = $changeSet; } /** @return array */ @@ -44,10 +42,8 @@ public function hasChangedField(string $field): bool /** * Gets the old value of the changeset of the changed field. - * - * @return mixed */ - public function getOldValue(string $field) + public function getOldValue(string $field): mixed { $this->assertValidField($field); @@ -56,10 +52,8 @@ public function getOldValue(string $field) /** * Gets the new value of the changeset of the changed field. - * - * @return mixed */ - public function getNewValue(string $field) + public function getNewValue(string $field): mixed { $this->assertValidField($field); @@ -68,10 +62,8 @@ public function getNewValue(string $field) /** * Sets the new value of this field. - * - * @param mixed $value */ - public function setNewValue(string $field, $value): void + public function setNewValue(string $field, mixed $value): void { $this->assertValidField($field); diff --git a/src/Events.php b/src/Events.php index b19c7f3afa..bef9cd864d 100644 --- a/src/Events.php +++ b/src/Events.php @@ -21,7 +21,7 @@ private function __construct() * * This is a document lifecycle event. */ - public const preRemove = 'preRemove'; + public const string preRemove = 'preRemove'; /** * The postRemove event occurs for a document after the document has @@ -29,7 +29,7 @@ private function __construct() * * This is a document lifecycle event. */ - public const postRemove = 'postRemove'; + public const string postRemove = 'postRemove'; /** * The prePersist event occurs for a given document before the respective @@ -37,7 +37,7 @@ private function __construct() * * This is a document lifecycle event. */ - public const prePersist = 'prePersist'; + public const string prePersist = 'prePersist'; /** * The postPersist event occurs for a document after the document has @@ -46,7 +46,7 @@ private function __construct() * * This is a document lifecycle event. */ - public const postPersist = 'postPersist'; + public const string postPersist = 'postPersist'; /** * The preUpdate event occurs before the database update operations to @@ -54,7 +54,7 @@ private function __construct() * * This is a document lifecycle event. */ - public const preUpdate = 'preUpdate'; + public const string preUpdate = 'preUpdate'; /** * The postUpdate event occurs after the database update operations to @@ -62,7 +62,7 @@ private function __construct() * * This is a document lifecycle event. */ - public const postUpdate = 'postUpdate'; + public const string postUpdate = 'postUpdate'; /** * The preLoad event occurs for a document before the document has been loaded @@ -71,7 +71,7 @@ private function __construct() * * This is a document lifecycle event. */ - public const preLoad = 'preLoad'; + public const string preLoad = 'preLoad'; /** * The postLoad event occurs for a document after the document has been loaded @@ -84,26 +84,26 @@ private function __construct() * * This is a document lifecycle event. */ - public const postLoad = 'postLoad'; + public const string postLoad = 'postLoad'; /** * The loadClassMetadata event occurs after the mapping metadata for a class * has been loaded from a mapping source (annotations/xml). */ - public const loadClassMetadata = 'loadClassMetadata'; + public const string loadClassMetadata = 'loadClassMetadata'; /** * The onClassMetadataNotFound event occurs whenever loading metadata for a class * failed. */ - public const onClassMetadataNotFound = 'onClassMetadataNotFound'; + public const string onClassMetadataNotFound = 'onClassMetadataNotFound'; /** * The preFlush event occurs when the DocumentManager#flush() operation is invoked, * but before any changes to managed documents have been calculated. This event is * always raised right after DocumentManager#flush() call. */ - public const preFlush = 'preFlush'; + public const string preFlush = 'preFlush'; /** * The onFlush event occurs when the DocumentManager#flush() operation is invoked, @@ -112,7 +112,7 @@ private function __construct() * actually something to do for the underlying UnitOfWork. If nothing needs to be done, * the onFlush event is not raised. */ - public const onFlush = 'onFlush'; + public const string onFlush = 'onFlush'; /** * The postFlush event occurs when the DocumentManager#flush() operation is invoked and @@ -121,22 +121,22 @@ private function __construct() * the postFlush event is not raised. The event won't be raised if an error occurs during the * flush operation. */ - public const postFlush = 'postFlush'; + public const string postFlush = 'postFlush'; /** * The onClear event occurs when the DocumentManager#clear() operation is invoked, * after all references to documents have been removed from the unit of work. */ - public const onClear = 'onClear'; + public const string onClear = 'onClear'; /** * The documentNotFound event occurs if a lazy object could not be found in * the database. */ - public const documentNotFound = 'documentNotFound'; + public const string documentNotFound = 'documentNotFound'; /** * The postCollectionLoad event occurs after collection is initialized (loaded). */ - public const postCollectionLoad = 'postCollectionLoad'; + public const string postCollectionLoad = 'postCollectionLoad'; } diff --git a/src/Hydrator/HydratorException.php b/src/Hydrator/HydratorException.php index d7932883fe..3c3c9a7ff6 100644 --- a/src/Hydrator/HydratorException.php +++ b/src/Hydrator/HydratorException.php @@ -39,8 +39,7 @@ public static function associationTypeMismatch(string $className, string $fieldN )); } - /** @param int|string $key */ - public static function associationItemTypeMismatch(string $className, string $fieldName, $key, string $expectedType, string $actualType): self + public static function associationItemTypeMismatch(string $className, string $fieldName, int|string $key, string $expectedType, string $actualType): self { return new self(sprintf( 'Expected association item with key "%s" for field "%s" in document of type "%s" to be of type "%s", "%s" received.', diff --git a/src/Id/AlnumGenerator.php b/src/Id/AlnumGenerator.php index 3140f99839..2a8644ce86 100644 --- a/src/Id/AlnumGenerator.php +++ b/src/Id/AlnumGenerator.php @@ -61,7 +61,7 @@ public function setChars(string $chars): void $this->chars = $chars; } - public function generate(DocumentManager $dm, object $document) + public function generate(DocumentManager $dm, object $document): string { $id = (string) parent::generate($dm, $document); $index = $this->awkwardSafeMode ? $this->awkwardSafeChars : $this->chars; diff --git a/src/Id/IdGenerator.php b/src/Id/IdGenerator.php index ab6721299d..dde895e7ec 100644 --- a/src/Id/IdGenerator.php +++ b/src/Id/IdGenerator.php @@ -10,8 +10,6 @@ interface IdGenerator { /** * Generates an identifier for a document. - * - * @return mixed */ - public function generate(DocumentManager $dm, object $document); + public function generate(DocumentManager $dm, object $document): mixed; } diff --git a/src/Id/IncrementGenerator.php b/src/Id/IncrementGenerator.php index 71bc7e5225..c422743041 100644 --- a/src/Id/IncrementGenerator.php +++ b/src/Id/IncrementGenerator.php @@ -20,21 +20,13 @@ */ class IncrementGenerator implements IdGenerator { - /** @var string|null */ - protected $collection = null; + protected ?string $collection = null; - /** @var string|null */ - protected $key = null; + protected ?string $key = null; - /** @var int */ - protected $startingId = 1; + protected int $startingId = 1; - /** - * @param string $collection - * - * @return void - */ - public function setCollection($collection) + public function setCollection(?string $collection): void { $this->collection = $collection; } @@ -49,7 +41,7 @@ public function setStartingId(int $startingId): void $this->startingId = $startingId; } - public function generate(DocumentManager $dm, object $document) + public function generate(DocumentManager $dm, object $document): int|string { $className = $document::class; $db = $dm->getDocumentDatabase($className); diff --git a/src/Iterator/CachingIterator.php b/src/Iterator/CachingIterator.php index 2a3096ad3c..c0f63fd1b1 100644 --- a/src/Iterator/CachingIterator.php +++ b/src/Iterator/CachingIterator.php @@ -7,7 +7,6 @@ use Countable; use Iterator as SPLIterator; use IteratorIterator; -use ReturnTypeWillChange; use RuntimeException; use Traversable; @@ -77,15 +76,12 @@ public function toArray(): array } /** @return TValue|false */ - #[ReturnTypeWillChange] - public function current() + public function current(): mixed { return current($this->items); } - /** @return mixed */ - #[ReturnTypeWillChange] - public function key() + public function key(): string|int|null { return key($this->items); } diff --git a/src/Iterator/HydratingIterator.php b/src/Iterator/HydratingIterator.php index 306e15c8dc..77e76dbb37 100644 --- a/src/Iterator/HydratingIterator.php +++ b/src/Iterator/HydratingIterator.php @@ -8,7 +8,6 @@ use Doctrine\ODM\MongoDB\UnitOfWork; use Iterator; use IteratorIterator; -use ReturnTypeWillChange; use RuntimeException; use Traversable; @@ -44,15 +43,12 @@ public function __destruct() } /** @return TDocument|null */ - #[ReturnTypeWillChange] - public function current() + public function current(): mixed { return $this->hydrate($this->getIterator()->current()); } - /** @return mixed */ - #[ReturnTypeWillChange] - public function key() + public function key(): mixed { return $this->getIterator()->key(); } diff --git a/src/Iterator/PrimingIterator.php b/src/Iterator/PrimingIterator.php index 86c4920b83..2f11e872ae 100644 --- a/src/Iterator/PrimingIterator.php +++ b/src/Iterator/PrimingIterator.php @@ -7,7 +7,6 @@ use Doctrine\ODM\MongoDB\Mapping\ClassMetadata; use Doctrine\ODM\MongoDB\Query\ReferencePrimer; use Doctrine\ODM\MongoDB\UnitOfWork; -use ReturnTypeWillChange; use function is_callable; use function iterator_to_array; @@ -38,8 +37,7 @@ public function toArray(): array } /** @return TValue|null */ - #[ReturnTypeWillChange] - public function current() + public function current(): mixed { $this->primeReferences(); @@ -51,9 +49,7 @@ public function next(): void $this->iterator->next(); } - /** @return mixed */ - #[ReturnTypeWillChange] - public function key() + public function key(): mixed { return $this->iterator->key(); } diff --git a/src/Iterator/UnrewindableIterator.php b/src/Iterator/UnrewindableIterator.php index 288ced8cb9..ac5dec4bb5 100644 --- a/src/Iterator/UnrewindableIterator.php +++ b/src/Iterator/UnrewindableIterator.php @@ -7,7 +7,6 @@ use Iterator as SPLIterator; use IteratorIterator; use LogicException; -use ReturnTypeWillChange; use RuntimeException; use Traversable; @@ -55,21 +54,14 @@ public function toArray(): array } /** @return TValue|null */ - #[ReturnTypeWillChange] - public function current() + public function current(): mixed { return $this->getIterator()->current(); } - /** @return mixed */ - #[ReturnTypeWillChange] - public function key() + public function key(): mixed { - if ($this->iterator) { - return $this->iterator->key(); - } - - return null; + return $this->iterator?->key(); } public function next(): void diff --git a/src/LockException.php b/src/LockException.php index b0bd71e697..067aeda477 100644 --- a/src/LockException.php +++ b/src/LockException.php @@ -6,7 +6,7 @@ final class LockException extends MongoDBException { - public function __construct(string $msg, private ?object $document = null) + public function __construct(string $msg, private readonly ?object $document = null) { parent::__construct($msg); } diff --git a/src/LockMode.php b/src/LockMode.php index 99a8096842..ffb2b137a5 100644 --- a/src/LockMode.php +++ b/src/LockMode.php @@ -9,10 +9,10 @@ */ final class LockMode { - public const NONE = 0; - public const OPTIMISTIC = 1; - public const PESSIMISTIC_READ = 2; - public const PESSIMISTIC_WRITE = 4; + public const int NONE = 0; + public const int OPTIMISTIC = 1; + public const int PESSIMISTIC_READ = 2; + public const int PESSIMISTIC_WRITE = 4; private function __construct() { diff --git a/src/Mapping/ClassMetadata.php b/src/Mapping/ClassMetadata.php index ac8f5c3923..477195cf2a 100644 --- a/src/Mapping/ClassMetadata.php +++ b/src/Mapping/ClassMetadata.php @@ -482,52 +482,38 @@ final class ClassMetadata implements BaseClassMetadata /** * READ-ONLY: The name of the mongo database the document is mapped to. - * - * @var string|null */ - public $db; + public ?string $db = null; /** * READ-ONLY: The name of the mongo collection the document is mapped to. - * - * @var string */ - public $collection; + public ?string $collection = null; /** * READ-ONLY: The name of the GridFS bucket the document is mapped to. - * - * @var string */ - public $bucketName = 'fs'; + public string $bucketName = 'fs'; /** * READ-ONLY: If the collection should be a fixed size. - * - * @var bool */ - public $collectionCapped = false; + public bool $collectionCapped = false; /** * READ-ONLY: If the collection is fixed size, its size in bytes. - * - * @var int|null */ - public $collectionSize; + public ?int $collectionSize = null; /** * READ-ONLY: If the collection is fixed size, the maximum number of elements to store in the collection. - * - * @var int|null */ - public $collectionMax; + public ?int $collectionMax = null; /** * READ-ONLY Describes how MongoDB clients route read operations to the members of a replica set. - * - * @var string|null */ - public $readPreference; + public ?string $readPreference = null; /** * READ-ONLY Associated with readPreference Allows to specify criteria so that your application can target read @@ -535,21 +521,17 @@ final class ClassMetadata implements BaseClassMetadata * * @var array> */ - public $readPreferenceTags = []; + public array $readPreferenceTags = []; /** * READ-ONLY: Describes the level of acknowledgement requested from MongoDB for write operations. - * - * @var string|int|null */ - public $writeConcern; + public string|int|null $writeConcern = null; /** * READ-ONLY: The field name of the document identifier. - * - * @var string|null */ - public $identifier; + public ?string $identifier = null; /** * READ-ONLY: The array of indexes for the document collection. @@ -557,14 +539,14 @@ final class ClassMetadata implements BaseClassMetadata * @var array> * @phpstan-var array */ - public $indexes = []; + public array $indexes = []; /** * READ-ONLY: The array of search indexes for the document collection. * * @var list */ - public $searchIndexes = []; + public array $searchIndexes = []; /** * READ-ONLY: Keys and options describing shard key. Only for sharded collections. @@ -572,7 +554,7 @@ final class ClassMetadata implements BaseClassMetadata * @var array * @phpstan-var ShardKey */ - public $shardKey = []; + public array $shardKey = []; /** * Allows users to specify a validation schema for the collection. @@ -596,7 +578,7 @@ final class ClassMetadata implements BaseClassMetadata * * @var class-string */ - public $name; + public string $name; /** * READ-ONLY: The name of the document class that is at the root of the mapped document inheritance @@ -605,7 +587,7 @@ final class ClassMetadata implements BaseClassMetadata * * @var class-string */ - public $rootDocumentName; + public string $rootDocumentName; /** * The name of the custom repository class used for the document class. @@ -613,21 +595,21 @@ final class ClassMetadata implements BaseClassMetadata * * @var class-string|null */ - public $customRepositoryClassName; + public ?string $customRepositoryClassName = null; /** * READ-ONLY: The names of the parent classes (ancestors). * * @var list */ - public $parentClasses = []; + public array $parentClasses = []; /** * READ-ONLY: The names of all subclasses (descendants). * * @var list */ - public $subClasses = []; + public array $subClasses = []; /** * The ReflectionProperty instances of the mapped class. @@ -636,38 +618,32 @@ final class ClassMetadata implements BaseClassMetadata * * @var LegacyReflectionFields|array */ - public $reflFields = []; + public LegacyReflectionFields|array $reflFields = []; /** @var array */ public array $propertyAccessors = []; /** * READ-ONLY: The inheritance mapping type used by the class. - * - * @var int */ - public $inheritanceType = self::INHERITANCE_TYPE_NONE; + public int $inheritanceType = self::INHERITANCE_TYPE_NONE; /** * READ-ONLY: The Id generator type used by the class. - * - * @var int */ - public $generatorType = self::GENERATOR_TYPE_AUTO; + public int $generatorType = self::GENERATOR_TYPE_AUTO; /** * READ-ONLY: The Id generator options. * * @var array */ - public $generatorOptions = []; + public array $generatorOptions = []; /** * READ-ONLY: The ID generator used for generating IDs for this class. - * - * @var IdGenerator|null */ - public $idGenerator; + public ?IdGenerator $idGenerator = null; /** * READ-ONLY: The field mappings of the class. @@ -685,7 +661,7 @@ final class ClassMetadata implements BaseClassMetadata * @var array * @phpstan-var array */ - public $fieldMappings = []; + public array $fieldMappings = []; /** * READ-ONLY: The association mappings of the class. @@ -694,21 +670,21 @@ final class ClassMetadata implements BaseClassMetadata * @var array * @phpstan-var array */ - public $associationMappings = []; + public array $associationMappings = []; /** * READ-ONLY: Array of fields to also load with a given method. * * @var array */ - public $alsoLoadMethods = []; + public array $alsoLoadMethods = []; /** * READ-ONLY: The registered lifecycle callbacks for documents of this class. * * @var array> */ - public $lifecycleCallbacks = []; + public array $lifecycleCallbacks = []; /** * READ-ONLY: The discriminator value of this class. @@ -718,9 +694,9 @@ final class ClassMetadata implements BaseClassMetadata * * @see discriminatorField * - * @var class-string|null + * @var class-string|string|int|null */ - public $discriminatorValue; + public string|int|null $discriminatorValue = null; /** * READ-ONLY: The discriminator map of all mapped classes in the hierarchy. @@ -730,47 +706,37 @@ final class ClassMetadata implements BaseClassMetadata * * @see discriminatorField * - * @var array + * @var array */ - public $discriminatorMap = []; + public array $discriminatorMap = []; /** * READ-ONLY: The definition of the discriminator field used in SINGLE_COLLECTION * inheritance mapping. - * - * @var string|null */ - public $discriminatorField; + public ?string $discriminatorField = null; /** * READ-ONLY: The default value for discriminatorField in case it's not set in the document * * @see discriminatorField - * - * @var string|null */ - public $defaultDiscriminatorValue; + public string|int|null $defaultDiscriminatorValue = null; /** * READ-ONLY: Whether this class describes the mapping of a mapped superclass. - * - * @var bool */ - public $isMappedSuperclass = false; + public bool $isMappedSuperclass = false; /** * READ-ONLY: Whether this class describes the mapping of a embedded document. - * - * @var bool */ - public $isEmbeddedDocument = false; + public bool $isEmbeddedDocument = false; /** * READ-ONLY: Whether this class describes the mapping of an aggregation result document. - * - * @var bool */ - public $isQueryResultDocument = false; + public bool $isQueryResultDocument = false; /** * READ-ONLY: Whether this class describes the mapping of a database view. @@ -779,68 +745,52 @@ final class ClassMetadata implements BaseClassMetadata /** * READ-ONLY: Whether this class describes the mapping of a gridFS file - * - * @var bool */ - public $isFile = false; + public bool $isFile = false; /** * READ-ONLY: The default chunk size in bytes for the file - * - * @var int|null */ - public $chunkSizeBytes; + public ?int $chunkSizeBytes = null; /** * READ-ONLY: The policy used for change-tracking on entities of this class. - * - * @var int */ - public $changeTrackingPolicy = self::CHANGETRACKING_DEFERRED_IMPLICIT; + public int $changeTrackingPolicy = self::CHANGETRACKING_DEFERRED_IMPLICIT; /** * READ-ONLY: A flag for whether or not instances of this class are to be versioned * with optimistic locking. - * - * @var bool $isVersioned */ - public $isVersioned = false; + public bool $isVersioned = false; /** * READ-ONLY: The name of the field which is used for versioning in optimistic locking (if any). - * - * @var string|null $versionField */ - public $versionField; + public ?string $versionField = null; /** * READ-ONLY: A flag for whether or not instances of this class are to allow pessimistic * locking. - * - * @var bool $isLockable */ - public $isLockable = false; + public bool $isLockable = false; /** * READ-ONLY: The name of the field which is used for locking a document. - * - * @var mixed $lockField */ - public $lockField; + public mixed $lockField = null; /** * The ReflectionClass instance of the mapped class. * * @var ReflectionClass */ - public $reflClass; + public ReflectionClass $reflClass; /** * READ_ONLY: A flag for whether or not this document is read-only. - * - * @var bool */ - public $isReadOnly; + public bool $isReadOnly = false; /** * READ-ONLY: A flag for whether or not this document has encrypted fields. @@ -878,12 +828,8 @@ public function __construct(string $documentName) * Helper method to get reference id of ref* type references * * @internal - * - * @param mixed $reference - * - * @return mixed */ - public static function getReferenceId($reference, string $storeAs) + public static function getReferenceId(mixed $reference, string $storeAs): mixed { return $storeAs === self::REFERENCE_STORE_AS_ID ? $reference : $reference[self::getReferencePrefix($storeAs) . 'id']; } @@ -969,8 +915,7 @@ public function getIdentifierFieldNames(): array return [$this->identifier]; } - /** @param string $fieldName */ - public function hasField($fieldName): bool + public function hasField(string $fieldName): bool { return isset($this->fieldMappings[$fieldName]); } @@ -1118,7 +1063,7 @@ public function setAlsoLoadMethods(array $methods): void * @throws MappingException If the discriminator field conflicts with the * "name" attribute of a mapped field. */ - public function setDiscriminatorField($discriminatorField): void + public function setDiscriminatorField(array|string|null $discriminatorField): void { if ($this->isFile) { throw MappingException::discriminatorNotAllowedForGridFS($this->name); @@ -1394,13 +1339,13 @@ public function isSharded(): bool } /** @return array|object|null */ - public function getValidator() + public function getValidator(): array|object|null { return $this->validator; } /** @param array|object|null $validator */ - public function setValidator($validator): void + public function setValidator(array|object|null $validator): void { $this->validator = $validator; } @@ -1438,16 +1383,13 @@ public function setReadPreference(?string $readPreference, array $tags): void /** * Sets the write concern used by this class. - * - * @param string|int|null $writeConcern */ - public function setWriteConcern($writeConcern): void + public function setWriteConcern(string|int|null $writeConcern): void { $this->writeConcern = $writeConcern; } - /** @return int|string|null */ - public function getWriteConcern() + public function getWriteConcern(): string|int|null { return $this->writeConcern; } @@ -1569,7 +1511,7 @@ public function getCollection(): string * * @throws InvalidArgumentException */ - public function setCollection($name): void + public function setCollection(array|string $name): void { if (is_array($name)) { if (! isset($name['name'])) { @@ -1822,10 +1764,8 @@ public function hasEmbed(string $fieldName): bool /** * Checks whether the class has a mapped association (embed or reference) with the given field name. - * - * @param string $fieldName */ - public function hasAssociation($fieldName): bool + public function hasAssociation(string $fieldName): bool { return $this->hasReference($fieldName) || $this->hasEmbed($fieldName); } @@ -1833,10 +1773,8 @@ public function hasAssociation($fieldName): bool /** * Checks whether the class has a mapped reference or embed for the specified field and * is a single valued association. - * - * @param string $fieldName */ - public function isSingleValuedAssociation($fieldName): bool + public function isSingleValuedAssociation(string $fieldName): bool { return $this->isSingleValuedReference($fieldName) || $this->isSingleValuedEmbed($fieldName); } @@ -1844,10 +1782,8 @@ public function isSingleValuedAssociation($fieldName): bool /** * Checks whether the class has a mapped reference or embed for the specified field and * is a collection valued association. - * - * @param string $fieldName */ - public function isCollectionValuedAssociation($fieldName): bool + public function isCollectionValuedAssociation(string $fieldName): bool { return $this->isCollectionValuedReference($fieldName) || $this->isCollectionValuedEmbed($fieldName); } @@ -1898,12 +1834,8 @@ public function setIdGenerator(IdGenerator $generator): void /** * Casts the identifier to its portable PHP type. - * - * @param mixed $id - * - * @return mixed $id */ - public function getPHPIdentifierValue($id) + public function getPHPIdentifierValue(mixed $id): mixed { $idType = $this->fieldMappings[$this->identifier]['type']; @@ -1912,12 +1844,8 @@ public function getPHPIdentifierValue($id) /** * Casts the identifier to its database type. - * - * @param mixed $id - * - * @return mixed $id */ - public function getDatabaseIdentifierValue($id) + public function getDatabaseIdentifierValue(mixed $id): mixed { $idType = $this->fieldMappings[$this->identifier]['type']; @@ -1928,10 +1856,8 @@ public function getDatabaseIdentifierValue($id) * Sets the document identifier of a document. * * The value will be converted to a PHP type before being set. - * - * @param mixed $id */ - public function setIdentifierValue(object $document, $id): void + public function setIdentifierValue(object $document, mixed $id): void { $id = $this->getPHPIdentifierValue($id); $this->propertyAccessors[$this->identifier]->setValue($document, $id); @@ -1939,10 +1865,8 @@ public function setIdentifierValue(object $document, $id): void /** * Gets the document identifier as a PHP type. - * - * @return mixed $id */ - public function getIdentifierValue(object $document) + public function getIdentifierValue(object $document): mixed { return $this->propertyAccessors[$this->identifier]->getValue($document); } @@ -1951,30 +1875,24 @@ public function getIdentifierValue(object $document) * Since MongoDB only allows exactly one identifier field this is a proxy * to {@see getIdentifierValue()} and returns an array with the identifier * field as a key. - * - * @param object $object */ - public function getIdentifierValues($object): array + public function getIdentifierValues(object $object): array { return [$this->identifier => $this->getIdentifierValue($object)]; } /** * Get the document identifier object as a database type. - * - * @return mixed $id */ - public function getIdentifierObject(object $document) + public function getIdentifierObject(object $document): mixed { return $this->getDatabaseIdentifierValue($this->getIdentifierValue($document)); } /** * Sets the specified field to the specified value on the given document. - * - * @param mixed $value */ - public function setFieldValue(object $document, string $field, $value): void + public function setFieldValue(object $document, string $field, mixed $value): void { if ($document instanceof InternalProxy && ! $document->__isInitialized()) { //property changes to an uninitialized proxy will not be tracked or persisted, @@ -1991,10 +1909,8 @@ public function setFieldValue(object $document, string $field, $value): void /** * Gets the specified field's value off the given document. - * - * @return mixed */ - public function getFieldValue(object $document, string $field) + public function getFieldValue(object $document, string $field): mixed { if ($document instanceof InternalProxy && $field !== $this->identifier && ! $document->__isInitialized()) { $document->__load(); @@ -2287,18 +2203,13 @@ public function getAssociationNames(): array return array_keys($this->associationMappings); } - /** @param string $fieldName */ - public function getTypeOfField($fieldName): ?string + public function getTypeOfField(string $fieldName): ?string { return $this->fieldMappings[$fieldName]['type'] ?? null; } - /** - * @param string $assocName - * - * @return class-string|null - */ - public function getAssociationTargetClass($assocName): ?string + /** @return class-string|null */ + public function getAssociationTargetClass(string $assocName): ?string { if (! isset($this->associationMappings[$assocName])) { throw new InvalidArgumentException("Association name expected, '" . $assocName . "' is not an association."); @@ -2325,14 +2236,12 @@ public function getAssociationCollectionClass(string $assocName): string return $this->associationMappings[$assocName]['collectionClass']; } - /** @param string $assocName */ - public function isAssociationInverseSide($assocName): bool + public function isAssociationInverseSide(string $assocName): bool { throw new BadMethodCallException(__METHOD__ . '() is not implemented yet.'); } - /** @param string $assocName */ - public function getAssociationMappedByTargetField($assocName): string + public function getAssociationMappedByTargetField(string $assocName): string { throw new BadMethodCallException(__METHOD__ . '() is not implemented yet.'); } @@ -2605,7 +2514,7 @@ public function mapField(array $mapping): array * * @return array The names of all the fields that should be serialized. */ - public function __sleep() + public function __sleep(): array { // This metadata is always serialized/cached. $serialized = [ diff --git a/src/Mapping/ClassMetadataFactory.php b/src/Mapping/ClassMetadataFactory.php index 0e9a7749db..adcc3cd470 100644 --- a/src/Mapping/ClassMetadataFactory.php +++ b/src/Mapping/ClassMetadataFactory.php @@ -84,8 +84,7 @@ protected function initialize(): void $this->initialized = true; } - /** @param string $className */ - protected function onNotFoundMetadata($className): ?ClassMetadata + protected function onNotFoundMetadata(string $className): ?ClassMetadata { if (! $this->evm->hasListeners(Events::onClassMetadataNotFound)) { return null; @@ -98,17 +97,6 @@ protected function onNotFoundMetadata($className): ?ClassMetadata return $eventArgs->getFoundMetadata(); } - /** - * @deprecated - * - * @param string $namespaceAlias - * @param string $simpleClassName - */ - protected function getFqcnFromAlias($namespaceAlias, $simpleClassName): string - { - return $this->config->getDocumentNamespace($namespaceAlias) . '\\' . $simpleClassName; - } - protected function getDriver(): MappingDriver { return $this->driver; @@ -136,8 +124,7 @@ protected function isEntity(ClassMetadataInterface $class): bool return ! $class->isMappedSuperclass && ! $class->isEmbeddedDocument && ! $class->isQueryResultDocument && ! $class->isView(); } - /** @param bool $rootEntityFound */ - protected function doLoadMetadata($class, $parent, $rootEntityFound, array $nonSuperclassParents = []): void + protected function doLoadMetadata(ClassMetadataInterface $class, ?ClassMetadataInterface $parent, bool $rootEntityFound, array $nonSuperclassParents = []): void { assert($class instanceof ClassMetadata); if ($parent instanceof ClassMetadata) { diff --git a/src/Mapping/Driver/SimplifiedXmlDriver.php b/src/Mapping/Driver/SimplifiedXmlDriver.php index 0288a65eef..af2cf44b6e 100644 --- a/src/Mapping/Driver/SimplifiedXmlDriver.php +++ b/src/Mapping/Driver/SimplifiedXmlDriver.php @@ -11,10 +11,10 @@ */ class SimplifiedXmlDriver extends XmlDriver { - public const DEFAULT_FILE_EXTENSION = '.mongodb-odm.xml'; + public const string DEFAULT_FILE_EXTENSION = '.mongodb-odm.xml'; - /** @param string[] $prefixes */ - public function __construct($prefixes, $fileExtension = self::DEFAULT_FILE_EXTENSION) + /** @param string[]|string $prefixes */ + public function __construct(array|string $prefixes, ?string $fileExtension = self::DEFAULT_FILE_EXTENSION) { $locator = new SymfonyFileLocator((array) $prefixes, $fileExtension); diff --git a/src/Mapping/Driver/XmlDriver.php b/src/Mapping/Driver/XmlDriver.php index f0acbfc8b8..3a1360a039 100644 --- a/src/Mapping/Driver/XmlDriver.php +++ b/src/Mapping/Driver/XmlDriver.php @@ -11,6 +11,7 @@ use Doctrine\ODM\MongoDB\Mapping\TimeSeries\Granularity; use Doctrine\ODM\MongoDB\Utility\CollectionHelper; use Doctrine\Persistence\Mapping\Driver\FileDriver; +use Doctrine\Persistence\Mapping\Driver\FileLocator; use DOMDocument; use InvalidArgumentException; use LibXMLError; @@ -51,9 +52,9 @@ */ class XmlDriver extends FileDriver { - public const DEFAULT_FILE_EXTENSION = '.dcm.xml'; + public const string DEFAULT_FILE_EXTENSION = '.dcm.xml'; - private const DEFAULT_GRIDFS_MAPPINGS = [ + private const array DEFAULT_GRIDFS_MAPPINGS = [ 'length' => [ 'name' => 'length', 'type' => 'int', @@ -76,8 +77,7 @@ class XmlDriver extends FileDriver ], ]; - /** @param string|null $fileExtension */ - public function __construct($locator, $fileExtension = self::DEFAULT_FILE_EXTENSION) + public function __construct(string|array|FileLocator $locator, ?string $fileExtension = self::DEFAULT_FILE_EXTENSION) { parent::__construct($locator, $fileExtension); } diff --git a/src/MongoDBException.php b/src/MongoDBException.php index 0735611a6e..f6eb9b398c 100644 --- a/src/MongoDBException.php +++ b/src/MongoDBException.php @@ -68,11 +68,10 @@ public static function invalidClassMetadataFactory(string $className): self /** * @param string|string[] $expected - * @param mixed $got * * @return MongoDBException */ - public static function invalidValueForType(string $type, $expected, $got): self + public static function invalidValueForType(string $type, string|array $expected, mixed $got): self { if (is_array($expected)) { $expected = sprintf( diff --git a/src/Persisters/DocumentPersister.php b/src/Persisters/DocumentPersister.php index c74c668fe5..50e0407252 100644 --- a/src/Persisters/DocumentPersister.php +++ b/src/Persisters/DocumentPersister.php @@ -48,7 +48,6 @@ use function array_merge; use function array_search; use function array_slice; -use function array_values; use function assert; use function count; use function explode; @@ -481,7 +480,7 @@ public function refresh(object $document): void * @todo Check identity map? loadById method? Try to guess whether * $criteria is the id? */ - public function load($criteria, ?object $document = null, array $hints = [], int $lockMode = 0, ?array $sort = null): ?object + public function load(mixed $criteria, ?object $document = null, array $hints = [], int $lockMode = 0, ?array $sort = null): ?object { // TODO: remove this if ($criteria === null || is_scalar($criteria) || $criteria instanceof ObjectId) { @@ -767,7 +766,7 @@ private function loadReferenceManyCollectionOwningSide(PersistentCollectionInter $class = $this->dm->getClassMetadata($className); $mongoCollection = $this->dm->getDocumentCollection($className); $criteria = $this->cm->merge( - ['_id' => ['$in' => array_values($ids)]], + ['_id' => ['$in' => $ids]], $this->dm->getFilterCollection()->getFilterCriteria($class), $mapping['criteria'] ?? [], ); @@ -923,12 +922,7 @@ public function prepareProjection(array $fields): array return $preparedFields; } - /** - * @param int|string $sort - * - * @return int|string - */ - private function getSortDirection($sort) + private function getSortDirection(int|string|null $sort): int|string|null { switch (strtolower((string) $sort)) { case 'desc': @@ -1082,12 +1076,8 @@ public function prepareQueryOrNewObj(array $query, bool $isNewObj = false): arra /** * Converts a single value to its database representation based on the mapping type if possible. - * - * @param mixed $value - * - * @return mixed */ - private function convertToDatabaseValue(string $fieldName, $value, ?ClassMetadata $class = null) + private function convertToDatabaseValue(string $fieldName, mixed $value, ?ClassMetadata $class = null): mixed { if (is_array($value)) { foreach ($value as $k => $v) { @@ -1159,11 +1149,9 @@ private function prepareQueryReference(mixed $value, ClassMetadata $class): mixe * It also handles converting $fieldName to the database name if they are * different. * - * @param mixed $value - * * @return array Returns an array of tuples containing the prepared field name and value */ - private function prepareQueryElement(string $originalFieldName, $value = null, ?ClassMetadata $class = null, bool $prepareValue = true, bool $inNewObj = false, string $fieldNamePrefix = ''): array + private function prepareQueryElement(string $originalFieldName, mixed $value = null, ?ClassMetadata $class = null, bool $prepareValue = true, bool $inNewObj = false, string $fieldNamePrefix = ''): array { $class ??= $this->class; $fieldName = $fieldNamePrefix . $originalFieldName; @@ -1398,10 +1386,8 @@ private function prepareQueryExpression(array $expression, ClassMetadata $class) * although it should return true for a DBRef. Rather, we're checking that * the value has one or more fields for a DBref. In practice, this could be * $elemMatch criteria for matching a DBRef. - * - * @param mixed $value */ - private function hasDBRefFields($value): bool + private function hasDBRefFields(mixed $value): bool { if (! is_array($value) && ! is_object($value)) { return false; @@ -1422,10 +1408,8 @@ private function hasDBRefFields($value): bool /** * Checks whether the value has query operators. - * - * @param mixed $value */ - private function hasQueryOperators($value): bool + private function hasQueryOperators(mixed $value): bool { if (! is_array($value) && ! is_object($value)) { return false; diff --git a/src/Persisters/PersistenceBuilder.php b/src/Persisters/PersistenceBuilder.php index 130269412c..20057a0786 100644 --- a/src/Persisters/PersistenceBuilder.php +++ b/src/Persisters/PersistenceBuilder.php @@ -54,11 +54,9 @@ public function __construct(DocumentManager $dm, UnitOfWork $uow) /** * Prepares the array that is ready to be inserted to mongodb for a given object document. * - * @param object $document - * * @return array $insertData */ - public function prepareInsertData($document) + public function prepareInsertData(object $document): array { $class = $this->dm->getClassMetadata($document::class); $changeset = $this->uow->getDocumentChangeSet($document); @@ -120,11 +118,9 @@ public function prepareInsertData($document) /** * Prepares the update query to update a given document object in mongodb. * - * @param object $document - * * @return array $updateData */ - public function prepareUpdateData($document) + public function prepareUpdateData(object $document): array { $class = $this->dm->getClassMetadata($document::class); $changeset = $this->uow->getDocumentChangeSet($document); @@ -230,11 +226,9 @@ public function prepareUpdateData($document) /** * Prepares the update query to upsert a given document object in mongodb. * - * @param object $document - * * @return array $updateData */ - public function prepareUpsertData($document) + public function prepareUpsertData(object $document): array { $class = $this->dm->getClassMetadata($document::class); $changeset = $this->uow->getDocumentChangeSet($document); @@ -323,12 +317,9 @@ public function prepareUpsertData($document) * If the document does not have an identifier and the mapping calls for a * simple reference, null may be returned. * - * @param object $document * @phpstan-param FieldMapping $referenceMapping - * - * @return array|null */ - public function prepareReferencedDocumentValue(array $referenceMapping, $document) + public function prepareReferencedDocumentValue(array $referenceMapping, object $document): mixed { return $this->dm->createReference($document, $referenceMapping); } @@ -347,15 +338,13 @@ public function prepareReferencedDocumentValue(array $referenceMapping, $documen * within this value were previously scheduled for deletion or update, they * will also be unscheduled. * - * @param object $embeddedDocument - * @param bool $includeNestedCollections * @phpstan-param FieldMapping $embeddedMapping * * @return array|object * * @throws UnexpectedValueException If an unsupported associating mapping is found. */ - public function prepareEmbeddedDocumentValue(array $embeddedMapping, $embeddedDocument, $includeNestedCollections = false) + public function prepareEmbeddedDocumentValue(array $embeddedMapping, object $embeddedDocument, bool $includeNestedCollections = false): array|object { $embeddedDocumentValue = []; $class = $this->dm->getClassMetadata($embeddedDocument::class); @@ -466,15 +455,13 @@ public function prepareEmbeddedDocumentValue(array $embeddedMapping, $embeddedDo /** * Returns the embedded document or reference representation to be stored. * - * @param object $document - * @param bool $includeNestedCollections * @phpstan-param FieldMapping $mapping * * @return mixed[]|object|null * * @throws InvalidArgumentException If the mapping is neither embedded nor reference. */ - public function prepareAssociatedDocumentValue(array $mapping, $document, $includeNestedCollections = false) + public function prepareAssociatedDocumentValue(array $mapping, object $document, bool $includeNestedCollections = false): array|object|null { if (isset($mapping['embedded'])) { return $this->prepareEmbeddedDocumentValue($mapping, $document, $includeNestedCollections); @@ -491,11 +478,10 @@ public function prepareAssociatedDocumentValue(array $mapping, $document, $inclu * Returns the collection representation to be stored and unschedules it afterwards. * * @param PersistentCollectionInterface $coll - * @param bool $includeNestedCollections * * @return mixed[] */ - public function prepareAssociatedCollectionValue(PersistentCollectionInterface $coll, $includeNestedCollections = false) + public function prepareAssociatedCollectionValue(PersistentCollectionInterface $coll, bool $includeNestedCollections = false): array { $mapping = $coll->getMapping(); $pb = $this; diff --git a/src/Proxy/Factory/LazyGhostProxyFactory.php b/src/Proxy/Factory/LazyGhostProxyFactory.php index a8e5246a38..8af191ed98 100644 --- a/src/Proxy/Factory/LazyGhostProxyFactory.php +++ b/src/Proxy/Factory/LazyGhostProxyFactory.php @@ -121,8 +121,7 @@ public function __construct( $this->lifecycleEventManager = new LifecycleEventManager($dm, $this->uow, $dm->getEventManager()); } - /** @param mixed $identifier */ - public function getProxy(ClassMetadata $metadata, $identifier): InternalProxy + public function getProxy(ClassMetadata $metadata, mixed $identifier): InternalProxy { $className = $metadata->getName(); diff --git a/src/Proxy/Factory/NativeLazyObjectFactory.php b/src/Proxy/Factory/NativeLazyObjectFactory.php index 4624dc1b25..63c03cd8d4 100644 --- a/src/Proxy/Factory/NativeLazyObjectFactory.php +++ b/src/Proxy/Factory/NativeLazyObjectFactory.php @@ -39,7 +39,7 @@ public function generateProxyClasses(array $classes): int return count($classes); } - public function getProxy(ClassMetadata $metadata, $identifier): object + public function getProxy(ClassMetadata $metadata, mixed $identifier): object { $proxy = $metadata->reflClass->newLazyGhost(function (object $object) use ( $identifier, diff --git a/src/Proxy/Factory/ProxyFactory.php b/src/Proxy/Factory/ProxyFactory.php index 4a8d93aeeb..11d078e3c1 100644 --- a/src/Proxy/Factory/ProxyFactory.php +++ b/src/Proxy/Factory/ProxyFactory.php @@ -15,12 +15,11 @@ public function generateProxyClasses(array $classes): int; * Gets a reference proxy instance for the entity of the given type and identified by * the given identifier. * - * @param mixed $identifier * @phpstan-param ClassMetadata $metadata * * @return T * * @template T of object */ - public function getProxy(ClassMetadata $metadata, $identifier): object; + public function getProxy(ClassMetadata $metadata, mixed $identifier): object; } diff --git a/src/Proxy/Factory/StaticProxyFactory.php b/src/Proxy/Factory/StaticProxyFactory.php index fdf7b47963..48cd4bcdcc 100644 --- a/src/Proxy/Factory/StaticProxyFactory.php +++ b/src/Proxy/Factory/StaticProxyFactory.php @@ -39,14 +39,13 @@ public function __construct(DocumentManager $documentManager) } /** - * @param mixed $identifier * @phpstan-param ClassMetadata $metadata * * @return T&GhostObjectInterface * * @template T of object */ - public function getProxy(ClassMetadata $metadata, $identifier): GhostObjectInterface + public function getProxy(ClassMetadata $metadata, mixed $identifier): GhostObjectInterface { $documentPersister = $this->uow->getDocumentPersister($metadata->getName()); diff --git a/src/Query/Builder.php b/src/Query/Builder.php index 43e8f7cc73..1f6ebbb98d 100644 --- a/src/Query/Builder.php +++ b/src/Query/Builder.php @@ -25,8 +25,6 @@ use function func_get_args; use function in_array; use function is_array; -use function is_bool; -use function is_callable; use function is_string; use function strtolower; @@ -50,11 +48,8 @@ class Builder /** * The current field we are operating on. - * - * @todo Change this to private once ODM requires doctrine/mongodb 1.1+ - * @var string */ - protected $currentField; + private string $currentField; /** * Whether or not to hydrate the data to documents. @@ -105,7 +100,7 @@ class Builder * * @param string[]|string|null $documentName (optional) an array of document names, the document name, or none */ - public function __construct(DocumentManager $dm, $documentName = null) + public function __construct(DocumentManager $dm, array|string|null $documentName = null) { $this->dm = $dm; $this->expr = new Expr($dm); @@ -116,7 +111,7 @@ public function __construct(DocumentManager $dm, $documentName = null) $this->setDocumentName($documentName); } - public function __clone() + public function __clone(): void { $this->expr = clone $this->expr; } @@ -132,7 +127,7 @@ public function __clone() * @param array|Expr $expression * @param array|Expr ...$expressions */ - public function addAnd($expression, ...$expressions): self + public function addAnd(array|Expr $expression, array|Expr ...$expressions): self { $this->expr->addAnd(...func_get_args()); @@ -150,7 +145,7 @@ public function addAnd($expression, ...$expressions): self * @param array|Expr $expression * @param array|Expr ...$expressions */ - public function addNor($expression, ...$expressions): self + public function addNor(array|Expr $expression, array|Expr ...$expressions): self { $this->expr->addNor(...func_get_args()); @@ -168,7 +163,7 @@ public function addNor($expression, ...$expressions): self * @param array|Expr $expression * @param array|Expr ...$expressions */ - public function addOr($expression, ...$expressions): self + public function addOr(array|Expr $expression, array|Expr ...$expressions): self { $this->expr->addOr(...func_get_args()); @@ -189,10 +184,8 @@ public function addOr($expression, ...$expressions): self * @see Expr::addToSet() * @see https://docs.mongodb.com/manual/reference/operator/addToSet/ * @see https://docs.mongodb.com/manual/reference/operator/each/ - * - * @param mixed|Expr $valueOrExpression */ - public function addToSet($valueOrExpression): self + public function addToSet(mixed $valueOrExpression): self { $this->expr->addToSet($valueOrExpression); @@ -251,7 +244,7 @@ public function bitOr(int $value): self * * @param int|list|Binary $value */ - public function bitsAllClear($value): self + public function bitsAllClear(int|array|Binary $value): self { $this->expr->bitsAllClear($value); @@ -267,7 +260,7 @@ public function bitsAllClear($value): self * * @param int|list|Binary $value */ - public function bitsAllSet($value): self + public function bitsAllSet(int|array|Binary $value): self { $this->expr->bitsAllSet($value); @@ -283,7 +276,7 @@ public function bitsAllSet($value): self * * @param int|list|Binary $value */ - public function bitsAnyClear($value): self + public function bitsAnyClear(int|array|Binary $value): self { $this->expr->bitsAnyClear($value); @@ -299,7 +292,7 @@ public function bitsAnyClear($value): self * * @param int|list|Binary $value */ - public function bitsAnySet($value): self + public function bitsAnySet(int|array|Binary $value): self { $this->expr->bitsAnySet($value); @@ -379,10 +372,8 @@ public function currentDate(string $type = 'date'): self * The $name parameter may be used to return a specific key from the * internal $query array property. If omitted, the entire array will be * returned. - * - * @return mixed */ - public function debug(?string $name = null) + public function debug(?string $name = null): mixed { return $name !== null ? $this->query[$name] : $this->query; } @@ -428,7 +419,7 @@ public function distinct(string $field): self * * @param array|Expr $expression */ - public function elemMatch($expression): self + public function elemMatch(array|Expr $expression): self { $this->expr->elemMatch($expression); @@ -439,10 +430,8 @@ public function elemMatch($expression): self * Specify an equality match for the current field. * * @see Expr::equals() - * - * @param mixed $value */ - public function equals($value): self + public function equals(mixed $value): self { $this->expr->equals($value); @@ -457,7 +446,7 @@ public function equals($value): self * * @param string[]|string $fieldName,... */ - public function exclude($fieldName = null): self + public function exclude(array|string|null $fieldName = null): self { $this->query['select'] ??= []; $fieldNames = is_array($fieldName) ? $fieldName : func_get_args(); @@ -542,7 +531,7 @@ public function findAndUpdate(?string $documentName = null): self * * @param array|Geometry $geometry */ - public function geoIntersects($geometry): self + public function geoIntersects(array|Geometry $geometry): self { $this->expr->geoIntersects($geometry); @@ -560,7 +549,7 @@ public function geoIntersects($geometry): self * * @param array|Geometry $geometry */ - public function geoWithin($geometry): self + public function geoWithin(array|Geometry $geometry): self { $this->expr->geoWithin($geometry); @@ -636,7 +625,7 @@ public function geoWithinCenterSphere(float $x, float $y, float $radius): self * @param array{int|float, int|float} $point3 Third point of the polygon * @param array{int|float, int|float} ...$points Additional points of the polygon */ - public function geoWithinPolygon($point1, $point2, $point3, ...$points): self + public function geoWithinPolygon(array $point1, array $point2, array $point3, array ...$points): self { $this->expr->geoWithinPolygon(...func_get_args()); @@ -746,10 +735,8 @@ public function getType(): int * * @see Expr::gt() * @see https://docs.mongodb.com/manual/reference/operator/gt/ - * - * @param mixed $value */ - public function gt($value): self + public function gt(mixed $value): self { $this->expr->gt($value); @@ -761,10 +748,8 @@ public function gt($value): self * * @see Expr::gte() * @see https://docs.mongodb.com/manual/reference/operator/gte/ - * - * @param mixed $value */ - public function gte($value): self + public function gte(mixed $value): self { $this->expr->gte($value); @@ -776,7 +761,7 @@ public function gte($value): self * * @param array|string $index */ - public function hint($index): self + public function hint(array|string $index): self { $this->query['hint'] = $index; @@ -822,10 +807,8 @@ public function in(array $values): self * * @see Expr::inc() * @see https://docs.mongodb.com/manual/reference/operator/inc/ - * - * @param float|int $value */ - public function inc($value): self + public function inc(float|int $value): self { $this->expr->inc($value); @@ -881,10 +864,8 @@ public function limit(int $limit): self * * @see Expr::lt() * @see https://docs.mongodb.com/manual/reference/operator/lt/ - * - * @param mixed $value */ - public function lt($value): self + public function lt(mixed $value): self { $this->expr->lt($value); @@ -896,10 +877,8 @@ public function lt($value): self * * @see Expr::lte() * @see https://docs.mongodb.com/manual/reference/operator/lte/ - * - * @param mixed $value */ - public function lte($value): self + public function lte(mixed $value): self { $this->expr->lte($value); @@ -911,10 +890,8 @@ public function lte($value): self * * @see Expr::max() * @see https://docs.mongodb.com/manual/reference/operator/update/max/ - * - * @param mixed $value */ - public function max($value): self + public function max(mixed $value): self { $this->expr->max($value); @@ -936,10 +913,8 @@ public function maxTimeMS(int $ms): self * * @see Expr::min() * @see https://docs.mongodb.com/manual/reference/operator/update/min/ - * - * @param mixed $value */ - public function min($value): self + public function min(mixed $value): self { $this->expr->min($value); @@ -951,11 +926,8 @@ public function min($value): self * * @see Expr::mod() * @see https://docs.mongodb.com/manual/reference/operator/mod/ - * - * @param float|int $divisor - * @param float|int $remainder */ - public function mod($divisor, $remainder = 0): self + public function mod(float|int $divisor, float|int $remainder = 0): self { $this->expr->mod($divisor, $remainder); @@ -969,10 +941,8 @@ public function mod($divisor, $remainder = 0): self * * @see Expr::mul() * @see https://docs.mongodb.com/manual/reference/operator/update/mul/ - * - * @param float|int $value */ - public function mul($value): self + public function mul(float|int $value): self { $this->expr->mul($value); @@ -990,9 +960,8 @@ public function mul($value): self * @see https://docs.mongodb.com/manual/reference/operator/near/ * * @param float|array|Point $x - * @param float $y */ - public function near($x, $y = null, ?float $minDistance = null, ?float $maxDistance = null): self + public function near(float|array|Point $x, ?float $y = null, ?float $minDistance = null, ?float $maxDistance = null): self { $this->expr->near($x, $y, $minDistance, $maxDistance); @@ -1010,9 +979,8 @@ public function near($x, $y = null, ?float $minDistance = null, ?float $maxDista * @see https://docs.mongodb.com/manual/reference/operator/nearSphere/ * * @param float|array|Point $x - * @param float $y */ - public function nearSphere($x, $y = null, ?float $minDistance = null, ?float $maxDistance = null): self + public function nearSphere(float|array|Point $x, ?float $y = null, ?float $minDistance = null, ?float $maxDistance = null): self { $this->expr->nearSphere($x, $y, $minDistance, $maxDistance); @@ -1026,10 +994,8 @@ public function nearSphere($x, $y = null, ?float $minDistance = null, ?float $ma * * @see Expr::not() * @see https://docs.mongodb.com/manual/reference/operator/not/ - * - * @param array|Expr|mixed $valueOrExpression */ - public function not($valueOrExpression): self + public function not(mixed $valueOrExpression): self { $this->expr->not($valueOrExpression); @@ -1041,10 +1007,8 @@ public function not($valueOrExpression): self * * @see Expr::notEqual() * @see https://docs.mongodb.com/manual/reference/operator/ne/ - * - * @param mixed $value */ - public function notEqual($value): self + public function notEqual(mixed $value): self { $this->expr->notEqual($value); @@ -1124,17 +1088,9 @@ public function popLast(): self * * If a custom callable is used, its signature should conform to the default * Closure defined in {@link ReferencePrimer::__construct()}. - * - * @param bool|callable $primer - * - * @throws InvalidArgumentException If $primer is not boolean or callable. */ - public function prime($primer = true): self + public function prime(bool|callable $primer = true): self { - if (! is_bool($primer) && ! is_callable($primer)) { - throw new InvalidArgumentException('$primer is not a boolean or callable'); - } - if ($primer === false) { unset($this->primers[$this->currentField]); @@ -1152,10 +1108,8 @@ public function prime($primer = true): self * * @see Expr::pull() * @see https://docs.mongodb.com/manual/reference/operator/pull/ - * - * @param mixed|Expr $valueOrExpression */ - public function pull($valueOrExpression): self + public function pull(mixed $valueOrExpression): self { $this->expr->pull($valueOrExpression); @@ -1194,10 +1148,8 @@ public function pullAll(array $values): self * @see https://docs.mongodb.com/manual/reference/operator/each/ * @see https://docs.mongodb.com/manual/reference/operator/slice/ * @see https://docs.mongodb.com/manual/reference/operator/sort/ - * - * @param mixed|Expr $valueOrExpression */ - public function push($valueOrExpression): self + public function push(mixed $valueOrExpression): self { $this->expr->push($valueOrExpression); @@ -1211,11 +1163,8 @@ public function push($valueOrExpression): self * and $lt criteria on the upper bound. The upper bound is not inclusive. * * @see Expr::range() - * - * @param mixed $start - * @param mixed $end */ - public function range($start, $end): self + public function range(mixed $start, mixed $end): self { $this->expr->range($start, $end); @@ -1277,7 +1226,7 @@ public function returnNew(bool $bool = true): self * * @param string[]|string $fieldName,... */ - public function select($fieldName = null): self + public function select(array|string|null $fieldName = null): self { $this->query['select'] ??= []; $fieldNames = is_array($fieldName) ? $fieldName : func_get_args(); @@ -1297,7 +1246,7 @@ public function select($fieldName = null): self * * @param array|Expr $expression */ - public function selectElemMatch(string $fieldName, $expression): self + public function selectElemMatch(string $fieldName, array|Expr $expression): self { if ($expression instanceof Expr) { $expression = $expression->getQuery(); @@ -1350,10 +1299,8 @@ public function selectSlice(string $fieldName, int $countOrSkip, ?int $limit = n * * @see Expr::set() * @see https://docs.mongodb.com/manual/reference/operator/set/ - * - * @param mixed $value */ - public function set($value, bool $atomic = true): self + public function set(mixed $value, bool $atomic = true): self { $this->expr->set($value, $atomic && $this->query['type'] !== Query::TYPE_INSERT); @@ -1385,10 +1332,8 @@ public function setNewObj(array $newObj): self * * @see Expr::setOnInsert() * @see https://docs.mongodb.com/manual/reference/operator/update/setOnInsert/ - * - * @param mixed $value */ - public function setOnInsert($value): self + public function setOnInsert(mixed $value): self { $this->expr->setOnInsert($value); @@ -1477,7 +1422,7 @@ public function snapshot(bool $bool = true): self * @param array|string $fieldName Field name or array of field/order pairs * @param int|string $order Field order (if one field is specified) */ - public function sort($fieldName, $order = 1): self + public function sort(array|string $fieldName, int|string $order = 1): self { $this->query['sort'] ??= []; $fields = is_array($fieldName) ? $fieldName : [$fieldName => $order]; @@ -1540,10 +1485,8 @@ public function text(string $search): self * * @see Expr::type() * @see https://docs.mongodb.com/manual/reference/operator/type/ - * - * @param int|string $type */ - public function type($type): self + public function type(int|string $type): self { $this->expr->type($type); @@ -1598,10 +1541,8 @@ public function upsert(bool $bool = true): self * * @see Expr::where() * @see https://docs.mongodb.com/manual/reference/operator/where/ - * - * @param string|Javascript $javascript */ - public function where($javascript): self + public function where(string|Javascript $javascript): self { $this->expr->where($javascript); @@ -1636,7 +1577,7 @@ private function getDiscriminatorValues(array $classNames): array } /** @param class-string[]|class-string|null $documentName an array of document names or just one. */ - private function setDocumentName($documentName): void + private function setDocumentName(array|string|null $documentName): void { if (is_array($documentName)) { $documentNames = $documentName; diff --git a/src/Query/CriteriaMerger.php b/src/Query/CriteriaMerger.php index 36fd1e53e9..8c77f397eb 100644 --- a/src/Query/CriteriaMerger.php +++ b/src/Query/CriteriaMerger.php @@ -24,7 +24,7 @@ final class CriteriaMerger * * @return array */ - public function merge(...$criterias): array + public function merge(array ...$criterias): array { $nonEmptyCriterias = array_values(array_filter($criterias, static fn (array $criteria) => ! empty($criteria))); diff --git a/src/Query/Expr.php b/src/Query/Expr.php index 3ff256bef2..19dd092019 100644 --- a/src/Query/Expr.php +++ b/src/Query/Expr.php @@ -58,19 +58,13 @@ class Expr */ private ?string $currentField = null; - /** - * The DocumentManager instance for this query - */ - private DocumentManager $dm; - /** * The ClassMetadata instance for the document being queried */ private ?ClassMetadata $class = null; - public function __construct(DocumentManager $dm) + public function __construct(private readonly DocumentManager $dm) { - $this->dm = $dm; } /** @@ -82,7 +76,7 @@ public function __construct(DocumentManager $dm) * @param array|Expr $expression * @param array|Expr ...$expressions */ - public function addAnd($expression, ...$expressions): self + public function addAnd(array|Expr $expression, array|Expr ...$expressions): self { $this->query['$and'] = array_merge( $this->query['$and'] ?? [], @@ -101,7 +95,7 @@ public function addAnd($expression, ...$expressions): self * @param array|Expr $expression * @param array|Expr ...$expressions */ - public function addNor($expression, ...$expressions): self + public function addNor(array|Expr $expression, array|Expr ...$expressions): self { $this->query['$nor'] = array_merge( $this->query['$nor'] ?? [], @@ -120,7 +114,7 @@ public function addNor($expression, ...$expressions): self * @param array|Expr $expression * @param array|Expr ...$expressions */ - public function addOr($expression, ...$expressions): self + public function addOr(array|Expr $expression, array|Expr ...$expressions): self { $this->query['$or'] = array_merge( $this->query['$or'] ?? [], @@ -144,10 +138,8 @@ public function addOr($expression, ...$expressions): self * @see Builder::addToSet() * @see https://docs.mongodb.com/manual/reference/operator/addToSet/ * @see https://docs.mongodb.com/manual/reference/operator/each/ - * - * @param mixed|Expr $valueOrExpression */ - public function addToSet($valueOrExpression): self + public function addToSet(mixed $valueOrExpression): self { $this->requiresCurrentField(__METHOD__); $this->newObj['$addToSet'][$this->currentField] = static::convertExpression($valueOrExpression, $this->class); @@ -212,7 +204,7 @@ public function bitOr(int $value): self * * @param int|list|Binary $value */ - public function bitsAllClear($value): self + public function bitsAllClear(int|array|Binary $value): self { $this->requiresCurrentField(__METHOD__); @@ -228,7 +220,7 @@ public function bitsAllClear($value): self * * @param int|list|Binary $value */ - public function bitsAllSet($value): self + public function bitsAllSet(int|array|Binary $value): self { $this->requiresCurrentField(__METHOD__); @@ -244,7 +236,7 @@ public function bitsAllSet($value): self * * @param int|list|Binary $value */ - public function bitsAnyClear($value): self + public function bitsAnyClear(int|array|Binary $value): self { $this->requiresCurrentField(__METHOD__); @@ -260,7 +252,7 @@ public function bitsAnyClear($value): self * * @param int|list|Binary $value */ - public function bitsAnySet($value): self + public function bitsAnySet(int|array|Binary $value): self { $this->requiresCurrentField(__METHOD__); @@ -386,7 +378,7 @@ public function each(array $values): self * * @param array|Expr $expression */ - public function elemMatch($expression): self + public function elemMatch(array|Expr $expression): self { return $this->operator('$elemMatch', $expression); } @@ -395,10 +387,8 @@ public function elemMatch($expression): self * Specify an equality match for the current field. * * @see Builder::equals() - * - * @param mixed $value */ - public function equals($value): self + public function equals(mixed $value): self { if ($this->currentField) { $this->query[$this->currentField] = $value; @@ -443,7 +433,7 @@ public function field(string $field): self * * @param array|Geometry $geometry */ - public function geoIntersects($geometry): self + public function geoIntersects(array|Geometry $geometry): self { if ($geometry instanceof Geometry) { $geometry = $geometry->jsonSerialize(); @@ -463,7 +453,7 @@ public function geoIntersects($geometry): self * * @param array|Geometry $geometry */ - public function geoWithin($geometry): self + public function geoWithin(array|Geometry $geometry): self { if ($geometry instanceof Geometry) { $geometry = $geometry->jsonSerialize(); @@ -543,7 +533,7 @@ public function geoWithinCenterSphere(float $x, float $y, float $radius): self * * @throws InvalidArgumentException If less than three points are given. */ - public function geoWithinPolygon($point1, $point2, $point3, ...$points): self + public function geoWithinPolygon(array $point1, array $point2, array $point3, array ...$points): self { $shape = ['$polygon' => func_get_args()]; @@ -587,10 +577,8 @@ public function getQuery(): array * * @see Builder::gt() * @see https://docs.mongodb.com/manual/reference/operator/gt/ - * - * @param mixed $value */ - public function gt($value): self + public function gt(mixed $value): self { return $this->operator('$gt', $value); } @@ -600,10 +588,8 @@ public function gt($value): self * * @see Builder::gte() * @see https://docs.mongodb.com/manual/reference/operator/gte/ - * - * @param mixed $value */ - public function gte($value): self + public function gte(mixed $value): self { return $this->operator('$gte', $value); } @@ -628,10 +614,8 @@ public function in(array $values): self * * @see Builder::inc() * @see https://docs.mongodb.com/manual/reference/operator/inc/ - * - * @param float|int $value */ - public function inc($value): self + public function inc(float|int $value): self { $this->requiresCurrentField(__METHOD__); $this->newObj['$inc'][$this->currentField] = $value; @@ -711,10 +695,8 @@ public function language(string $language): self * * @see Builder::lte() * @see https://docs.mongodb.com/manual/reference/operator/lte/ - * - * @param mixed $value */ - public function lt($value): self + public function lt(mixed $value): self { return $this->operator('$lt', $value); } @@ -724,10 +706,8 @@ public function lt($value): self * * @see Builder::lte() * @see https://docs.mongodb.com/manual/reference/operator/lte/ - * - * @param mixed $value */ - public function lte($value): self + public function lte(mixed $value): self { return $this->operator('$lte', $value); } @@ -737,10 +717,8 @@ public function lte($value): self * * @see Builder::max() * @see https://docs.mongodb.com/manual/reference/operator/update/max/ - * - * @param mixed $value */ - public function max($value): self + public function max(mixed $value): self { $this->requiresCurrentField(__METHOD__); $this->newObj['$max'][$this->currentField] = $value; @@ -753,10 +731,8 @@ public function max($value): self * * @see Builder::min() * @see https://docs.mongodb.com/manual/reference/operator/update/min/ - * - * @param mixed $value */ - public function min($value): self + public function min(mixed $value): self { $this->requiresCurrentField(__METHOD__); $this->newObj['$min'][$this->currentField] = $value; @@ -769,11 +745,8 @@ public function min($value): self * * @see Builder::mod() * @see https://docs.mongodb.com/manual/reference/operator/mod/ - * - * @param float|int $divisor - * @param float|int $remainder */ - public function mod($divisor, $remainder = 0): self + public function mod(float|int $divisor, float|int $remainder = 0): self { return $this->operator('$mod', [$divisor, $remainder]); } @@ -785,10 +758,8 @@ public function mod($divisor, $remainder = 0): self * * @see Builder::mul() * @see https://docs.mongodb.com/manual/reference/operator/update/mul/ - * - * @param float|int $value */ - public function mul($value): self + public function mul(float|int $value): self { $this->requiresCurrentField(__METHOD__); $this->newObj['$mul'][$this->currentField] = $value; @@ -807,9 +778,8 @@ public function mul($value): self * @see https://docs.mongodb.com/manual/reference/operator/near/ * * @param float|array|Point $x - * @param float $y */ - public function near($x, $y = null, ?float $minDistance = null, ?float $maxDistance = null): self + public function near(float|array|Point $x, ?float $y = null, ?float $minDistance = null, ?float $maxDistance = null): self { if ($x instanceof Point) { $x = $x->jsonSerialize(); @@ -850,9 +820,8 @@ public function near($x, $y = null, ?float $minDistance = null, ?float $maxDista * @see https://docs.mongodb.com/manual/reference/operator/nearSphere/ * * @param float|array|Point $x - * @param float $y */ - public function nearSphere($x, $y = null, ?float $minDistance = null, ?float $maxDistance = null): self + public function nearSphere(float|array|Point $x, ?float $y = null, ?float $minDistance = null, ?float $maxDistance = null): self { if ($x instanceof Point) { $x = $x->jsonSerialize(); @@ -887,10 +856,8 @@ public function nearSphere($x, $y = null, ?float $minDistance = null, ?float $ma * * @see Builder::not() * @see https://docs.mongodb.com/manual/reference/operator/not/ - * - * @param array|Expr|mixed $expression */ - public function not($expression): self + public function not(mixed $expression): self { return $this->operator('$not', $expression); } @@ -900,10 +867,8 @@ public function not($expression): self * * @see Builder::notEqual() * @see https://docs.mongodb.com/manual/reference/operator/ne/ - * - * @param mixed $value */ - public function notEqual($value): self + public function notEqual(mixed $value): self { return $this->operator('$ne', $value); } @@ -926,10 +891,8 @@ public function notIn(array $values): self * * If there is a current field, the operator will be set on it; otherwise, * the operator is set at the top level of the query. - * - * @param mixed $value */ - public function operator(string $operator, $value): self + public function operator(string $operator, mixed $value): self { $this->wrapEqualityCriteria(); @@ -989,10 +952,8 @@ public function position(int $position): self * * @see Builder::pull() * @see https://docs.mongodb.com/manual/reference/operator/pull/ - * - * @param mixed|Expr $valueOrExpression */ - public function pull($valueOrExpression): self + public function pull(mixed $valueOrExpression): self { $this->requiresCurrentField(__METHOD__); $this->newObj['$pull'][$this->currentField] = static::convertExpression($valueOrExpression, $this->class); @@ -1033,10 +994,8 @@ public function pullAll(array $values): self * @see https://docs.mongodb.com/manual/reference/operator/each/ * @see https://docs.mongodb.com/manual/reference/operator/slice/ * @see https://docs.mongodb.com/manual/reference/operator/sort/ - * - * @param mixed|Expr $valueOrExpression */ - public function push($valueOrExpression): self + public function push(mixed $valueOrExpression): self { if ($valueOrExpression instanceof Expr) { $valueOrExpression = array_merge( @@ -1058,11 +1017,8 @@ public function push($valueOrExpression): self * and $lt criteria on the upper bound. The upper bound is not inclusive. * * @see Builder::range() - * - * @param mixed $start - * @param mixed $end */ - public function range($start, $end): self + public function range(mixed $start, mixed $end): self { return $this->operator('$gte', $start)->operator('$lt', $end); } @@ -1136,10 +1092,8 @@ public function rename(string $name): self * * @see Builder::set() * @see https://docs.mongodb.com/manual/reference/operator/set/ - * - * @param mixed $value */ - public function set($value, bool $atomic = true): self + public function set(mixed $value, bool $atomic = true): self { $this->requiresCurrentField(__METHOD__); assert($this->currentField !== null); @@ -1200,10 +1154,8 @@ public function setNewObj(array $newObj): self * * @see Builder::setOnInsert() * @see https://docs.mongodb.com/manual/reference/operator/update/setOnInsert/ - * - * @param mixed $value */ - public function setOnInsert($value): self + public function setOnInsert(mixed $value): self { $this->requiresCurrentField(__METHOD__); $this->newObj['$setOnInsert'][$this->currentField] = $value; @@ -1263,9 +1215,9 @@ public function slice(int $slice): self * @see https://docs.mongodb.com/manual/reference/operator/sort/ * * @param array|string $fieldName Field name or array of field/order pairs - * @param int|string $order Field order (if one field is specified) + * @param int|string|null $order Field order (if one field is specified) */ - public function sort($fieldName, $order = null): self + public function sort(array|string $fieldName, int|string|null $order = null): self { $fields = is_array($fieldName) ? $fieldName : [$fieldName => $order]; @@ -1292,10 +1244,8 @@ public function text(string $search): self * * @see Builder::type() * @see https://docs.mongodb.com/manual/reference/operator/type/ - * - * @param int|string $type */ - public function type($type): self + public function type(int|string $type): self { return $this->operator('$type', $type); } @@ -1321,10 +1271,8 @@ public function unsetField(): self * * @see Builder::where() * @see https://docs.mongodb.com/manual/reference/operator/where/ - * - * @param string|Javascript $javascript */ - public function where($javascript): self + public function where(string|Javascript $javascript): self { $this->query['$where'] = $javascript; @@ -1374,8 +1322,7 @@ private function getReferenceMapping(): array } } - /** @param int|string $order */ - private function normalizeSortOrder($order): int + private function normalizeSortOrder(int|string $order): int { if (is_string($order)) { $order = strtolower($order) === 'asc' ? 1 : -1; @@ -1472,12 +1419,8 @@ private function convertExpressions(array $query, ?ClassMetadata $classMetadata /** * Converts expression objects to query arrays. Non-expression values are * returned unmodified. - * - * @param Expr|mixed $expression - * - * @return array|mixed */ - private static function convertExpression($expression, ClassMetadata $classMetadata) + private static function convertExpression(mixed $expression, ClassMetadata $classMetadata): mixed { if (! $expression instanceof Expr) { return $expression; diff --git a/src/Query/Filter/BsonFilter.php b/src/Query/Filter/BsonFilter.php index 07c16eef0b..d2fd5c12d9 100644 --- a/src/Query/Filter/BsonFilter.php +++ b/src/Query/Filter/BsonFilter.php @@ -17,19 +17,15 @@ */ abstract class BsonFilter { - /** @var DocumentManager */ - protected $dm; - /** * Parameters for the filter. * * @var array */ - protected $parameters = []; + protected array $parameters = []; - final public function __construct(DocumentManager $dm) + final public function __construct(protected DocumentManager $dm) { - $this->dm = $dm; } /** @@ -37,7 +33,7 @@ final public function __construct(DocumentManager $dm) * * @param mixed $value Value of the parameter. */ - final public function setParameter(string $name, $value): self + final public function setParameter(string $name, mixed $value): self { $this->parameters[$name] = $value; @@ -53,7 +49,7 @@ final public function setParameter(string $name, $value): self * * @return mixed The parameter. */ - final public function getParameter(string $name) + final public function getParameter(string $name): mixed { if (! array_key_exists($name, $this->parameters)) { throw new InvalidArgumentException("Filter parameter '" . $name . "' is not set."); diff --git a/src/Query/Query.php b/src/Query/Query.php index f5dad99f97..198d142b6f 100644 --- a/src/Query/Query.php +++ b/src/Query/Query.php @@ -67,34 +67,19 @@ */ final class Query implements IterableResult { - public const TYPE_FIND = 1; - public const TYPE_FIND_AND_UPDATE = 2; - public const TYPE_FIND_AND_REMOVE = 3; - public const TYPE_INSERT = 4; - public const TYPE_UPDATE = 5; - public const TYPE_REMOVE = 6; - public const TYPE_DISTINCT = 9; - public const TYPE_COUNT = 11; + public const int TYPE_FIND = 1; + public const int TYPE_FIND_AND_UPDATE = 2; + public const int TYPE_FIND_AND_REMOVE = 3; + public const int TYPE_INSERT = 4; + public const int TYPE_UPDATE = 5; + public const int TYPE_REMOVE = 6; + public const int TYPE_DISTINCT = 9; + public const int TYPE_COUNT = 11; // 2 was used for HINT_SLAVE_OKAY, which was removed in 2.0 - public const HINT_REFRESH = 1; - public const HINT_READ_PREFERENCE = 3; - public const HINT_READ_ONLY = 5; - - /** - * The DocumentManager instance. - */ - private DocumentManager $dm; - - /** - * The ClassMetadata instance. - */ - private ClassMetadata $class; - - /** - * Whether to hydrate results as document class instances. - */ - private bool $hydrate = true; + public const int HINT_REFRESH = 1; + public const int HINT_READ_PREFERENCE = 3; + public const int HINT_READ_ONLY = 5; /** * Array of primer Closure instances. @@ -112,34 +97,25 @@ final class Query implements IterableResult */ private array $unitOfWorkHints = []; - /** - * The Collection instance. - */ - protected Collection $collection; - - /** - * Query structure generated by the Builder class. - * - * @phpstan-var QueryShape - */ - private array $query; - private ?Iterator $iterator = null; /** - * Query options - * - * @var array - */ - private array $options; - - /** - * @param QueryShape $query - * @param array $options + * @param QueryShape $query Query structure generated by the Builder class. + * @param array $options Query options. * @param array $primers */ - public function __construct(DocumentManager $dm, ClassMetadata $class, Collection $collection, array $query, array $options = [], bool $hydrate = true, bool $refresh = false, array $primers = [], bool $readOnly = false, bool $rewindable = true) - { + public function __construct( + private DocumentManager $dm, + private ClassMetadata $class, + private Collection $collection, + private array $query, + private array $options = [], + private bool $hydrate = true, + bool $refresh = false, + array $primers = [], + bool $readOnly = false, + bool $rewindable = true, + ) { $primers = array_filter($primers); switch ($query['type']) { @@ -157,13 +133,7 @@ public function __construct(DocumentManager $dm, ClassMetadata $class, Collectio throw new InvalidArgumentException('Invalid query type: ' . $query['type']); } - $this->collection = $collection; - $this->query = $query; - $this->options = $options; - $this->dm = $dm; - $this->class = $class; - $this->hydrate = $hydrate; - $this->primers = $primers; + $this->primers = $primers; $this->setReadOnly($readOnly); $this->setRefresh($refresh); @@ -176,7 +146,7 @@ public function __construct(DocumentManager $dm, ClassMetadata $class, Collectio $this->unitOfWorkHints[self::HINT_READ_PREFERENCE] = $query['readPreference']; } - public function __clone() + public function __clone(): void { $this->iterator = null; } @@ -187,10 +157,8 @@ public function __clone() * The $name parameter may be used to return a specific key from the * internal $query array property. If omitted, the entire array will be * returned. - * - * @return array|mixed */ - public function debug(?string $name = null) + public function debug(?string $name = null): mixed { return $name !== null ? $this->query[$name] : $this->query; } @@ -440,7 +408,7 @@ private function renameQueryOptions(array $options, array $rename): array * * @return Iterator|UpdateResult|InsertOneResult|DeleteResult|array|object|int|null */ - private function runQuery() + private function runQuery(): array|object|int|null { $options = $this->options; diff --git a/src/Query/QueryExpressionVisitor.php b/src/Query/QueryExpressionVisitor.php index 83ff341825..3793683248 100644 --- a/src/Query/QueryExpressionVisitor.php +++ b/src/Query/QueryExpressionVisitor.php @@ -109,10 +109,8 @@ public function walkCompositeExpression(CompositeExpression $expr): Expr * Converts a value expression into the target query language part. * * @see ExpressionVisitor::walkValue() - * - * @return mixed */ - public function walkValue(Value $value) + public function walkValue(Value $value): mixed { return $value->getValue(); } diff --git a/src/Query/ReferencePrimer.php b/src/Query/ReferencePrimer.php index d038974f4d..10ae4cfad3 100644 --- a/src/Query/ReferencePrimer.php +++ b/src/Query/ReferencePrimer.php @@ -40,22 +40,10 @@ * @phpstan-import-type FieldMapping from ClassMetadata * @phpstan-import-type Hints from UnitOfWork */ -final class ReferencePrimer +final readonly class ReferencePrimer { - /** - * The DocumentManager instance. - */ - private DocumentManager $dm; - - /** - * The UnitOfWork instance. - */ - private UnitOfWork $uow; - - public function __construct(DocumentManager $dm, UnitOfWork $uow) + public function __construct(private DocumentManager $dm, private UnitOfWork $uow) { - $this->dm = $dm; - $this->uow = $uow; } /** @@ -65,11 +53,11 @@ public function __construct(DocumentManager $dm, UnitOfWork $uow) * the default primer defined in the constructor. If $primer is not * callable, the default primer will be used. * - * @param ClassMetadata $class Class metadata for the document - * @param array|Traversable $documents Documents containing references to prime - * @param string $fieldName Field name containing references to prime - * @param array $hints UnitOfWork hints for priming queries - * @param callable|null $primer Optional primer callable + * @param ClassMetadata $class Class metadata for the document + * @param iterable $documents Documents containing references to prime + * @param string $fieldName Field name containing references to prime + * @param array $hints UnitOfWork hints for priming queries + * @param callable|null $primer Optional primer callable * @phpstan-param Hints $hints * * @throws InvalidArgumentException If the mapped field is not the owning @@ -77,7 +65,7 @@ public function __construct(DocumentManager $dm, UnitOfWork $uow) * @throws LogicException If the mapped field is a simple reference and is * missing a target document class. */ - public function primeReferences(ClassMetadata $class, $documents, string $fieldName, array $hints = [], ?callable $primer = null): void + public function primeReferences(ClassMetadata $class, iterable $documents, string $fieldName, array $hints = [], ?callable $primer = null): void { $data = $this->parseDotSyntaxForPrimer($fieldName, $class, $documents); $mapping = $data['mapping']; @@ -136,12 +124,12 @@ public function primeReferences(ClassMetadata $class, $documents, string $fieldN * ... but you cannot prime this: myDocument.embeddedDocument.referencedDocuments.referencedDocument(s) * This addresses Issue #624. * - * @param array|Traversable $documents - * @param FieldMapping|null $mapping + * @param iterable $documents + * @param FieldMapping|null $mapping * * @return array{fieldName: string, class: ClassMetadata, documents: array|Traversable, mapping: FieldMapping} */ - private function parseDotSyntaxForPrimer(string $fieldName, ClassMetadata $class, $documents, ?array $mapping = null): array + private function parseDotSyntaxForPrimer(string $fieldName, ClassMetadata $class, iterable $documents, ?array $mapping = null): array { // Recursion passthrough: if ($mapping !== null) { diff --git a/src/Repository/DefaultGridFSRepository.php b/src/Repository/DefaultGridFSRepository.php index 030fb112f8..f31fe8fbf0 100644 --- a/src/Repository/DefaultGridFSRepository.php +++ b/src/Repository/DefaultGridFSRepository.php @@ -24,7 +24,7 @@ class DefaultGridFSRepository extends DocumentRepository implements GridFSRepository { /** @see Bucket::openDownloadStream() */ - public function openDownloadStream($id) + public function openDownloadStream(mixed $id) { try { return $this->getDocumentBucket()->openDownloadStream($this->class->getDatabaseIdentifierValue($id)); @@ -34,7 +34,7 @@ public function openDownloadStream($id) } /** @see Bucket::downloadToStream */ - public function downloadToStream($id, $destination): void + public function downloadToStream(mixed $id, $destination): void { try { $this->getDocumentBucket()->downloadToStream($this->class->getDatabaseIdentifierValue($id), $destination); @@ -52,7 +52,7 @@ public function openUploadStream(string $filename, ?UploadOptions $uploadOptions } /** @see Bucket::uploadFromStream */ - public function uploadFromStream(string $filename, $source, ?UploadOptions $uploadOptions = null) + public function uploadFromStream(string $filename, $source, ?UploadOptions $uploadOptions = null): object { $options = $this->prepareOptions($uploadOptions); @@ -62,7 +62,7 @@ public function uploadFromStream(string $filename, $source, ?UploadOptions $uplo return $this->dm->getReference($this->getClassName(), $documentIdentifier); } - public function uploadFromFile(string $source, ?string $filename = null, ?UploadOptions $uploadOptions = null) + public function uploadFromFile(string $source, ?string $filename = null, ?UploadOptions $uploadOptions = null): object { $resource = fopen($source, 'r'); if ($resource === false) { diff --git a/src/Repository/DocumentRepository.php b/src/Repository/DocumentRepository.php index dad3120add..629c730069 100644 --- a/src/Repository/DocumentRepository.php +++ b/src/Repository/DocumentRepository.php @@ -38,16 +38,10 @@ class DocumentRepository implements ObjectRepository, Selectable { /** @var class-string */ - protected $documentName; - - /** @var DocumentManager */ - protected $dm; - - /** @var UnitOfWork */ - protected $uow; + protected string $documentName; /** @var ClassMetadata */ - protected $class; + protected ClassMetadata $class; /** * Initializes this instance with the specified document manager, unit of work and class metadata. @@ -57,11 +51,9 @@ class DocumentRepository implements ObjectRepository, Selectable * @param ClassMetadata $classMetadata The class metadata. * @phpstan-param ClassMetadata $classMetadata The class metadata. */ - public function __construct(DocumentManager $dm, UnitOfWork $uow, ClassMetadata $classMetadata) + public function __construct(protected DocumentManager $dm, protected UnitOfWork $uow, ClassMetadata $classMetadata) { $this->documentName = $classMetadata->name; - $this->dm = $dm; - $this->uow = $uow; $this->class = $classMetadata; } @@ -92,7 +84,7 @@ public function createAggregationBuilder(): AggregationBuilder * @throws MappingException * @throws LockException */ - public function find($id, int $lockMode = LockMode::NONE, ?int $lockVersion = null): ?object + public function find(mixed $id, int $lockMode = LockMode::NONE, ?int $lockVersion = null): ?object { if ($id === null) { return null; @@ -151,11 +143,8 @@ public function findAll(): array /** * Finds documents by a set of criteria. - * - * @param int|null $limit - * @param int|null $offset */ - public function findBy(array $criteria, ?array $orderBy = null, $limit = null, $offset = null): array + public function findBy(array $criteria, ?array $orderBy = null, ?int $limit = null, ?int $offset = null): array { return $this->getDocumentPersister()->loadAll($criteria, $orderBy, $limit, $offset)->toArray(); } diff --git a/src/Repository/GridFSRepository.php b/src/Repository/GridFSRepository.php index e166640c77..cb4f558297 100644 --- a/src/Repository/GridFSRepository.php +++ b/src/Repository/GridFSRepository.php @@ -19,7 +19,7 @@ interface GridFSRepository extends ObjectRepository * * @return resource */ - public function openDownloadStream($id); + public function openDownloadStream(mixed $id); /** * Writes the contents of a GridFS file to a writable stream. @@ -27,7 +27,7 @@ public function openDownloadStream($id); * @param mixed $id File ID * @param resource $destination Writable Stream */ - public function downloadToStream($id, $destination): void; + public function downloadToStream(mixed $id, $destination): void; /** * Opens a writable stream for writing a GridFS file. @@ -43,7 +43,7 @@ public function openUploadStream(string $filename, ?UploadOptions $uploadOptions * * @return object The newly created GridFS file */ - public function uploadFromStream(string $filename, $source, ?UploadOptions $uploadOptions = null); + public function uploadFromStream(string $filename, $source, ?UploadOptions $uploadOptions = null): object; /** * Writes the contents of a file to a GridFS file. @@ -52,5 +52,5 @@ public function uploadFromStream(string $filename, $source, ?UploadOptions $uplo * * @return object The newly created GridFS file */ - public function uploadFromFile(string $source, ?string $filename = null, ?UploadOptions $uploadOptions = null); + public function uploadFromFile(string $source, ?string $filename = null, ?UploadOptions $uploadOptions = null): object; } diff --git a/src/Repository/UploadOptions.php b/src/Repository/UploadOptions.php index 6d022389a5..2ccea4aa2d 100644 --- a/src/Repository/UploadOptions.php +++ b/src/Repository/UploadOptions.php @@ -6,12 +6,7 @@ final class UploadOptions { - /** @var mixed */ - public $id; - - /** @var int|null */ - public $chunkSizeBytes; - - /** @var object|null */ - public $metadata; + public mixed $id = null; + public ?int $chunkSizeBytes = null; + public ?object $metadata = null; } diff --git a/src/SchemaManager.php b/src/SchemaManager.php index 342f2d1191..7226f0220e 100644 --- a/src/SchemaManager.php +++ b/src/SchemaManager.php @@ -46,15 +46,15 @@ */ final class SchemaManager { - private const GRIDFS_FILE_COLLECTION_INDEX = ['files_id' => 1, 'n' => 1]; + private const array GRIDFS_FILE_COLLECTION_INDEX = ['files_id' => 1, 'n' => 1]; - private const GRIDFS_CHUNKS_COLLECTION_INDEX = ['filename' => 1, 'uploadDate' => 1]; + private const array GRIDFS_CHUNKS_COLLECTION_INDEX = ['filename' => 1, 'uploadDate' => 1]; - private const CODE_SHARDING_ALREADY_INITIALIZED = 23; - private const CODE_COMMAND_NOT_SUPPORTED = 115; - private const CODE_SEARCH_NOT_ENABLED = 31082; + private const int CODE_SHARDING_ALREADY_INITIALIZED = 23; + private const int CODE_COMMAND_NOT_SUPPORTED = 115; + private const int CODE_SEARCH_NOT_ENABLED = 31082; - private const ALLOWED_MISSING_INDEX_OPTIONS = [ + private const array ALLOWED_MISSING_INDEX_OPTIONS = [ 'background', 'partialFilterExpression', 'sparse', diff --git a/src/Tools/Console/Command/Schema/AbstractCommand.php b/src/Tools/Console/Command/Schema/AbstractCommand.php index ac9b5bdad9..cf10fdf44c 100644 --- a/src/Tools/Console/Command/Schema/AbstractCommand.php +++ b/src/Tools/Console/Command/Schema/AbstractCommand.php @@ -38,62 +38,38 @@ private function configureCommonOptions(): void ->addOption('journal', null, InputOption::VALUE_REQUIRED, 'An optional journal option for the write concern that will be used for all schema operations. Using this option without a w option will cause an exception to be thrown.'); } - /** - * @return void - * - * @throws BadMethodCallException - */ - protected function processDocumentCollection(SchemaManager $sm, string $document, ?int $maxTimeMs, ?WriteConcern $writeConcern) + /** @throws BadMethodCallException */ + protected function processDocumentCollection(SchemaManager $sm, string $document, ?int $maxTimeMs, ?WriteConcern $writeConcern): void { throw new BadMethodCallException('This command does not support collections'); } - /** - * @return void - * - * @throws BadMethodCallException - */ - protected function processCollection(SchemaManager $sm, ?int $maxTimeMs, ?WriteConcern $writeConcern) + /** @throws BadMethodCallException */ + protected function processCollection(SchemaManager $sm, ?int $maxTimeMs, ?WriteConcern $writeConcern): void { throw new BadMethodCallException('This command does not support collections'); } - /** - * @return void - * - * @throws BadMethodCallException - */ - protected function processDocumentDb(SchemaManager $sm, string $document, ?int $maxTimeMs, ?WriteConcern $writeConcern) + /** @throws BadMethodCallException */ + protected function processDocumentDb(SchemaManager $sm, string $document, ?int $maxTimeMs, ?WriteConcern $writeConcern): void { throw new BadMethodCallException('This command does not support databases'); } - /** - * @return void - * - * @throws BadMethodCallException - */ - protected function processDb(SchemaManager $sm, ?int $maxTimeMs, ?WriteConcern $writeConcern) + /** @throws BadMethodCallException */ + protected function processDb(SchemaManager $sm, ?int $maxTimeMs, ?WriteConcern $writeConcern): void { throw new BadMethodCallException('This command does not support databases'); } - /** - * @return void - * - * @throws BadMethodCallException - */ - protected function processDocumentIndex(SchemaManager $sm, string $document, ?int $maxTimeMs, ?WriteConcern $writeConcern) + /** @throws BadMethodCallException */ + protected function processDocumentIndex(SchemaManager $sm, string $document, ?int $maxTimeMs, ?WriteConcern $writeConcern): void { throw new BadMethodCallException('This command does not support indexes'); } - /** - * @return void - * - * @throws BadMethodCallException - */ - protected function processIndex(SchemaManager $sm, ?int $maxTimeMs, ?WriteConcern $writeConcern) + /** @throws BadMethodCallException */ + protected function processIndex(SchemaManager $sm, ?int $maxTimeMs, ?WriteConcern $writeConcern): void { throw new BadMethodCallException('This command does not support indexes'); } @@ -114,20 +90,17 @@ protected function processDocumentSearchIndex(SchemaManager $sm, string $documen throw new BadMethodCallException('This command does not support search indexes'); } - /** @return SchemaManager */ - protected function getSchemaManager() + protected function getSchemaManager(): SchemaManager { return $this->getDocumentManager()->getSchemaManager(); } - /** @return DocumentManager */ - protected function getDocumentManager() + protected function getDocumentManager(): DocumentManager { return $this->getHelper('documentManager')->getDocumentManager(); } - /** @return ClassMetadataFactoryInterface */ - protected function getMetadataFactory() + protected function getMetadataFactory(): ClassMetadataFactoryInterface { return $this->getDocumentManager()->getMetadataFactory(); } diff --git a/src/Tools/Console/Command/Schema/CreateCommand.php b/src/Tools/Console/Command/Schema/CreateCommand.php index 661368d97c..34ca6a7b59 100644 --- a/src/Tools/Console/Command/Schema/CreateCommand.php +++ b/src/Tools/Console/Command/Schema/CreateCommand.php @@ -91,22 +91,22 @@ protected function execute(InputInterface $input, OutputInterface $output): int return $isErrored ? 255 : 0; } - protected function processDocumentCollection(SchemaManager $sm, string $document, ?int $maxTimeMs, ?WriteConcern $writeConcern) + protected function processDocumentCollection(SchemaManager $sm, string $document, ?int $maxTimeMs, ?WriteConcern $writeConcern): void { $sm->createDocumentCollection($document, $maxTimeMs, $writeConcern); } - protected function processCollection(SchemaManager $sm, ?int $maxTimeMs, ?WriteConcern $writeConcern) + protected function processCollection(SchemaManager $sm, ?int $maxTimeMs, ?WriteConcern $writeConcern): void { $sm->createCollections($maxTimeMs, $writeConcern); } - protected function processDocumentIndex(SchemaManager $sm, string $document, ?int $maxTimeMs, ?WriteConcern $writeConcern, bool $background = false) + protected function processDocumentIndex(SchemaManager $sm, string $document, ?int $maxTimeMs, ?WriteConcern $writeConcern, bool $background = false): void { $sm->ensureDocumentIndexes($document, $maxTimeMs, $writeConcern, $background); } - protected function processIndex(SchemaManager $sm, ?int $maxTimeMs, ?WriteConcern $writeConcern, bool $background = false) + protected function processIndex(SchemaManager $sm, ?int $maxTimeMs, ?WriteConcern $writeConcern, bool $background = false): void { $sm->ensureIndexes($maxTimeMs, $writeConcern, $background); } @@ -121,16 +121,14 @@ protected function processSearchIndex(SchemaManager $sm): void $sm->createSearchIndexes(); } - /** @return void */ - protected function processDocumentProxy(SchemaManager $sm, string $document) + protected function processDocumentProxy(SchemaManager $sm, string $document): void { $classMetadata = $this->getMetadataFactory()->getMetadataFor($document); $this->getDocumentManager()->getProxyFactory()->generateProxyClasses([$classMetadata]); } - /** @return void */ - protected function processProxy(SchemaManager $sm) + protected function processProxy(SchemaManager $sm): void { $metadatas = $this->getMetadataFactory()->getAllMetadata(); $this->getDocumentManager()->getProxyFactory()->generateProxyClasses($metadatas); diff --git a/src/Tools/Console/Command/Schema/DropCommand.php b/src/Tools/Console/Command/Schema/DropCommand.php index c1cb073aed..ffcd94d69b 100644 --- a/src/Tools/Console/Command/Schema/DropCommand.php +++ b/src/Tools/Console/Command/Schema/DropCommand.php @@ -91,32 +91,32 @@ protected function execute(InputInterface $input, OutputInterface $output): int return $isErrored ? 255 : 0; } - protected function processDocumentCollection(SchemaManager $sm, string $document, ?int $maxTimeMs, ?WriteConcern $writeConcern) + protected function processDocumentCollection(SchemaManager $sm, string $document, ?int $maxTimeMs, ?WriteConcern $writeConcern): void { $sm->dropDocumentCollection($document, $maxTimeMs, $writeConcern); } - protected function processCollection(SchemaManager $sm, ?int $maxTimeMs, ?WriteConcern $writeConcern) + protected function processCollection(SchemaManager $sm, ?int $maxTimeMs, ?WriteConcern $writeConcern): void { $sm->dropCollections($maxTimeMs, $writeConcern); } - protected function processDocumentDb(SchemaManager $sm, string $document, ?int $maxTimeMs, ?WriteConcern $writeConcern) + protected function processDocumentDb(SchemaManager $sm, string $document, ?int $maxTimeMs, ?WriteConcern $writeConcern): void { $sm->dropDocumentDatabase($document, $maxTimeMs, $writeConcern); } - protected function processDb(SchemaManager $sm, ?int $maxTimeMs, ?WriteConcern $writeConcern) + protected function processDb(SchemaManager $sm, ?int $maxTimeMs, ?WriteConcern $writeConcern): void { $sm->dropDatabases($maxTimeMs, $writeConcern); } - protected function processDocumentIndex(SchemaManager $sm, string $document, ?int $maxTimeMs, ?WriteConcern $writeConcern) + protected function processDocumentIndex(SchemaManager $sm, string $document, ?int $maxTimeMs, ?WriteConcern $writeConcern): void { $sm->deleteDocumentIndexes($document, $maxTimeMs, $writeConcern); } - protected function processIndex(SchemaManager $sm, ?int $maxTimeMs, ?WriteConcern $writeConcern) + protected function processIndex(SchemaManager $sm, ?int $maxTimeMs, ?WriteConcern $writeConcern): void { $sm->deleteIndexes($maxTimeMs, $writeConcern); } diff --git a/src/Tools/Console/Command/Schema/UpdateCommand.php b/src/Tools/Console/Command/Schema/UpdateCommand.php index b48471172c..111cecb213 100644 --- a/src/Tools/Console/Command/Schema/UpdateCommand.php +++ b/src/Tools/Console/Command/Schema/UpdateCommand.php @@ -75,24 +75,22 @@ protected function execute(InputInterface $input, OutputInterface $output): int return $isErrored ? 255 : 0; } - protected function processDocumentIndex(SchemaManager $sm, string $document, ?int $maxTimeMs, ?WriteConcern $writeConcern) + protected function processDocumentIndex(SchemaManager $sm, string $document, ?int $maxTimeMs, ?WriteConcern $writeConcern): void { $sm->updateDocumentIndexes($document, $maxTimeMs, $writeConcern); } - protected function processIndex(SchemaManager $sm, ?int $maxTimeMs, ?WriteConcern $writeConcern) + protected function processIndex(SchemaManager $sm, ?int $maxTimeMs, ?WriteConcern $writeConcern): void { $sm->updateIndexes($maxTimeMs, $writeConcern); } - /** @return void */ - protected function processDocumentValidator(SchemaManager $sm, string $document, ?int $maxTimeMs, ?WriteConcern $writeConcern) + protected function processDocumentValidator(SchemaManager $sm, string $document, ?int $maxTimeMs, ?WriteConcern $writeConcern): void { $sm->updateDocumentValidator($document, $maxTimeMs, $writeConcern); } - /** @return void */ - protected function processValidators(SchemaManager $sm, ?int $maxTimeMs, ?WriteConcern $writeConcern) + protected function processValidators(SchemaManager $sm, ?int $maxTimeMs, ?WriteConcern $writeConcern): void { $sm->updateValidators($maxTimeMs, $writeConcern); } diff --git a/src/Tools/Console/MetadataFilter.php b/src/Tools/Console/MetadataFilter.php index a77f4d819b..d04f7806cf 100644 --- a/src/Tools/Console/MetadataFilter.php +++ b/src/Tools/Console/MetadataFilter.php @@ -29,7 +29,7 @@ class MetadataFilter extends FilterIterator implements Countable * * @return ClassMetadata[] */ - public static function filter(array $metadatas, $filter): array + public static function filter(array $metadatas, array|string $filter): array { $metadatas = new MetadataFilter(new ArrayIterator($metadatas), $filter); @@ -43,7 +43,7 @@ public static function filter(array $metadatas, $filter): array * @param string[]|string $filter * @param ArrayIterator> $metadata */ - public function __construct(ArrayIterator $metadata, $filter) + public function __construct(ArrayIterator $metadata, array|string $filter) { $this->_filter = (array) $filter; diff --git a/src/Tools/ResolveTargetDocumentListener.php b/src/Tools/ResolveTargetDocumentListener.php index 1a0164ee4e..062dfe83e9 100644 --- a/src/Tools/ResolveTargetDocumentListener.php +++ b/src/Tools/ResolveTargetDocumentListener.php @@ -27,7 +27,7 @@ class ResolveTargetDocumentListener implements EventSubscriber /** @var array */ private array $resolveTargetDocuments = []; - public function getSubscribedEvents() + public function getSubscribedEvents(): array { return [ Events::loadClassMetadata, @@ -52,12 +52,8 @@ private function getRealClassName(string $className): string return ltrim($className, '\\'); } - /** - * @internal this is an event callback, and should not be called directly - * - * @return void - */ - public function onClassMetadataNotFound(OnClassMetadataNotFoundEventArgs $args) + /** @internal this is an event callback, and should not be called directly */ + public function onClassMetadataNotFound(OnClassMetadataNotFoundEventArgs $args): void { if (! array_key_exists($args->getClassName(), $this->resolveTargetDocuments)) { return; diff --git a/src/Types/BinDataByteArrayType.php b/src/Types/BinDataByteArrayType.php index a197e9b8da..0dc7268e85 100644 --- a/src/Types/BinDataByteArrayType.php +++ b/src/Types/BinDataByteArrayType.php @@ -14,6 +14,5 @@ */ class BinDataByteArrayType extends BinDataType { - /** @var int */ - protected $binDataType = Binary::TYPE_OLD_BINARY; + protected int $binDataType = Binary::TYPE_OLD_BINARY; } diff --git a/src/Types/BinDataCustomType.php b/src/Types/BinDataCustomType.php index 9c6de5bac4..60a8b1b21e 100644 --- a/src/Types/BinDataCustomType.php +++ b/src/Types/BinDataCustomType.php @@ -11,6 +11,5 @@ */ class BinDataCustomType extends BinDataType { - /** @var int */ - protected $binDataType = Binary::TYPE_USER_DEFINED; + protected int $binDataType = Binary::TYPE_USER_DEFINED; } diff --git a/src/Types/BinDataFuncType.php b/src/Types/BinDataFuncType.php index a8ab3006cb..2978a6ab88 100644 --- a/src/Types/BinDataFuncType.php +++ b/src/Types/BinDataFuncType.php @@ -11,6 +11,5 @@ */ class BinDataFuncType extends BinDataType { - /** @var int */ - protected $binDataType = Binary::TYPE_FUNCTION; + protected int $binDataType = Binary::TYPE_FUNCTION; } diff --git a/src/Types/BinDataMD5Type.php b/src/Types/BinDataMD5Type.php index 7ff562facb..fd103bd893 100644 --- a/src/Types/BinDataMD5Type.php +++ b/src/Types/BinDataMD5Type.php @@ -14,6 +14,5 @@ */ class BinDataMD5Type extends BinDataType { - /** @var int */ - protected $binDataType = Binary::TYPE_MD5; + protected int $binDataType = Binary::TYPE_MD5; } diff --git a/src/Types/BinDataType.php b/src/Types/BinDataType.php index 662ac63d2f..da33e66914 100644 --- a/src/Types/BinDataType.php +++ b/src/Types/BinDataType.php @@ -17,10 +17,8 @@ class BinDataType extends Type * Data type for binary data * * @see http://bsonspec.org/#/specification - * - * @var int */ - protected $binDataType = Binary::TYPE_GENERIC; + protected int $binDataType = Binary::TYPE_GENERIC; public function convertToDatabaseValue($value) { diff --git a/src/Types/BinDataUUIDRFC4122Type.php b/src/Types/BinDataUUIDRFC4122Type.php index d7ead249e5..d5fa46e161 100644 --- a/src/Types/BinDataUUIDRFC4122Type.php +++ b/src/Types/BinDataUUIDRFC4122Type.php @@ -11,6 +11,5 @@ */ class BinDataUUIDRFC4122Type extends BinDataType { - /** @var int */ - protected $binDataType = Binary::TYPE_UUID; + protected int $binDataType = Binary::TYPE_UUID; } diff --git a/src/Types/BinDataUUIDType.php b/src/Types/BinDataUUIDType.php index 7366496ce2..92e2a3fe7c 100644 --- a/src/Types/BinDataUUIDType.php +++ b/src/Types/BinDataUUIDType.php @@ -14,6 +14,5 @@ */ class BinDataUUIDType extends BinDataType { - /** @var int */ - protected $binDataType = Binary::TYPE_OLD_UUID; + protected int $binDataType = Binary::TYPE_OLD_UUID; } diff --git a/src/UnitOfWork.php b/src/UnitOfWork.php index 9fa61a158a..cb5eec289d 100644 --- a/src/UnitOfWork.php +++ b/src/UnitOfWork.php @@ -77,30 +77,30 @@ final class UnitOfWork implements PropertyChangedListener /** * A document is in MANAGED state when its persistence is managed by a DocumentManager. */ - public const STATE_MANAGED = 1; + public const int STATE_MANAGED = 1; /** * A document is new if it has just been instantiated (i.e. using the "new" operator) * and is not (yet) managed by a DocumentManager. */ - public const STATE_NEW = 2; + public const int STATE_NEW = 2; /** * A detached document is an instance with a persistent identity that is not * (or no longer) associated with a DocumentManager (and a UnitOfWork). */ - public const STATE_DETACHED = 3; + public const int STATE_DETACHED = 3; /** * A removed document instance is an instance with a persistent identity, * associated with a DocumentManager, whose persistent state has been * deleted (or is scheduled for deletion). */ - public const STATE_REMOVED = 4; + public const int STATE_REMOVED = 4; /** @internal */ - public const DEPRECATED_WRITE_OPTIONS = ['fsync', 'safe', 'w']; - private const TRANSACTION_OPTIONS = [ + public const array DEPRECATED_WRITE_OPTIONS = ['fsync', 'safe', 'w']; + private const array TRANSACTION_OPTIONS = [ 'maxCommitTimeMS' => 1, 'readConcern' => 1, 'readPreference' => 1, @@ -966,7 +966,7 @@ public function computeChangeSets(): void * * @throws InvalidArgumentException */ - private function computeAssociationChanges(object $parentDocument, array $assoc, $value): void + private function computeAssociationChanges(object $parentDocument, array $assoc, mixed $value): void { $isNewParentDocument = isset($this->scheduledDocumentInsertions[spl_object_id($parentDocument)]); $class = $this->dm->getClassMetadata($parentDocument::class); @@ -1627,7 +1627,7 @@ public function removeFromIdentityMap(object $document): bool * * @template T of object */ - public function getById($id, ClassMetadata $class): object + public function getById(mixed $id, ClassMetadata $class): object { if (! $class->identifier) { throw new InvalidArgumentException(sprintf('Class "%s" does not have an identifier', $class->name)); @@ -1647,7 +1647,7 @@ public function getById($id, ClassMetadata $class): object * @param mixed $id Document identifier * @phpstan-param ClassMetadata $class * - * @return mixed The found document or FALSE. + * @return object|false The found document or FALSE. * @phpstan-return T|false * * @throws InvalidArgumentException If the class does not have an identifier. @@ -1656,7 +1656,7 @@ public function getById($id, ClassMetadata $class): object * * @ phpstan-suppress InvalidReturnStatement, InvalidReturnType because of the inability of defining a generic property map */ - public function tryGetById($id, ClassMetadata $class) + public function tryGetById(mixed $id, ClassMetadata $class): object|false { if (! $class->identifier) { throw new InvalidArgumentException(sprintf('Class "%s" does not have an identifier', $class->name)); @@ -1715,10 +1715,8 @@ private function getIdForIdentityMap(object $document): string * Checks whether an identifier exists in the identity map. * * @internal - * - * @param mixed $id */ - public function containsId($id, string $rootClassName): bool + public function containsId(mixed $id, string $rootClassName): bool { return isset($this->identityMap[$rootClassName][serialize($id)]); } @@ -2871,10 +2869,8 @@ public function setOriginalDocumentData(object $document, array $data): void * Sets a property value of the original data array of a document. * * @internal - * - * @param mixed $value */ - public function setOriginalDocumentProperty(int $oid, string $property, $value): void + public function setOriginalDocumentProperty(int $oid, string $property, mixed $value): void { $this->originalDocumentData[$oid][$property] = $value; } @@ -2884,7 +2880,7 @@ public function setOriginalDocumentProperty(int $oid, string $property, $value): * * @return mixed The identifier value */ - public function getDocumentIdentifier(object $document) + public function getDocumentIdentifier(object $document): mixed { return $this->documentIdentifiers[spl_object_id($document)] ?? null; } @@ -2932,7 +2928,7 @@ public function size(): int * @param mixed $id The identifier values. * @param array $data */ - public function registerManaged(object $document, $id, array $data): void + public function registerManaged(object $document, mixed $id, array $data): void { $oid = spl_object_id($document); $class = $this->dm->getClassMetadata($document::class); @@ -2968,7 +2964,7 @@ public function clearDocumentChangeSet(int $oid): void * @param mixed $oldValue The old value of the property. * @param mixed $newValue The new value of the property. */ - public function propertyChanged($sender, $propertyName, $oldValue, $newValue): void + public function propertyChanged(object $sender, string $propertyName, mixed $oldValue, mixed $newValue): void { $oid = spl_object_id($sender); $class = $this->dm->getClassMetadata($sender::class); diff --git a/src/Utility/LifecycleEventManager.php b/src/Utility/LifecycleEventManager.php index 4214c01568..a42bea1bf3 100644 --- a/src/Utility/LifecycleEventManager.php +++ b/src/Utility/LifecycleEventManager.php @@ -30,7 +30,7 @@ final class LifecycleEventManager /** @var array> */ private array $transactionalEvents = []; - public function __construct(private DocumentManager $dm, private UnitOfWork $uow, private EventManager $evm) + public function __construct(private readonly DocumentManager $dm, private readonly UnitOfWork $uow, private readonly EventManager $evm) { } @@ -47,12 +47,8 @@ public function enableTransactionalMode(Session $session): void $this->session = $session; } - /** - * @param mixed $id - * - * @return bool Returns whether the exceptionDisabled flag was set - */ - public function documentNotFound(object $proxy, $id): bool + /** @return bool Returns whether the exceptionDisabled flag was set */ + public function documentNotFound(object $proxy, mixed $id): bool { $eventArgs = new DocumentNotFoundEventArgs($proxy, $this->dm, $id); $this->evm->dispatchEvent(Events::documentNotFound, $eventArgs); diff --git a/tests/Tests/DocumentManagerTest.php b/tests/Tests/DocumentManagerTest.php index a23f5612d8..2f7c33efdf 100644 --- a/tests/Tests/DocumentManagerTest.php +++ b/tests/Tests/DocumentManagerTest.php @@ -31,13 +31,13 @@ use Documents\Tournament\Participant; use Documents\Tournament\ParticipantSolo; use Documents\User; -use InvalidArgumentException; use MongoDB\BSON\ObjectId; use MongoDB\Client; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\IgnoreDeprecations; use RuntimeException; use stdClass; +use TypeError; class DocumentManagerTest extends BaseTestCase { @@ -136,7 +136,7 @@ public static function dataMethodsAffectedByNoObjectArguments(): array #[DataProvider('dataMethodsAffectedByNoObjectArguments')] public function testThrowsExceptionOnNonObjectValues(string $methodName): void { - $this->expectException(InvalidArgumentException::class); + $this->expectException(TypeError::class); $this->dm->$methodName(null); } diff --git a/tests/Tests/Functional/Ticket/GH2158Test.php b/tests/Tests/Functional/Ticket/GH2158Test.php index f01456ce21..9924c1a28e 100644 --- a/tests/Tests/Functional/Ticket/GH2158Test.php +++ b/tests/Tests/Functional/Ticket/GH2158Test.php @@ -15,7 +15,7 @@ public function testDiscriminatorMapCreationType(): void $this->dm->persist($obj); $this->dm->flush(); - self::assertEquals($this->dm->find(GH2158Abstract::class, $obj->getId()), $obj); + self::assertSame($obj, $this->dm->find(GH2158Abstract::class, $obj->getId())); } } diff --git a/tests/Tests/Query/BuilderTest.php b/tests/Tests/Query/BuilderTest.php index 5efcdbbd33..abe412c8c4 100644 --- a/tests/Tests/Query/BuilderTest.php +++ b/tests/Tests/Query/BuilderTest.php @@ -29,13 +29,6 @@ class BuilderTest extends BaseTestCase { - public function testPrimeRequiresBooleanOrCallable(): void - { - $this->expectException(InvalidArgumentException::class); - $this->dm->createQueryBuilder(User::class) - ->field('groups')->prime(1); - } - public function testReferencesGoesThroughDiscriminatorMap(): void { $f = new Feature('Smarter references');