diff --git a/.gitignore b/.gitignore index 9289795d18..9158da40b5 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,5 @@ tests/PersistentCollections/* phpunit.xml composer.lock vendor/ +.phpcs-cache +phpcs.xml diff --git a/.travis.yml b/.travis.yml index a0da4148a7..d51e9ccb3b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -43,11 +43,17 @@ jobs: - composer update --prefer-lowest - stage: Code Quality - php: 7.2 - env: SERVER_VERSION="3.6" KEY_ID="2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5" + php: 7.1 + env: STATIC_ANALYSIS SERVER_VERSION="3.6" KEY_ID="2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5" script: - vendor/bin/phpstan analyse -l 1 lib + - stage: Code Quality + php: 7.1 + env: CODING_STANDARDS SERVER_VERSION="3.6" KEY_ID="2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5" + script: + - vendor/bin/phpcs + before_install: - mv ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/xdebug.ini{,.disabled} || echo "xdebug not available" - sudo apt-key adv --keyserver ${KEY_SERVER} --recv ${KEY_ID} diff --git a/composer.json b/composer.json index 22dd2ac8ea..79d32b00be 100644 --- a/composer.json +++ b/composer.json @@ -26,7 +26,8 @@ "require-dev": { "phpunit/phpunit": "^7.0", "jmikola/geojson": "^1.0", - "phpstan/phpstan": "^0.9.2" + "phpstan/phpstan": "^0.9.2", + "doctrine/coding-standard": "^4.0" }, "autoload": { "psr-0": { "Doctrine\\ODM\\MongoDB": "lib/" } diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Builder.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Builder.php index e1fcd0cd0f..ee2657ae0f 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Builder.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Builder.php @@ -1,15 +1,23 @@ getExpression(); }, + function (Stage $stage) { + return $stage->getExpression(); + }, $this->stages ); @@ -240,12 +247,12 @@ function (Stage $stage) { return $stage->getExpression(); }, /** * Returns a certain stage from the pipeline * - * @param integer $index + * @param int $index * @return Stage */ public function getStage($index) { - if ( ! isset($this->stages[$index])) { + if (! isset($this->stages[$index])) { throw new \OutOfRangeException("Could not find stage with index {$index}."); } @@ -311,7 +318,7 @@ public function indexStats() * * @see http://docs.mongodb.org/manual/reference/operator/aggregation/limit/ * - * @param integer $limit + * @param int $limit * @return Stage\Limit */ public function limit($limit) @@ -424,7 +431,7 @@ public function replaceRoot($expression = null) * * @see https://docs.mongodb.org/manual/reference/operator/aggregation/sample/ * - * @param integer $size + * @param int $size * @return Stage\Sample */ public function sample($size) @@ -438,7 +445,7 @@ public function sample($size) * * @see http://docs.mongodb.org/manual/reference/operator/aggregation/skip/ * - * @param integer $skip + * @param int $skip * @return Stage\Skip */ public function skip($skip) @@ -456,7 +463,7 @@ public function skip($skip) * @see http://docs.mongodb.org/manual/reference/operator/aggregation/sort/ * * @param array|string $fieldName Field name or array of field/order pairs - * @param integer|string $order Field order (if one field is specified) + * @param int|string $order Field order (if one field is specified) * @return Stage\Sort */ public function sort($fieldName, $order = null) @@ -497,7 +504,6 @@ public function unwind($fieldName) } /** - * @param Stage $stage * @return Stage */ protected function addStage(Stage $stage) @@ -524,18 +530,13 @@ private function applyFilters(array $query) } /** - * @return \Doctrine\ODM\MongoDB\Persisters\DocumentPersister + * @return DocumentPersister */ private function getDocumentPersister() { return $this->dm->getUnitOfWork()->getDocumentPersister($this->class->name); } - /** - * @param Cursor $cursor - * - * @return Iterator - */ private function prepareIterator(Cursor $cursor): Iterator { $class = null; diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Expr.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Expr.php index 6261455a48..cbd1004158 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Expr.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Expr.php @@ -1,10 +1,19 @@ currentField) { + if (! $this->currentField) { throw new \LogicException(($method ?: 'This method') . ' requires you set a current field using field().'); } } @@ -1732,5 +1707,4 @@ public function then($expression) return $this; } - } diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage.php index e439fde92b..df7724a0cb 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage.php @@ -1,5 +1,7 @@ - * @since 1.2 * @internal */ abstract class Stage @@ -19,9 +19,6 @@ abstract class Stage */ protected $builder; - /** - * @param Builder $builder - */ public function __construct(Builder $builder) { $this->builder = $builder; @@ -92,8 +89,6 @@ public function bucketAuto() * the pipeline returns an error. * * @see http://docs.mongodb.org/manual/reference/operator/aggregation/geoNear/ - * @since 1.5 - * * @return Stage\CollStats */ public function collStats() @@ -135,7 +130,7 @@ public function facet() * @see http://docs.mongodb.org/manual/reference/operator/aggregation/geoNear/ * * @param float|array|Point $x - * @param float $y + * @param float $y * @return Stage\GeoNear */ public function geoNear($x, $y = null) @@ -198,7 +193,7 @@ public function indexStats() * * @see http://docs.mongodb.org/manual/reference/operator/aggregation/limit/ * - * @param integer $limit + * @param int $limit * @return Stage\Limit */ public function limit($limit) @@ -298,7 +293,7 @@ public function replaceRoot($expression = null) * * @see https://docs.mongodb.org/manual/reference/operator/aggregation/sample/ * - * @param integer $size + * @param int $size * @return Stage\Sample */ public function sample($size) @@ -312,7 +307,7 @@ public function sample($size) * * @see http://docs.mongodb.org/manual/reference/operator/aggregation/skip/ * - * @param integer $skip + * @param int $skip * @return Stage\Skip */ public function skip($skip) @@ -343,7 +338,7 @@ public function sortByCount($expression) * @see http://docs.mongodb.org/manual/reference/operator/aggregation/sort/ * * @param array|string $fieldName Field name or array of field/order pairs - * @param integer|string $order Field order (if one field is specified) + * @param int|string $order Field order (if one field is specified) * @return Stage\Sort */ public function sort($fieldName, $order = null) diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/AbstractBucket.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/AbstractBucket.php index 7f6b5475d4..1bb990b0c7 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/AbstractBucket.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/AbstractBucket.php @@ -1,5 +1,7 @@ - * @since 1.5 */ abstract class AbstractBucket extends Stage { @@ -102,7 +107,7 @@ private function convertExpression($expression) } /** - * @return \Doctrine\ODM\MongoDB\Persisters\DocumentPersister + * @return DocumentPersister */ private function getDocumentPersister() { diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/AddFields.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/AddFields.php index 6cd1d014a3..445925d1d3 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/AddFields.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/AddFields.php @@ -1,11 +1,12 @@ */ final class AddFields extends Operator { @@ -15,7 +16,7 @@ final class AddFields extends Operator public function getExpression() { return [ - '$addFields' => $this->expr->getExpression() + '$addFields' => $this->expr->getExpression(), ]; } } diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Bucket.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Bucket.php index f72dd8f31f..bb4ee2d58c 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Bucket.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Bucket.php @@ -1,5 +1,7 @@ - * @since 1.5 */ abstract class AbstractOutput extends Stage { @@ -25,10 +25,6 @@ abstract class AbstractOutput extends Stage */ private $expr; - /** - * @param Builder $builder - * @param Stage\AbstractBucket $bucket - */ public function __construct(Builder $builder, Stage\AbstractBucket $bucket) { parent::__construct($builder); diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Bucket/BucketAutoOutput.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Bucket/BucketAutoOutput.php index 5a5eb24951..cc46f15f85 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Bucket/BucketAutoOutput.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Bucket/BucketAutoOutput.php @@ -1,5 +1,7 @@ - * @since 1.5 */ class BucketAutoOutput extends AbstractOutput { - /** - * @param Builder $builder - * @param Stage\BucketAuto $bucket - */ public function __construct(Builder $builder, Stage\BucketAuto $bucket) { parent::__construct($builder, $bucket); diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Bucket/BucketOutput.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Bucket/BucketOutput.php index 75c6f39c3c..ad23487597 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Bucket/BucketOutput.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Bucket/BucketOutput.php @@ -1,5 +1,7 @@ - * @since 1.5 */ class BucketOutput extends AbstractOutput { - /** - * @param Builder $builder - * @param Stage\Bucket $bucket - */ public function __construct(Builder $builder, Stage\Bucket $bucket) { parent::__construct($builder, $bucket); diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/BucketAuto.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/BucketAuto.php index 77cd311c6e..e9678a197f 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/BucketAuto.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/BucketAuto.php @@ -1,5 +1,7 @@ - * @since 1.5 */ class CollStats extends Stage { - const LATENCY_STATS_NONE = 0; - const LATENCY_STATS_SIMPLE = 1; - const LATENCY_STATS_HISTOGRAMS = 2; + public const LATENCY_STATS_NONE = 0; + public const LATENCY_STATS_SIMPLE = 1; + public const LATENCY_STATS_HISTOGRAMS = 2; /** * @var int @@ -27,9 +27,6 @@ class CollStats extends Stage */ private $storageStats = false; - /** - * @param Builder $builder - */ public function __construct(Builder $builder) { parent::__construct($builder); diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Count.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Count.php index 8e26b624b0..c6b8988d1d 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Count.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Count.php @@ -1,5 +1,7 @@ - * @since 1.5 */ class Count extends Stage { @@ -19,7 +19,6 @@ class Count extends Stage private $fieldName; /** - * @param Builder $builder * @param string $fieldName */ public function __construct(Builder $builder, $fieldName) @@ -35,7 +34,7 @@ public function __construct(Builder $builder, $fieldName) public function getExpression() { return [ - '$count' => $this->fieldName + '$count' => $this->fieldName, ]; } } diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Facet.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Facet.php index 10c3410af7..99e9052597 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Facet.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Facet.php @@ -1,15 +1,16 @@ - * @since 1.5 */ class Facet extends Stage { @@ -29,7 +30,9 @@ class Facet extends Stage public function getExpression() { return [ - '$facet' => array_map(function (Builder $builder) { return $builder->getPipeline(); }, $this->pipelines), + '$facet' => array_map(function (Builder $builder) { + return $builder->getPipeline(); + }, $this->pipelines), ]; } diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/GeoNear.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/GeoNear.php index 7e82f6a0ff..dc4c39b17b 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/GeoNear.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/GeoNear.php @@ -1,15 +1,16 @@ - * @since 1.2 */ class GeoNear extends Match { @@ -44,24 +45,23 @@ class GeoNear extends Match private $near; /** - * @var integer + * @var int */ private $num; /** - * @var boolean + * @var bool */ private $spherical = false; /** - * @var boolean + * @var bool */ private $uniqueDocs; /** - * @param Builder $builder * @param float|array|Point $x - * @param float $y + * @param float $y */ public function __construct(Builder $builder, $x, $y = null) { @@ -79,20 +79,18 @@ public function getExpression() 'near' => $this->near, 'spherical' => $this->spherical, 'distanceField' => $this->distanceField, - 'query' => $this->query->getQuery() + 'query' => $this->query->getQuery(), ]; foreach (['distanceMultiplier', 'includeLocs', 'maxDistance', 'minDistance', 'num', 'uniqueDocs'] as $option) { - if ( ! $this->$option) { + if (! $this->$option) { continue; } $geoNear[$option] = $this->$option; } - return [ - '$geoNear' => $geoNear - ]; + return ['$geoNear' => $geoNear]; } /** @@ -137,7 +135,7 @@ public function includeLocs($includeLocs) /** * The maximum number of documents to return. * - * @param integer $limit + * @param int $limit * @return $this */ public function limit($limit) @@ -164,7 +162,6 @@ public function maxDistance($maxDistance) * @param float $minDistance * @return $this * - * @since 1.3 */ public function minDistance($minDistance) { @@ -182,7 +179,7 @@ public function minDistance($minDistance) * used, the "spherical" option will default to true. * * @param float|array|Point $x - * @param float $y + * @param float $y * @return $this */ public function near($x, $y = null) @@ -200,12 +197,12 @@ public function near($x, $y = null) /** * The maximum number of documents to return. * - * @param integer $num + * @param int $num * @return $this */ public function num($num) { - $this->num = (integer) $num; + $this->num = (int) $num; return $this; } @@ -213,12 +210,12 @@ public function num($num) /** * Required if using a 2dsphere index. Determines how MongoDB calculates the distance. * - * @param boolean $spherical + * @param bool $spherical * @return $this */ public function spherical($spherical = true) { - $this->spherical = (boolean) $spherical; + $this->spherical = (bool) $spherical; return $this; } @@ -226,12 +223,12 @@ public function spherical($spherical = true) /** * If this value is true, the query returns a matching document once, even if more than one of the document’s location fields match the query. * - * @param boolean $uniqueDocs + * @param bool $uniqueDocs * @return $this */ public function uniqueDocs($uniqueDocs = true) { - $this->uniqueDocs = (boolean) $uniqueDocs; + $this->uniqueDocs = (bool) $uniqueDocs; return $this; } diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/GraphLookup.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/GraphLookup.php index d3a30ea77a..90ed370f21 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/GraphLookup.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/GraphLookup.php @@ -1,5 +1,7 @@ targetClass) { + if (! $this->targetClass) { $this->connectFromField = $connectFromField; return $this; } // connectFromField doesn't have to be a reference - in this case, just convert the field name - if ( ! $this->targetClass->hasReference($connectFromField)) { + if (! $this->targetClass->hasReference($connectFromField)) { $this->connectFromField = $this->convertTargetFieldName($connectFromField); return $this; } @@ -281,7 +285,7 @@ public function startWith($expression) */ private function fromReference($fieldName) { - if ( ! $this->class->hasReference($fieldName)) { + if (! $this->class->hasReference($fieldName)) { MappingException::referenceMappingNotFound($this->class->name, $fieldName); } @@ -330,7 +334,7 @@ private function convertTargetFieldName($fieldName) return array_map([$this, 'convertTargetFieldName'], $fieldName); } - if ( ! $this->targetClass) { + if (! $this->targetClass) { return $fieldName; } @@ -338,8 +342,7 @@ private function convertTargetFieldName($fieldName) } /** - * @param ClassMetadata $class - * @return \Doctrine\ODM\MongoDB\Persisters\DocumentPersister + * @return DocumentPersister */ private function getDocumentPersister(ClassMetadata $class) { @@ -348,7 +351,7 @@ private function getDocumentPersister(ClassMetadata $class) private function getReferencedFieldName($fieldName, array $mapping) { - if ( ! $mapping['isOwningSide']) { + if (! $mapping['isOwningSide']) { if (isset($mapping['repositoryMethod']) || ! isset($mapping['mappedBy'])) { throw MappingException::repositoryMethodLookupNotAllowed($this->class->name, $fieldName); } diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/GraphLookup/Match.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/GraphLookup/Match.php index 5f936a09c0..65541e8be8 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/GraphLookup/Match.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/GraphLookup/Match.php @@ -1,5 +1,7 @@ - * @since 1.2 */ class Group extends Operator { @@ -34,7 +34,7 @@ public function __construct(Builder $builder) public function getExpression() { return [ - '$group' => $this->expr->getExpression() + '$group' => $this->expr->getExpression(), ]; } @@ -195,7 +195,6 @@ public function push($expression) * @param mixed|Expr $expression * @return $this * - * @since 1.3 */ public function stdDevPop($expression) { @@ -214,7 +213,6 @@ public function stdDevPop($expression) * @param mixed|Expr $expression * @return $this * - * @since 1.3 */ public function stdDevSamp($expression) { diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/IndexStats.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/IndexStats.php index 6a71441898..8b427c6a8a 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/IndexStats.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/IndexStats.php @@ -1,5 +1,7 @@ - * @since 1.3 */ class IndexStats extends Stage { @@ -18,7 +18,7 @@ class IndexStats extends Stage public function getExpression() { return [ - '$indexStats' => new \stdClass() + '$indexStats' => new \stdClass(), ]; } } diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Limit.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Limit.php index 543ccc2589..efb45a52f8 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Limit.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Limit.php @@ -1,5 +1,7 @@ - * @since 1.2 */ class Limit extends Stage { /** - * @var integer + * @var int */ private $limit; /** - * @param Builder $builder - * @param integer $limit + * @param int $limit */ public function __construct(Builder $builder, $limit) { parent::__construct($builder); - $this->limit = (integer) $limit; + $this->limit = (int) $limit; } /** @@ -35,7 +34,7 @@ public function __construct(Builder $builder, $limit) public function getExpression() { return [ - '$limit' => $this->limit + '$limit' => $this->limit, ]; } } diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Lookup.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Lookup.php index 8f1c711f01..b53dfa4397 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Lookup.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Lookup.php @@ -1,5 +1,7 @@ $this->localField, 'foreignField' => $this->foreignField, 'as' => $this->as, - ] + ], ]; } @@ -170,9 +170,9 @@ public function foreignField($foreignField) return $this; } - protected function prepareFieldName($fieldName, ClassMetadata $class = null) + protected function prepareFieldName($fieldName, ?ClassMetadata $class = null) { - if ( ! $class) { + if (! $class) { return $fieldName; } @@ -237,7 +237,7 @@ private function fromReference($fieldName) } /** - * @return \Doctrine\ODM\MongoDB\Persisters\DocumentPersister + * @return DocumentPersister */ private function getDocumentPersister(ClassMetadata $class) { diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Match.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Match.php index f1b32d9820..ff68f44aed 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Match.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Match.php @@ -1,11 +1,14 @@ query->exists((boolean) $bool); + $this->query->exists((bool) $bool); return $this; } @@ -220,7 +223,6 @@ public function geoIntersects($geometry) * * @see Expr::geoWithin() * @see http://docs.mongodb.org/manual/reference/operator/geoWithin/ - * @param Geometry $geometry * @return $this */ public function geoWithin(Geometry $geometry) @@ -306,9 +308,9 @@ public function geoWithinCenterSphere($x, $y, $radius) * * @see Expr::geoWithinPolygon() * @see http://docs.mongodb.org/manual/reference/operator/polygon/ - * @param array $point1 First point of the polygon - * @param array $point2 Second point of the polygon - * @param array $point3 Third point of the polygon + * @param array $point1 First point of the polygon + * @param array $point2 Second point of the polygon + * @param array $point3 Third point of the polygon * @param array ...$points Additional points of the polygon * @return $this */ @@ -481,8 +483,8 @@ public function minDistance($minDistance) * * @see Expr::mod() * @see http://docs.mongodb.org/manual/reference/operator/mod/ - * @param float|integer $divisor - * @param float|integer $remainder + * @param float|int $divisor + * @param float|int $remainder * @return $this */ public function mod($divisor, $remainder = 0) @@ -574,12 +576,12 @@ public function references($document) * * @see Expr::size() * @see http://docs.mongodb.org/manual/reference/operator/size/ - * @param integer $size + * @param int $size * @return $this */ public function size($size) { - $this->query->size((integer) $size); + $this->query->size((int) $size); return $this; } @@ -608,7 +610,7 @@ public function text($search) * * @see Expr::type() * @see http://docs.mongodb.org/manual/reference/operator/type/ - * @param integer $type + * @param int $type * @return $this */ public function type($type) diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Operator.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Operator.php index 8874e6c3f1..02aef11848 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Operator.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Operator.php @@ -1,16 +1,17 @@ - * @since 1.2 * @method $this switch() * @method $this case(mixed|Expr $expression) * @method $this then(mixed|Expr $expression) @@ -35,7 +36,7 @@ public function __construct(Builder $builder) /** * @param string $method - * @param array $args + * @param array $args * @return $this */ public function __call($method, $args) @@ -56,7 +57,6 @@ public function __call($method, $args) * @param mixed|Expr $number * @return $this * - * @since 1.3 */ public function abs($number) { @@ -168,7 +168,6 @@ public function anyElementTrue($expression) * @param mixed|Expr $index * @return $this * - * @since 1.3 */ public function arrayElemAt($array, $index) { @@ -188,7 +187,6 @@ public function arrayElemAt($array, $index) * @param mixed|Expr $number * @return $this * - * @since 1.3 */ public function ceil($number) { @@ -250,7 +248,6 @@ public function concat($expression1, $expression2, ...$expressions) * @param mixed|Expr ...$arrays Additional expressions * @return $this * - * @since 1.3 */ public function concatArrays($array1, $array2, ...$arrays) { @@ -288,7 +285,7 @@ public function cond($if, $then, $else) * * @see http://docs.mongodb.org/manual/reference/operator/aggregation/dateToString/ * @see Expr::dateToString - * @param string $format + * @param string $format * @param mixed|Expr $expression * @return $this */ @@ -397,7 +394,6 @@ public function eq($expression1, $expression2) * @param mixed|Expr $exponent * @return $this * - * @since 1.3 */ public function exp($exponent) { @@ -448,7 +444,6 @@ public function field($fieldName) * @param mixed|Expr $cond * @return $this * - * @since 1.3 */ public function filter($input, $as, $cond) { @@ -468,7 +463,6 @@ public function filter($input, $as, $cond) * @param mixed|Expr $number * @return $this * - * @since 1.3 */ public function floor($number) { @@ -538,7 +532,6 @@ public function hour($expression) * * @see https://docs.mongodb.com/manual/reference/operator/aggregation/in/ * @see Expr::in - * @since 1.5 * @param mixed|Expr $expression * @param mixed|Expr $arrayExpression * @return $this @@ -557,11 +550,10 @@ public function in($expression, $arrayExpression) * * @see https://docs.mongodb.com/manual/reference/operator/aggregation/indexOfArray/ * @see Expr::indexOfArray - * @since 1.5 - * @param mixed|Expr $arrayExpression Can be any valid expression as long as it resolves to an array. + * @param mixed|Expr $arrayExpression Can be any valid expression as long as it resolves to an array. * @param mixed|Expr $searchExpression Can be any valid expression. - * @param mixed|Expr $start Optional. An integer, or a number that can be represented as integers (such as 2.0), that specifies the starting index position for the search. Can be any valid expression that resolves to a non-negative integral number. - * @param mixed|Expr $end An integer, or a number that can be represented as integers (such as 2.0), that specifies the ending index position for the search. Can be any valid expression that resolves to a non-negative integral number. + * @param mixed|Expr $start Optional. An integer, or a number that can be represented as integers (such as 2.0), that specifies the starting index position for the search. Can be any valid expression that resolves to a non-negative integral number. + * @param mixed|Expr $end An integer, or a number that can be represented as integers (such as 2.0), that specifies the ending index position for the search. Can be any valid expression that resolves to a non-negative integral number. * @return $this */ public function indexOfArray($arrayExpression, $searchExpression, $start = null, $end = null) @@ -577,11 +569,10 @@ public function indexOfArray($arrayExpression, $searchExpression, $start = null, * found, returns -1. * * @see https://docs.mongodb.com/manual/reference/operator/aggregation/indexOfBytes/ - * @since 1.5 - * @param mixed|Expr $stringExpression Can be any valid expression as long as it resolves to a string. + * @param mixed|Expr $stringExpression Can be any valid expression as long as it resolves to a string. * @param mixed|Expr $substringExpression Can be any valid expression as long as it resolves to a string. - * @param int|null $start An integral number that specifies the starting index position for the search. Can be any valid expression that resolves to a non-negative integral number. - * @param int|null $end An integral number that specifies the ending index position for the search. Can be any valid expression that resolves to a non-negative integral number. + * @param int|null $start An integral number that specifies the starting index position for the search. Can be any valid expression that resolves to a non-negative integral number. + * @param int|null $end An integral number that specifies the ending index position for the search. Can be any valid expression that resolves to a non-negative integral number. * * @return $this */ @@ -598,11 +589,10 @@ public function indexOfBytes($stringExpression, $substringExpression, $start = n * not found, returns -1. * * @see https://docs.mongodb.com/manual/reference/operator/aggregation/indexOfCP/ - * @since 1.5 - * @param mixed|Expr $stringExpression Can be any valid expression as long as it resolves to a string. + * @param mixed|Expr $stringExpression Can be any valid expression as long as it resolves to a string. * @param mixed|Expr $substringExpression Can be any valid expression as long as it resolves to a string. - * @param int|null $start An integral number that specifies the starting index position for the search. Can be any valid expression that resolves to a non-negative integral number. - * @param int|null $end An integral number that specifies the ending index position for the search. Can be any valid expression that resolves to a non-negative integral number. + * @param int|null $start An integral number that specifies the starting index position for the search. Can be any valid expression that resolves to a non-negative integral number. + * @param int|null $end An integral number that specifies the ending index position for the search. Can be any valid expression that resolves to a non-negative integral number. * * @return $this */ @@ -644,7 +634,6 @@ public function ifNull($expression, $replacementExpression) * @param mixed|Expr $expression * @return $this * - * @since 1.3 */ public function isArray($expression) { @@ -660,7 +649,6 @@ public function isArray($expression) * The argument can be any expression as long as it resolves to a date. * * @see http://docs.mongodb.org/manual/reference/operator/aggregation/isoDayOfWeek/ - * @since 1.5 * @param mixed|Expr $expression * @return $this */ @@ -680,7 +668,6 @@ public function isoDayOfWeek($expression) * The argument can be any expression as long as it resolves to a date. * * @see http://docs.mongodb.org/manual/reference/operator/aggregation/isoWeek/ - * @since 1.5 * @param mixed|Expr $expression * @return $this */ @@ -700,7 +687,6 @@ public function isoWeek($expression) * The argument can be any expression as long as it resolves to a date. * * @see http://docs.mongodb.org/manual/reference/operator/aggregation/isoWeek/ - * @since 1.5 * @param mixed|Expr $expression * @return $this */ @@ -756,7 +742,6 @@ public function literal($value) * @param mixed|Expr $number * @return $this * - * @since 1.3 */ public function ln($number) { @@ -780,7 +765,6 @@ public function ln($number) * @param mixed|Expr $base * @return $this * - * @since 1.3 */ public function log($number, $base) { @@ -802,7 +786,6 @@ public function log($number, $base) * @param mixed|Expr $number * @return $this * - * @since 1.3 */ public function log10($number) { @@ -854,7 +837,7 @@ public function lte($expression1, $expression2) * @see http://docs.mongodb.org/manual/reference/operator/aggregation/map/ * @see Expr::map * @param mixed|Expr $input An expression that resolves to an array. - * @param string $as The variable name for the items in the input array. The in expression accesses each item in the input array by this variable. + * @param string $as The variable name for the items in the input array. The in expression accesses each item in the input array by this variable. * @param mixed|Expr $in The expression to apply to each item in the input array. The expression accesses the item by its variable name. * @return $this */ @@ -1016,7 +999,6 @@ public function not($expression) * @param mixed|Expr $exponent * @return $this * - * @since 1.3 */ public function pow($number, $exponent) { @@ -1032,10 +1014,9 @@ public function pow($number, $exponent) * * @see https://docs.mongodb.com/manual/reference/operator/aggregation/range/ * @see Expr::range - * @since 1.5 * @param mixed|Expr $start An integer that specifies the start of the sequence. Can be any valid expression that resolves to an integer. - * @param mixed|Expr $end An integer that specifies the exclusive upper limit of the sequence. Can be any valid expression that resolves to an integer. - * @param mixed|Expr $step Optional. An integer that specifies the increment value. Can be any valid expression that resolves to a non-zero integer. Defaults to 1. + * @param mixed|Expr $end An integer that specifies the exclusive upper limit of the sequence. Can be any valid expression that resolves to an integer. + * @param mixed|Expr $step Optional. An integer that specifies the increment value. Can be any valid expression that resolves to a non-zero integer. Defaults to 1. * @return $this */ public function range($start, $end, $step = 1) @@ -1051,10 +1032,9 @@ public function range($start, $end, $step = 1) * * @see https://docs.mongodb.com/manual/reference/operator/aggregation/reduce/ * @see Expr::reduce - * @since 1.5 - * @param mixed|Expr $input Can be any valid expression that resolves to an array. + * @param mixed|Expr $input Can be any valid expression that resolves to an array. * @param mixed|Expr $initialValue The initial cumulative value set before in is applied to the first element of the input array. - * @param mixed|Expr $in A valid expression that $reduce applies to each element in the input array in left-to-right order. Wrap the input value with $reverseArray to yield the equivalent of applying the combining expression from right-to-left. + * @param mixed|Expr $in A valid expression that $reduce applies to each element in the input array in left-to-right order. Wrap the input value with $reverseArray to yield the equivalent of applying the combining expression from right-to-left. * @return $this */ public function reduce($input, $initialValue, $in) @@ -1070,7 +1050,6 @@ public function reduce($input, $initialValue, $in) * * @see https://docs.mongodb.com/manual/reference/operator/aggregation/reverseArray/ * @see Expr::reverseArray - * @since 1.5 * @param mixed|Expr $expression * @return $this */ @@ -1220,12 +1199,11 @@ public function size($expression) * * @see https://docs.mongodb.org/manual/reference/operator/aggregation/slice/ * @see Expr::slice - * @param mixed|Expr $array - * @param mixed|Expr $n + * @param mixed|Expr $array + * @param mixed|Expr $n * @param mixed|Expr|null $position * @return $this * - * @since 1.3 */ public function slice($array, $n, $position = null) { @@ -1242,8 +1220,7 @@ public function slice($array, $n, $position = null) * returns the original string as the only element of an array. * * @see https://docs.mongodb.com/manual/reference/operator/aggregation/split/ - * @since 1.5 - * @param mixed|Expr $string The string to be split. Can be any valid expression as long as it resolves to a string. + * @param mixed|Expr $string The string to be split. Can be any valid expression as long as it resolves to a string. * @param mixed|Expr $delimiter The delimiter to use when splitting the string expression. Can be any valid expression as long as it resolves to a string. * * @return $this @@ -1299,7 +1276,6 @@ public function strcasecmp($expression1, $expression2) * Returns the number of UTF-8 encoded bytes in the specified string. * * @see https://docs.mongodb.com/manual/reference/operator/aggregation/strLenBytes/ - * @since 1.5 * @param mixed|Expr $string * * @return $this @@ -1315,7 +1291,6 @@ public function strLenBytes($string) * Returns the number of UTF-8 code points in the specified string. * * @see https://docs.mongodb.com/manual/reference/operator/aggregation/strLenCP/ - * @since 1.5 * @param mixed|Expr $string * * @return $this @@ -1355,10 +1330,9 @@ public function substr($string, $start, $length) * specified. * * @see https://docs.mongodb.com/manual/reference/operator/aggregation/substrBytes/ - * @since 1.5 * @param mixed|Expr $string The string from which the substring will be extracted. Can be any valid expression as long as it resolves to a string. - * @param mixed|Expr $start Indicates the starting point of the substring. Can be any valid expression as long as it resolves to a non-negative integer or number that can be represented as an integer. - * @param mixed|Expr $count Can be any valid expression as long as it resolves to a non-negative integer or number that can be represented as an integer. + * @param mixed|Expr $start Indicates the starting point of the substring. Can be any valid expression as long as it resolves to a non-negative integer or number that can be represented as an integer. + * @param mixed|Expr $count Can be any valid expression as long as it resolves to a non-negative integer or number that can be represented as an integer. * * @return $this */ @@ -1377,10 +1351,9 @@ public function substrBytes($string, $start, $count) * specified. * * @see https://docs.mongodb.com/manual/reference/operator/aggregation/substrBytes/ - * @since 1.5 * @param mixed|Expr $string The string from which the substring will be extracted. Can be any valid expression as long as it resolves to a string. - * @param mixed|Expr $start Indicates the starting point of the substring. Can be any valid expression as long as it resolves to a non-negative integer or number that can be represented as an integer. - * @param mixed|Expr $count Can be any valid expression as long as it resolves to a non-negative integer or number that can be represented as an integer. + * @param mixed|Expr $start Indicates the starting point of the substring. Can be any valid expression as long as it resolves to a non-negative integer or number that can be represented as an integer. + * @param mixed|Expr $count Can be any valid expression as long as it resolves to a non-negative integer or number that can be represented as an integer. * * @return $this */ @@ -1455,7 +1428,6 @@ public function toUpper($expression) * @param mixed|Expr $number * @return $this * - * @since 1.3 */ public function trunc($number) { @@ -1470,7 +1442,6 @@ public function trunc($number) * The argument can be any valid expression. * * @see http://docs.mongodb.org/manual/reference/operator/aggregation/type/ - * @since 1.5 * @param mixed|Expr $expression * * @return $this @@ -1523,10 +1494,9 @@ public function year($expression) * * @see https://docs.mongodb.com/manual/reference/operator/aggregation/zip/ * @see Expr::zip - * @since 1.5 - * @param mixed|Expr $inputs An array of expressions that resolve to arrays. The elements of these input arrays combine to form the arrays of the output array. - * @param bool|null $useLongestLength A boolean which specifies whether the length of the longest array determines the number of arrays in the output array. - * @param mixed|Expr|null $defaults An array of default element values to use if the input arrays have different lengths. You must specify useLongestLength: true along with this field, or else $zip will return an error. + * @param mixed|Expr $inputs An array of expressions that resolve to arrays. The elements of these input arrays combine to form the arrays of the output array. + * @param bool|null $useLongestLength A boolean which specifies whether the length of the longest array determines the number of arrays in the output array. + * @param mixed|Expr|null $defaults An array of default element values to use if the input arrays have different lengths. You must specify useLongestLength: true along with this field, or else $zip will return an error. * @return $this */ public function zip($inputs, $useLongestLength = null, $defaults = null) diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Out.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Out.php index e89771be48..a174669225 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Out.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Out.php @@ -1,5 +1,7 @@ $this->collection + '$out' => $this->collection, ]; } diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Project.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Project.php index 5e040daa58..630cca3359 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Project.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Project.php @@ -1,14 +1,15 @@ - * @since 1.2 */ class Project extends Operator { @@ -18,7 +19,7 @@ class Project extends Operator public function getExpression() { return [ - '$project' => $this->expr->getExpression() + '$project' => $this->expr->getExpression(), ]; } @@ -33,7 +34,6 @@ public function getExpression() * @param mixed|Expr ...$expressions Additional expressions * @return $this * - * @since 1.3 */ public function avg($expression1, ...$expressions) { @@ -63,7 +63,6 @@ public function includeFields(array $fields) * If you specify the exclusion of a field other than _id, you cannot employ * any other $project specification forms. * - * @since 1.5 * @param array $fields * @return $this */ @@ -86,7 +85,6 @@ public function excludeFields(array $fields) * @param mixed|Expr ...$expressions Additional expressions * @return $this * - * @since 1.3 */ public function max($expression1, ...$expressions) { @@ -105,7 +103,6 @@ public function max($expression1, ...$expressions) * @param mixed|Expr ...$expressions Additional expressions * @return $this * - * @since 1.3 */ public function min($expression1, ...$expressions) { @@ -125,7 +122,6 @@ public function min($expression1, ...$expressions) * @param mixed|Expr ...$expressions Additional expressions * @return $this * - * @since 1.3 */ public function stdDevPop($expression1, ...$expressions) { @@ -145,7 +141,6 @@ public function stdDevPop($expression1, ...$expressions) * @param mixed|Expr ...$expressions Additional expressions * @return $this * - * @since 1.3 */ public function stdDevSamp($expression1, ...$expressions) { @@ -165,7 +160,6 @@ public function stdDevSamp($expression1, ...$expressions) * @param mixed|Expr ...$expressions Additional expressions * @return $this * - * @since 1.3 */ public function sum($expression1, ...$expressions) { diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Redact.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Redact.php index 9c0cf95161..f88a71cf56 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Redact.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Redact.php @@ -1,12 +1,12 @@ - * @since 1.2 */ class Redact extends Operator { @@ -16,7 +16,7 @@ class Redact extends Operator public function getExpression() { return [ - '$redact' => $this->expr->getExpression() + '$redact' => $this->expr->getExpression(), ]; } } diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/ReplaceRoot.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/ReplaceRoot.php index f6e39f6ea4..40736ea4d7 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/ReplaceRoot.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/ReplaceRoot.php @@ -1,12 +1,19 @@ $this->expression !== null ? $this->convertExpression($this->expression) : $this->expr->getExpression() + '$replaceRoot' => $this->expression !== null ? $this->convertExpression($this->expression) : $this->expr->getExpression(), ]; } @@ -56,7 +63,7 @@ private function convertExpression($expression) } /** - * @return \Doctrine\ODM\MongoDB\Persisters\DocumentPersister + * @return DocumentPersister */ private function getDocumentPersister() { diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Sample.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Sample.php index dd0f16a3eb..e2c401be98 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Sample.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Sample.php @@ -1,5 +1,7 @@ - * @since 1.3 */ class Sample extends Stage { /** - * @var integer + * @var int */ private $size; /** - * @param Builder $builder - * @param integer $size + * @param int $size */ public function __construct(Builder $builder, $size) { parent::__construct($builder); - $this->size = (integer) $size; + $this->size = (int) $size; } /** @@ -35,7 +34,7 @@ public function __construct(Builder $builder, $size) public function getExpression() { return [ - '$sample' => ['size' => $this->size] + '$sample' => ['size' => $this->size], ]; } } diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Skip.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Skip.php index 5105798721..9379d32c81 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Skip.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Skip.php @@ -1,5 +1,7 @@ - * @since 1.2 */ class Skip extends Stage { /** - * @var integer + * @var int */ private $skip; /** - * @param Builder $builder - * @param integer $skip + * @param int $skip */ public function __construct(Builder $builder, $skip) { parent::__construct($builder); - $this->skip = (integer) $skip; + $this->skip = (int) $skip; } /** @@ -35,7 +34,7 @@ public function __construct(Builder $builder, $skip) public function getExpression() { return [ - '$skip' => $this->skip + '$skip' => $this->skip, ]; } } diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Sort.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Sort.php index e3550578e2..1f627263e4 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Sort.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Sort.php @@ -1,15 +1,19 @@ - * @since 1.2 */ class Sort extends Stage { @@ -19,9 +23,8 @@ class Sort extends Stage private $sort = []; /** - * @param Builder $builder * @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 $order Field order (if one field is specified) */ public function __construct(Builder $builder, $fieldName, $order = null) { @@ -50,7 +53,7 @@ public function __construct(Builder $builder, $fieldName, $order = null) public function getExpression() { return [ - '$sort' => $this->sort + '$sort' => $this->sort, ]; } } diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/SortByCount.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/SortByCount.php index a702010c70..2ee1c1890d 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/SortByCount.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/SortByCount.php @@ -1,11 +1,14 @@ $this->fieldName + '$sortByCount' => $this->fieldName, ]; } } diff --git a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Unwind.php b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Unwind.php index 91a35e95a7..4de31e6aef 100644 --- a/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Unwind.php +++ b/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Unwind.php @@ -1,5 +1,7 @@ - * @since 1.2 */ class Unwind extends Stage { @@ -29,7 +29,6 @@ class Unwind extends Stage private $preserveNullAndEmptyArrays = false; /** - * @param Builder $builder * @param string $fieldName */ public function __construct(Builder $builder, $fieldName) @@ -47,23 +46,21 @@ public function getExpression() // Fallback behavior for MongoDB < 3.2 if ($this->includeArrayIndex === null && ! $this->preserveNullAndEmptyArrays) { return [ - '$unwind' => $this->fieldName + '$unwind' => $this->fieldName, ]; } $unwind = ['path' => $this->fieldName]; foreach (['includeArrayIndex', 'preserveNullAndEmptyArrays'] as $option) { - if ( ! $this->$option) { + if (! $this->$option) { continue; } $unwind[$option] = $this->$option; } - return [ - '$unwind' => $unwind - ]; + return ['$unwind' => $unwind]; } /** @@ -73,7 +70,6 @@ public function getExpression() * @param string $includeArrayIndex * @return $this * - * @since 1.3 */ public function includeArrayIndex($includeArrayIndex) { @@ -89,7 +85,6 @@ public function includeArrayIndex($includeArrayIndex) * @param bool $preserveNullAndEmptyArrays * @return $this * - * @since 1.3 */ public function preserveNullAndEmptyArrays($preserveNullAndEmptyArrays = true) { diff --git a/lib/Doctrine/ODM/MongoDB/Configuration.php b/lib/Doctrine/ODM/MongoDB/Configuration.php index a6d08087f5..aabedda3ca 100644 --- a/lib/Doctrine/ODM/MongoDB/Configuration.php +++ b/lib/Doctrine/ODM/MongoDB/Configuration.php @@ -1,5 +1,7 @@ attributes['documentNamespaces'][$documentNamespaceAlias])) { + if (! isset($this->attributes['documentNamespaces'][$documentNamespaceAlias])) { throw MongoDBException::unknownDocumentNamespace($documentNamespaceAlias); } @@ -116,7 +118,6 @@ public function getDocumentNamespaces() * Set the document alias map * * @param array $documentNamespaces - * @return void */ public function setDocumentNamespaces(array $documentNamespaces) { @@ -126,7 +127,6 @@ public function setDocumentNamespaces(array $documentNamespaces) /** * Sets the cache driver implementation that is used for metadata caching. * - * @param MappingDriver $driverImpl * @todo Force parameter to be a Closure to ensure lazy evaluation * (as soon as a metadata cache is in effect, the driver never needs to initialize). */ @@ -141,11 +141,11 @@ public function setMetadataDriverImpl(MappingDriver $driverImpl) * @param array $paths * @return Mapping\Driver\AnnotationDriver */ - public function newDefaultAnnotationDriver($paths = array()) + public function newDefaultAnnotationDriver($paths = []) { $reader = new AnnotationReader(); - return new AnnotationDriver($reader, (array)$paths); + return new AnnotationDriver($reader, (array) $paths); } /** @@ -161,7 +161,7 @@ public function getMetadataDriverImpl() /** * Gets the cache driver implementation that is used for metadata caching. * - * @return \Doctrine\Common\Cache\Cache + * @return Cache */ public function getMetadataCacheImpl() { @@ -171,7 +171,6 @@ public function getMetadataCacheImpl() /** * Sets the cache driver implementation that is used for metadata caching. * - * @param \Doctrine\Common\Cache\Cache $cacheImpl */ public function setMetadataCacheImpl(Cache $cacheImpl) { @@ -202,7 +201,7 @@ public function getProxyDir() * Gets a boolean flag that indicates whether proxy classes should always be regenerated * during each script execution. * - * @return boolean|integer + * @return bool|int */ public function getAutoGenerateProxyClasses() { @@ -213,7 +212,7 @@ public function getAutoGenerateProxyClasses() * Sets a boolean flag that indicates whether proxy classes should always be regenerated * during each script execution. * - * @param boolean|int $bool Possible values are constants of Doctrine\Common\Proxy\AbstractProxyFactory + * @param bool|int $bool Possible values are constants of Doctrine\Common\Proxy\AbstractProxyFactory */ public function setAutoGenerateProxyClasses($bool) { @@ -264,7 +263,7 @@ public function getHydratorDir() * Gets a boolean flag that indicates whether hydrator classes should always be regenerated * during each script execution. * - * @return boolean|integer Possible values are defined constants + * @return bool|int Possible values are defined constants */ public function getAutoGenerateHydratorClasses() { @@ -275,7 +274,7 @@ public function getAutoGenerateHydratorClasses() * Sets a boolean flag that indicates whether hydrator classes should always be regenerated * during each script execution. * - * @param boolean|integer $bool + * @param bool|int $bool */ public function setAutoGenerateHydratorClasses($bool) { @@ -326,7 +325,7 @@ public function getPersistentCollectionDir() * Gets a integer flag that indicates how and when persistent collection * classes should be generated. * - * @return integer Possible values are defined constants + * @return int Possible values are defined constants */ public function getAutoGeneratePersistentCollectionClasses() { @@ -337,7 +336,7 @@ public function getAutoGeneratePersistentCollectionClasses() * Sets a integer flag that indicates how and when persistent collection * classes should be generated. * - * @param integer $mode Possible values are defined constants + * @param int $mode Possible values are defined constants */ public function setAutoGeneratePersistentCollectionClasses($mode) { @@ -402,7 +401,7 @@ public function setClassMetadataFactoryName($cmfName) */ public function getClassMetadataFactoryName() { - if ( ! isset($this->attributes['classMetadataFactoryName'])) { + if (! isset($this->attributes['classMetadataFactoryName'])) { $this->attributes['classMetadataFactoryName'] = ClassMetadataFactory::class; } return $this->attributes['classMetadataFactoryName']; @@ -415,7 +414,7 @@ public function getClassMetadataFactoryName() */ public function getDefaultCommitOptions() { - return $this->attributes['defaultCommitOptions'] ?? array('w' => 1); + return $this->attributes['defaultCommitOptions'] ?? ['w' => 1]; } /** @@ -435,12 +434,12 @@ public function setDefaultCommitOptions($defaultCommitOptions) * @param string $className The class name of the filter. * @param array $parameters The parameters for the filter. */ - public function addFilter($name, $className, array $parameters = array()) + public function addFilter($name, $className, array $parameters = []) { - $this->attributes['filters'][$name] = array( + $this->attributes['filters'][$name] = [ 'class' => $className, - 'parameters' => $parameters - ); + 'parameters' => $parameters, + ]; } /** @@ -476,7 +475,6 @@ public function getFilterParameters($name) * * @param string $className * - * @return void * * @throws MongoDBException If not is a ObjectRepository */ @@ -484,7 +482,7 @@ public function setDefaultRepositoryClassName($className) { $reflectionClass = new \ReflectionClass($className); - if ( ! $reflectionClass->implementsInterface(ObjectRepository::class)) { + if (! $reflectionClass->implementsInterface(ObjectRepository::class)) { throw MongoDBException::invalidDocumentRepository($className); } @@ -504,7 +502,6 @@ public function getDefaultRepositoryClassName() /** * Set the document repository factory. * - * @param RepositoryFactory $repositoryFactory */ public function setRepositoryFactory(RepositoryFactory $repositoryFactory) { @@ -524,7 +521,6 @@ public function getRepositoryFactory() /** * Set the persistent collection factory. * - * @param PersistentCollectionFactory $persistentCollectionFactory */ public function setPersistentCollectionFactory(PersistentCollectionFactory $persistentCollectionFactory) { @@ -538,7 +534,7 @@ public function setPersistentCollectionFactory(PersistentCollectionFactory $pers */ public function getPersistentCollectionFactory() { - if ( ! isset($this->attributes['persistentCollectionFactory'])) { + if (! isset($this->attributes['persistentCollectionFactory'])) { $this->attributes['persistentCollectionFactory'] = new DefaultPersistentCollectionFactory(); } return $this->attributes['persistentCollectionFactory']; @@ -547,7 +543,6 @@ public function getPersistentCollectionFactory() /** * Set the persistent collection generator. * - * @param PersistentCollectionGenerator $persistentCollectionGenerator */ public function setPersistentCollectionGenerator(PersistentCollectionGenerator $persistentCollectionGenerator) { @@ -561,7 +556,7 @@ public function setPersistentCollectionGenerator(PersistentCollectionGenerator $ */ public function getPersistentCollectionGenerator() { - if ( ! isset($this->attributes['persistentCollectionGenerator'])) { + if (! isset($this->attributes['persistentCollectionGenerator'])) { $this->attributes['persistentCollectionGenerator'] = new DefaultPersistentCollectionGenerator( $this->getPersistentCollectionDir(), $this->getPersistentCollectionNamespace() diff --git a/lib/Doctrine/ODM/MongoDB/DocumentManager.php b/lib/Doctrine/ODM/MongoDB/DocumentManager.php index 58e2f6df34..aeb19137ba 100644 --- a/lib/Doctrine/ODM/MongoDB/DocumentManager.php +++ b/lib/Doctrine/ODM/MongoDB/DocumentManager.php @@ -1,13 +1,16 @@ config = $config ?: new Configuration(); $this->eventManager = $eventManager ?: new EventManager(); @@ -155,7 +160,8 @@ protected function __construct(Client $client = null, Configuration $config = nu $this->unitOfWork = new UnitOfWork($this, $this->eventManager, $this->hydratorFactory); $this->hydratorFactory->setUnitOfWork($this->unitOfWork); $this->schemaManager = new SchemaManager($this, $this->metadataFactory); - $this->proxyFactory = new ProxyFactory($this, + $this->proxyFactory = new ProxyFactory( + $this, $this->config->getProxyDir(), $this->config->getProxyNamespace(), $this->config->getAutoGenerateProxyClasses() @@ -178,12 +184,9 @@ public function getProxyFactory() * and uses the given Configuration. * * @static - * @param Client|null $client - * @param Configuration|null $config - * @param \Doctrine\Common\EventManager|null $eventManager * @return DocumentManager */ - public static function create(Client $client = null, Configuration $config = null, EventManager $eventManager = null) + public static function create(?Client $client = null, ?Configuration $config = null, ?EventManager $eventManager = null) { return new static($client, $config, $eventManager); } @@ -191,7 +194,7 @@ public static function create(Client $client = null, Configuration $config = nul /** * Gets the EventManager used by the DocumentManager. * - * @return \Doctrine\Common\EventManager + * @return EventManager */ public function getEventManager() { @@ -211,7 +214,7 @@ public function getClient() /** * Gets the metadata factory used to gather the metadata of classes. * - * @return \Doctrine\ODM\MongoDB\Mapping\ClassMetadataFactory + * @return ClassMetadataFactory */ public function getMetadataFactory() { @@ -254,7 +257,7 @@ public function getHydratorFactory() /** * Returns SchemaManager, used to create/drop indexes/collections/databases. * - * @return \Doctrine\ODM\MongoDB\SchemaManager + * @return SchemaManager */ public function getSchemaManager() { @@ -265,7 +268,7 @@ public function getSchemaManager() * Returns the metadata for a class. * * @param string $className The class name. - * @return \Doctrine\ODM\MongoDB\Mapping\ClassMetadata + * @return ClassMetadata * @internal Performance-sensitive method. */ public function getClassMetadata($className) @@ -320,11 +323,11 @@ public function getDocumentCollection($className) $metadata = $this->metadataFactory->getMetadataFor($className); $collectionName = $metadata->getCollection(); - if ( ! $collectionName) { + if (! $collectionName) { throw MongoDBException::documentNotMappedToCollection($className); } - if ( ! isset($this->documentCollections[$className])) { + if (! isset($this->documentCollections[$className])) { $db = $this->getDocumentDatabase($className); $options = []; @@ -384,7 +387,7 @@ public function createAggregationBuilder($documentName) */ public function persist($document) { - if ( ! is_object($document)) { + if (! is_object($document)) { throw new \InvalidArgumentException(gettype($document)); } $this->errorIfClosed(); @@ -402,7 +405,7 @@ public function persist($document) */ public function remove($document) { - if ( ! is_object($document)) { + if (! is_object($document)) { throw new \InvalidArgumentException(gettype($document)); } $this->errorIfClosed(); @@ -418,7 +421,7 @@ public function remove($document) */ public function refresh($document) { - if ( ! is_object($document)) { + if (! is_object($document)) { throw new \InvalidArgumentException(gettype($document)); } $this->errorIfClosed(); @@ -437,7 +440,7 @@ public function refresh($document) */ public function detach($document) { - if ( ! is_object($document)) { + if (! is_object($document)) { throw new \InvalidArgumentException(gettype($document)); } $this->unitOfWork->detach($document); @@ -455,7 +458,7 @@ public function detach($document) */ public function merge($document) { - if ( ! is_object($document)) { + if (! is_object($document)) { throw new \InvalidArgumentException(gettype($document)); } $this->errorIfClosed(); @@ -466,13 +469,13 @@ public function merge($document) * Acquire a lock on the given document. * * @param object $document - * @param int $lockMode - * @param int $lockVersion + * @param int $lockMode + * @param int $lockVersion * @throws \InvalidArgumentException */ public function lock($document, $lockMode, $lockVersion = null) { - if ( ! is_object($document)) { + if (! is_object($document)) { throw new \InvalidArgumentException(gettype($document)); } $this->unitOfWork->lock($document, $lockMode, $lockVersion); @@ -486,7 +489,7 @@ public function lock($document, $lockMode, $lockVersion = null) */ public function unlock($document) { - if ( ! is_object($document)) { + if (! is_object($document)) { throw new \InvalidArgumentException(gettype($document)); } $this->unitOfWork->unlock($document); @@ -495,7 +498,7 @@ public function unlock($document) /** * Gets the repository for a document class. * - * @param string $documentName The name of the Document. + * @param string $documentName The name of the Document. * @return ObjectRepository The repository. */ public function getRepository($documentName) @@ -511,7 +514,7 @@ public function getRepository($documentName) * @param array $options Array of options to be used with batchInsert(), update() and remove() * @throws \InvalidArgumentException */ - public function flush(array $options = array()) + public function flush(array $options = []) { $this->errorIfClosed(); $this->unitOfWork->commit($options); @@ -525,7 +528,7 @@ public function flush(array $options = array()) * has its identifier populated. Otherwise a proxy is returned that automatically * loads itself on first access. * - * @param string $documentName + * @param string $documentName * @param string|object $identifier * @return mixed|object The document reference. */ @@ -539,8 +542,8 @@ public function getReference($documentName, $identifier) return $document; } - $document = $this->proxyFactory->getProxy($class->name, array($class->identifier => $identifier)); - $this->unitOfWork->registerManaged($document, $identifier, array()); + $document = $this->proxyFactory->getProxy($class->name, [$class->identifier => $identifier]); + $this->unitOfWork->registerManaged($document, $identifier, []); return $document; } @@ -561,7 +564,7 @@ public function getReference($documentName, $identifier) * never be loaded in the first place. * * @param string $documentName The name of the document type. - * @param mixed $identifier The document identifier. + * @param mixed $identifier The document identifier. * @return object The (partial) document reference. */ public function getPartialReference($documentName, $identifier) @@ -574,7 +577,7 @@ public function getPartialReference($documentName, $identifier) } $document = $class->newInstance(); $class->setIdentifierValue($document, $identifier); - $this->unitOfWork->registerManaged($document, $identifier, array()); + $this->unitOfWork->registerManaged($document, $identifier, []); return $document; } @@ -585,9 +588,9 @@ public function getPartialReference($documentName, $identifier) * This is just a convenient shortcut for getRepository($documentName)->find($id). * * @param string $documentName - * @param mixed $identifier - * @param int $lockMode - * @param int $lockVersion + * @param mixed $identifier + * @param int $lockMode + * @param int $lockVersion * @return object $document */ public function find($documentName, $identifier, $lockMode = LockMode::NONE, $lockVersion = null) @@ -624,11 +627,11 @@ public function close() * * @param object $document * @throws \InvalidArgumentException When the $document param is not an object - * @return boolean TRUE if this DocumentManager currently manages the given document, FALSE otherwise. + * @return bool TRUE if this DocumentManager currently manages the given document, FALSE otherwise. */ public function contains($document) { - if ( ! is_object($document)) { + if (! is_object($document)) { throw new \InvalidArgumentException(gettype($document)); } return $this->unitOfWork->isScheduledForInsert($document) || @@ -649,8 +652,8 @@ public function getConfiguration() /** * Returns a reference to the supplied document. * - * @param object $document A document object - * @param array $referenceMapping Mapping for the field that references the document + * @param object $document A document object + * @param array $referenceMapping Mapping for the field that references the document * * @throws \InvalidArgumentException * @throws MappingException @@ -658,7 +661,7 @@ public function getConfiguration() */ public function createReference($document, array $referenceMapping) { - if ( ! is_object($document)) { + if (! is_object($document)) { throw new \InvalidArgumentException('Cannot create a DBRef, the document is not an object'); } @@ -682,7 +685,6 @@ public function createReference($document, array $referenceMapping) return $class->getDatabaseIdentifierValue($id); break; - case ClassMetadata::REFERENCE_STORE_AS_REF: $reference = ['id' => $class->getDatabaseIdentifierValue($id)]; break; @@ -758,17 +760,17 @@ private function errorIfClosed() */ public function isOpen() { - return ( ! $this->closed); + return ! $this->closed; } /** * Gets the filter collection. * - * @return \Doctrine\ODM\MongoDB\Query\FilterCollection The active filter collection. + * @return FilterCollection The active filter collection. */ public function getFilterCollection() { - if (null === $this->filterCollection) { + if ($this->filterCollection === null) { $this->filterCollection = new FilterCollection($this); } diff --git a/lib/Doctrine/ODM/MongoDB/DocumentNotFoundException.php b/lib/Doctrine/ODM/MongoDB/DocumentNotFoundException.php index a0fc887868..92cd81bd9e 100644 --- a/lib/Doctrine/ODM/MongoDB/DocumentNotFoundException.php +++ b/lib/Doctrine/ODM/MongoDB/DocumentNotFoundException.php @@ -1,12 +1,16 @@ $id); + $criteria = ['_id' => $id]; if ($lockMode === LockMode::NONE) { return $this->getDocumentPersister()->load($criteria); } if ($lockMode === LockMode::OPTIMISTIC) { - if (!$this->class->isVersioned) { + if (! $this->class->isVersioned) { throw LockException::notVersioned($this->documentName); } if ($document = $this->getDocumentPersister()->load($criteria)) { @@ -140,7 +141,7 @@ public function find($id, $lockMode = LockMode::NONE, $lockVersion = null) return $document; } - return $this->getDocumentPersister()->load($criteria, null, array(), $lockMode); + return $this->getDocumentPersister()->load($criteria, null, [], $lockMode); } /** @@ -150,20 +151,20 @@ public function find($id, $lockMode = LockMode::NONE, $lockVersion = null) */ public function findAll() { - return $this->findBy(array()); + return $this->findBy([]); } /** * Finds documents by a set of criteria. * - * @param array $criteria Query criteria - * @param array $sort Sort array for Cursor::sort() - * @param integer|null $limit Limit for Cursor::limit() - * @param integer|null $skip Skip for Cursor::skip() + * @param array $criteria Query criteria + * @param array $sort Sort array for Cursor::sort() + * @param int|null $limit Limit for Cursor::limit() + * @param int|null $skip Skip for Cursor::skip() * * @return array */ - public function findBy(array $criteria, array $sort = null, $limit = null, $skip = null) + public function findBy(array $criteria, ?array $sort = null, $limit = null, $skip = null) { return $this->getDocumentPersister()->loadAll($criteria, $sort, $limit, $skip)->toArray(false); } @@ -216,7 +217,6 @@ public function getClassName() * returns a new collection containing these elements. * * @see Selectable::matching() - * @param Criteria $criteria * @return Collection */ public function matching(Criteria $criteria) diff --git a/lib/Doctrine/ODM/MongoDB/Event/DocumentNotFoundEventArgs.php b/lib/Doctrine/ODM/MongoDB/Event/DocumentNotFoundEventArgs.php index db12ccecd6..5a9c7a4e25 100644 --- a/lib/Doctrine/ODM/MongoDB/Event/DocumentNotFoundEventArgs.php +++ b/lib/Doctrine/ODM/MongoDB/Event/DocumentNotFoundEventArgs.php @@ -1,4 +1,7 @@ documentChangeSet[$field])) { + if (! isset($this->documentChangeSet[$field])) { throw new \InvalidArgumentException(sprintf( 'Field "%s" is not a valid field of the document "%s" in PreUpdateEventArgs.', $field, diff --git a/lib/Doctrine/ODM/MongoDB/Events.php b/lib/Doctrine/ODM/MongoDB/Events.php index 4351734692..12bd41dd14 100644 --- a/lib/Doctrine/ODM/MongoDB/Events.php +++ b/lib/Doctrine/ODM/MongoDB/Events.php @@ -1,5 +1,7 @@ dm = $dm; @@ -96,7 +112,6 @@ public function __construct(DocumentManager $dm, EventManager $evm, $hydratorDir /** * Sets the UnitOfWork instance. * - * @param UnitOfWork $uow */ public function setUnitOfWork(UnitOfWork $uow) { @@ -107,7 +122,7 @@ public function setUnitOfWork(UnitOfWork $uow) * Gets the hydrator object for the given document class. * * @param string $className - * @return \Doctrine\ODM\MongoDB\Hydrator\HydratorInterface $hydrator + * @return HydratorInterface $hydrator */ public function getHydratorFor($className) { @@ -118,7 +133,7 @@ public function getHydratorFor($className) $fqn = $this->hydratorNamespace . '\\' . $hydratorClassName; $class = $this->dm->getClassMetadata($className); - if ( ! class_exists($fqn, false)) { + if (! class_exists($fqn, false)) { $fileName = $this->hydratorDir . DIRECTORY_SEPARATOR . $hydratorClassName . '.php'; switch ($this->autoGenerate) { case Configuration::AUTOGENERATE_NEVER: @@ -131,7 +146,7 @@ public function getHydratorFor($className) break; case Configuration::AUTOGENERATE_FILE_NOT_EXISTS: - if (!file_exists($fileName)) { + if (! file_exists($fileName)) { $this->generateHydratorClass($class, $hydratorClassName, $fileName); } require $fileName; @@ -149,10 +164,10 @@ public function getHydratorFor($className) /** * Generates hydrator classes for all given classes. * - * @param array $classes The classes (ClassMetadata instances) for which to generate hydrators. - * @param string $toDir The target directory of the hydrator classes. If not specified, the - * directory configured on the Configuration of the DocumentManager used - * by this factory is used. + * @param array $classes The classes (ClassMetadata instances) for which to generate hydrators. + * @param string $toDir The target directory of the hydrator classes. If not specified, the + * directory configured on the Configuration of the DocumentManager used + * by this factory is used. */ public function generateHydratorClasses(array $classes, $toDir = null) { @@ -166,7 +181,6 @@ public function generateHydratorClasses(array $classes, $toDir = null) } /** - * @param ClassMetadata $class * @param string $hydratorClassName * @param string $fileName */ @@ -177,7 +191,8 @@ private function generateHydratorClass(ClassMetadata $class, $hydratorClassName, foreach ($class->fieldMappings as $fieldName => $mapping) { if (isset($mapping['alsoLoadFields'])) { foreach ($mapping['alsoLoadFields'] as $name) { - $code .= sprintf(<<closureToPHP() ); - - - } elseif ( ! isset($mapping['association'])) { - $code .= sprintf(<<class->fieldMappings['%2\$s']['nullable']) && array_key_exists('%1\$s', \$data))) { @@ -233,7 +248,8 @@ private function generateHydratorClass(ClassMetadata $class, $hydratorClassName, Type::getType($mapping['type'])->closureToPHP() ); } elseif ($mapping['association'] === ClassMetadata::REFERENCE_ONE && $mapping['isOwningSide']) { - $code .= sprintf(<<class->fieldMappings['%2\$s']['targetDocument']; \$return = \$this->dm->getRepository(\$className)->%3\$s(\$document); @@ -268,7 +285,8 @@ private function generateHydratorClass(ClassMetadata $class, $hydratorClassName, $mapping['repositoryMethod'] ); } else { - $code .= sprintf(<<class->fieldMappings['%2\$s']; \$className = \$mapping['targetDocument']; @@ -291,7 +309,8 @@ private function generateHydratorClass(ClassMetadata $class, $hydratorClassName, ); } } elseif ($mapping['association'] === ClassMetadata::REFERENCE_MANY || $mapping['association'] === ClassMetadata::EMBED_MANY) { - $code .= sprintf(<<hydratorNamespace; - $code = sprintf(<<dm->getClassMetadata(get_class($document)); // Invoke preLoad lifecycle events and listeners - if ( ! empty($metadata->lifecycleCallbacks[Events::preLoad])) { - $args = array(new PreLoadEventArgs($document, $this->dm, $data)); + if (! empty($metadata->lifecycleCallbacks[Events::preLoad])) { + $args = [new PreLoadEventArgs($document, $this->dm, $data)]; $metadata->invokeLifecycleCallbacks(Events::preLoad, $document, $args); } if ($this->evm->hasListeners(Events::preLoad)) { @@ -423,7 +444,7 @@ public function hydrate($document, $data, array $hints = array()) } // alsoLoadMethods may transform the document before hydration - if ( ! empty($metadata->alsoLoadMethods)) { + if (! empty($metadata->alsoLoadMethods)) { foreach ($metadata->alsoLoadMethods as $method => $fieldNames) { foreach ($fieldNames as $fieldName) { // Invoke the method only once for the first field we find @@ -443,15 +464,15 @@ public function hydrate($document, $data, array $hints = array()) // lazy properties may be left uninitialized $properties = $document->__getLazyProperties(); foreach ($properties as $propertyName => $property) { - if ( ! isset($document->$propertyName)) { + if (! isset($document->$propertyName)) { $document->$propertyName = $properties[$propertyName]; } } } // Invoke the postLoad lifecycle callbacks and listeners - if ( ! empty($metadata->lifecycleCallbacks[Events::postLoad])) { - $metadata->invokeLifecycleCallbacks(Events::postLoad, $document, array(new LifecycleEventArgs($document, $this->dm))); + if (! empty($metadata->lifecycleCallbacks[Events::postLoad])) { + $metadata->invokeLifecycleCallbacks(Events::postLoad, $document, [new LifecycleEventArgs($document, $this->dm)]); } if ($this->evm->hasListeners(Events::postLoad)) { $this->evm->dispatchEvent(Events::postLoad, new LifecycleEventArgs($document, $this->dm)); diff --git a/lib/Doctrine/ODM/MongoDB/Hydrator/HydratorInterface.php b/lib/Doctrine/ODM/MongoDB/Hydrator/HydratorInterface.php index 4e7adcd3ba..cd02d25879 100644 --- a/lib/Doctrine/ODM/MongoDB/Hydrator/HydratorInterface.php +++ b/lib/Doctrine/ODM/MongoDB/Hydrator/HydratorInterface.php @@ -1,21 +1,22 @@ awkwardSafeMode ? $this->awkwardSafeChars : $this->chars; - $base = strlen($index); + $base = (string) strlen($index); $out = ''; do { $out = $index[bcmod($id, $base)] . $out; $id = bcdiv($id, $base); - } while (bccomp($id, 0) == 1); + } while (bccomp($id, '0') === 1); if (is_numeric($this->pad)) { $out = str_pad($out, $this->pad, '0', STR_PAD_LEFT); diff --git a/lib/Doctrine/ODM/MongoDB/Id/AutoGenerator.php b/lib/Doctrine/ODM/MongoDB/Id/AutoGenerator.php index 910cd97cb0..25242ee5d5 100644 --- a/lib/Doctrine/ODM/MongoDB/Id/AutoGenerator.php +++ b/lib/Doctrine/ODM/MongoDB/Id/AutoGenerator.php @@ -1,19 +1,21 @@ isValid($namespace)) { + if (! $this->isValid($namespace)) { throw new \Exception('Provided $namespace is invalid: ' . $namespace); } // Get hexadecimal components of namespace - $nhex = str_replace(array('-', '{', '}'), '', $namespace); + $nhex = str_replace(['-', '{', '}'], '', $namespace); // Binary Value $nstr = ''; diff --git a/lib/Doctrine/ODM/MongoDB/Iterator/CachingIterator.php b/lib/Doctrine/ODM/MongoDB/Iterator/CachingIterator.php index 0e65cff23a..11180c37f1 100644 --- a/lib/Doctrine/ODM/MongoDB/Iterator/CachingIterator.php +++ b/lib/Doctrine/ODM/MongoDB/Iterator/CachingIterator.php @@ -1,7 +1,14 @@ -iteratorExhausted) { + if (! $this->iteratorExhausted) { $this->iterator->next(); $this->storeCurrentItem(); } @@ -76,7 +81,6 @@ public function next() /** * @see http://php.net/iterator.rewind - * @return void */ public function rewind() { @@ -93,7 +97,7 @@ public function rewind() /** * * @see http://php.net/iterator.valid - * @return boolean + * @return bool */ public function valid() { @@ -105,7 +109,7 @@ public function valid() */ private function exhaustIterator() { - while ( ! $this->iteratorExhausted) { + while (! $this->iteratorExhausted) { $this->next(); } } diff --git a/lib/Doctrine/ODM/MongoDB/Iterator/HydratingIterator.php b/lib/Doctrine/ODM/MongoDB/Iterator/HydratingIterator.php index 7727d9da0f..674367b2c9 100644 --- a/lib/Doctrine/ODM/MongoDB/Iterator/HydratingIterator.php +++ b/lib/Doctrine/ODM/MongoDB/Iterator/HydratingIterator.php @@ -1,4 +1,6 @@ -ClassMetadata instance holds all the object-document mapping metadata @@ -24,7 +50,6 @@ * get the whole class name, namespace inclusive, prepended to every property in * the serialized representation). * - * @since 1.0 */ class ClassMetadata implements BaseClassMetadata { @@ -32,24 +57,24 @@ class ClassMetadata implements BaseClassMetadata /** * AUTO means Doctrine will automatically create a new \MongoDB\BSON\ObjectId instance for us. */ - const GENERATOR_TYPE_AUTO = 1; + public const GENERATOR_TYPE_AUTO = 1; /** * INCREMENT means a separate collection is used for maintaining and incrementing id generation. * Offers full portability. */ - const GENERATOR_TYPE_INCREMENT = 2; + public const GENERATOR_TYPE_INCREMENT = 2; /** * UUID means Doctrine will generate a uuid for us. */ - const GENERATOR_TYPE_UUID = 3; + public const GENERATOR_TYPE_UUID = 3; /** * ALNUM means Doctrine will generate Alpha-numeric string identifiers, using the INCREMENT * generator to ensure identifier uniqueness */ - const GENERATOR_TYPE_ALNUM = 4; + public const GENERATOR_TYPE_ALNUM = 4; /** * CUSTOM means Doctrine expect a class parameter. It will then try to initiate that class @@ -59,13 +84,13 @@ class ClassMetadata implements BaseClassMetadata * * The class will have to be a subtype of AbstractIdGenerator. */ - const GENERATOR_TYPE_CUSTOM = 5; + public const GENERATOR_TYPE_CUSTOM = 5; /** * NONE means Doctrine will not generate any id for us and you are responsible for manually * assigning an id. */ - const GENERATOR_TYPE_NONE = 6; + public const GENERATOR_TYPE_NONE = 6; /** * Default discriminator field name. @@ -73,41 +98,41 @@ class ClassMetadata implements BaseClassMetadata * This is used for associations value for associations where a that do not define a "targetDocument" or * "discriminatorField" option in their mapping. */ - const DEFAULT_DISCRIMINATOR_FIELD = '_doctrine_class_name'; + public const DEFAULT_DISCRIMINATOR_FIELD = '_doctrine_class_name'; - const REFERENCE_ONE = 1; - const REFERENCE_MANY = 2; - const EMBED_ONE = 3; - const EMBED_MANY = 4; - const MANY = 'many'; - const ONE = 'one'; + public const REFERENCE_ONE = 1; + public const REFERENCE_MANY = 2; + public const EMBED_ONE = 3; + public const EMBED_MANY = 4; + public const MANY = 'many'; + public const ONE = 'one'; /** * The types of storeAs references */ - const REFERENCE_STORE_AS_ID = 'id'; - const REFERENCE_STORE_AS_DB_REF = 'dbRef'; - const REFERENCE_STORE_AS_DB_REF_WITH_DB = 'dbRefWithDb'; - const REFERENCE_STORE_AS_REF = 'ref'; + public const REFERENCE_STORE_AS_ID = 'id'; + public const REFERENCE_STORE_AS_DB_REF = 'dbRef'; + public const REFERENCE_STORE_AS_DB_REF_WITH_DB = 'dbRefWithDb'; + public const REFERENCE_STORE_AS_REF = 'ref'; /* The inheritance mapping types */ /** * NONE means the class does not participate in an inheritance hierarchy * and therefore does not need an inheritance mapping type. */ - const INHERITANCE_TYPE_NONE = 1; + public const INHERITANCE_TYPE_NONE = 1; /** * SINGLE_COLLECTION means the class will be persisted according to the rules of * Single Collection Inheritance. */ - const INHERITANCE_TYPE_SINGLE_COLLECTION = 2; + public const INHERITANCE_TYPE_SINGLE_COLLECTION = 2; /** * COLLECTION_PER_CLASS means the class will be persisted according to the rules * of Concrete Collection Inheritance. */ - const INHERITANCE_TYPE_COLLECTION_PER_CLASS = 3; + public const INHERITANCE_TYPE_COLLECTION_PER_CLASS = 3; /** * DEFERRED_IMPLICIT means that changes of entities are calculated at commit-time @@ -116,38 +141,38 @@ class ClassMetadata implements BaseClassMetadata * * This is the default change tracking policy. */ - const CHANGETRACKING_DEFERRED_IMPLICIT = 1; + public const CHANGETRACKING_DEFERRED_IMPLICIT = 1; /** * DEFERRED_EXPLICIT means that changes of entities are calculated at commit-time * by doing a property-by-property comparison with the original data. This will * be done only for entities that were explicitly saved (through persist() or a cascade). */ - const CHANGETRACKING_DEFERRED_EXPLICIT = 2; + public const CHANGETRACKING_DEFERRED_EXPLICIT = 2; /** * NOTIFY means that Doctrine relies on the entities sending out notifications * when their properties change. Such entity classes must implement * the NotifyPropertyChanged interface. */ - const CHANGETRACKING_NOTIFY = 3; + public const CHANGETRACKING_NOTIFY = 3; /** * SET means that fields will be written to the database using a $set operator */ - const STORAGE_STRATEGY_SET = 'set'; + public const STORAGE_STRATEGY_SET = 'set'; /** * INCREMENT means that fields will be written to the database by calculating * the difference and using the $inc operator */ - const STORAGE_STRATEGY_INCREMENT = 'increment'; + public const STORAGE_STRATEGY_INCREMENT = 'increment'; - const STORAGE_STRATEGY_PUSH_ALL = 'pushAll'; - const STORAGE_STRATEGY_ADD_TO_SET = 'addToSet'; - const STORAGE_STRATEGY_ATOMIC_SET = 'atomicSet'; - const STORAGE_STRATEGY_ATOMIC_SET_ARRAY = 'atomicSetArray'; - const STORAGE_STRATEGY_SET_ARRAY = 'setArray'; + public const STORAGE_STRATEGY_PUSH_ALL = 'pushAll'; + public const STORAGE_STRATEGY_ADD_TO_SET = 'addToSet'; + public const STORAGE_STRATEGY_ATOMIC_SET = 'atomicSet'; + public const STORAGE_STRATEGY_ATOMIC_SET_ARRAY = 'atomicSetArray'; + public const STORAGE_STRATEGY_SET_ARRAY = 'setArray'; /** * READ-ONLY: The name of the mongo database the document is mapped to. @@ -198,7 +223,7 @@ class ClassMetadata implements BaseClassMetadata /** * READ-ONLY: The array of indexes for the document collection. */ - public $indexes = array(); + public $indexes = []; /** * READ-ONLY: Keys and options describing shard key. Only for sharded collections. @@ -240,26 +265,26 @@ class ClassMetadata implements BaseClassMetadata * * @var array */ - public $parentClasses = array(); + public $parentClasses = []; /** * READ-ONLY: The names of all subclasses (descendants). * * @var array */ - public $subClasses = array(); + public $subClasses = []; /** * The ReflectionProperty instances of the mapped class. * * @var \ReflectionProperty[] */ - public $reflFields = array(); + public $reflFields = []; /** * READ-ONLY: The inheritance mapping type used by the class. * - * @var integer + * @var int */ public $inheritanceType = self::INHERITANCE_TYPE_NONE; @@ -275,12 +300,12 @@ class ClassMetadata implements BaseClassMetadata * * @var array */ - public $generatorOptions = array(); + public $generatorOptions = []; /** * READ-ONLY: The ID generator used for generating IDs for this class. * - * @var \Doctrine\ODM\MongoDB\Id\AbstractIdGenerator + * @var AbstractIdGenerator */ public $idGenerator; @@ -299,7 +324,7 @@ class ClassMetadata implements BaseClassMetadata * * @var array */ - public $fieldMappings = array(); + public $fieldMappings = []; /** * READ-ONLY: The association mappings of the class. @@ -307,21 +332,21 @@ class ClassMetadata implements BaseClassMetadata * * @var array */ - public $associationMappings = array(); + public $associationMappings = []; /** * READ-ONLY: Array of fields to also load with a given method. * * @var array */ - public $alsoLoadMethods = array(); + public $alsoLoadMethods = []; /** * READ-ONLY: The registered lifecycle callbacks for documents of this class. * * @var array */ - public $lifecycleCallbacks = array(); + public $lifecycleCallbacks = []; /** * READ-ONLY: The discriminator value of this class. @@ -343,7 +368,7 @@ class ClassMetadata implements BaseClassMetadata * @var mixed * @see discriminatorField */ - public $discriminatorMap = array(); + public $discriminatorMap = []; /** * READ-ONLY: The definition of the discriminator field used in SINGLE_COLLECTION @@ -364,28 +389,28 @@ class ClassMetadata implements BaseClassMetadata /** * READ-ONLY: Whether this class describes the mapping of a mapped superclass. * - * @var boolean + * @var bool */ public $isMappedSuperclass = false; /** * READ-ONLY: Whether this class describes the mapping of a embedded document. * - * @var boolean + * @var bool */ public $isEmbeddedDocument = false; /** * READ-ONLY: Whether this class describes the mapping of an aggregation result document. * - * @var boolean + * @var bool */ public $isQueryResultDocument = false; /** * READ-ONLY: The policy used for change-tracking on entities of this class. * - * @var integer + * @var int */ public $changeTrackingPolicy = self::CHANGETRACKING_DEFERRED_IMPLICIT; @@ -393,7 +418,7 @@ class ClassMetadata implements BaseClassMetadata * READ-ONLY: A flag for whether or not instances of this class are to be versioned * with optimistic locking. * - * @var boolean $isVersioned + * @var bool $isVersioned */ public $isVersioned; @@ -408,7 +433,7 @@ class ClassMetadata implements BaseClassMetadata * READ-ONLY: A flag for whether or not instances of this class are to allow pessimistic * locking. * - * @var boolean $isLockable + * @var bool $isLockable */ public $isLockable; @@ -434,7 +459,7 @@ class ClassMetadata implements BaseClassMetadata public $isReadOnly; /** - * @var \Doctrine\Instantiator\InstantiatorInterface|null + * @var InstantiatorInterface|null */ private $instantiator; @@ -463,7 +488,7 @@ public function __construct($documentName) */ public static function getReferenceId($reference, $storeAs) { - return $storeAs === ClassMetadata::REFERENCE_STORE_AS_ID ? $reference : $reference[ClassMetadata::getReferencePrefix($storeAs) . 'id']; + return $storeAs === self::REFERENCE_STORE_AS_ID ? $reference : $reference[self::getReferencePrefix($storeAs) . 'id']; } /** @@ -473,11 +498,11 @@ public static function getReferenceId($reference, $storeAs) */ private static function getReferencePrefix($storeAs) { - if (!in_array($storeAs, [ClassMetadata::REFERENCE_STORE_AS_REF, ClassMetadata::REFERENCE_STORE_AS_DB_REF, ClassMetadata::REFERENCE_STORE_AS_DB_REF_WITH_DB])) { + if (! in_array($storeAs, [self::REFERENCE_STORE_AS_REF, self::REFERENCE_STORE_AS_DB_REF, self::REFERENCE_STORE_AS_DB_REF_WITH_DB])) { throw new \LogicException('Can only get a reference prefix for DBRef and reference arrays'); } - return $storeAs === ClassMetadata::REFERENCE_STORE_AS_REF ? '' : '$'; + return $storeAs === self::REFERENCE_STORE_AS_REF ? '' : '$'; } /** @@ -489,7 +514,7 @@ private static function getReferencePrefix($storeAs) */ public static function getReferenceFieldName($storeAs, $pathPrefix = '') { - if ($storeAs === ClassMetadata::REFERENCE_STORE_AS_ID) { + if ($storeAs === self::REFERENCE_STORE_AS_ID) { return $pathPrefix; } @@ -501,7 +526,7 @@ public static function getReferenceFieldName($storeAs, $pathPrefix = '') */ public function getReflectionClass() { - if ( ! $this->reflClass) { + if (! $this->reflClass) { $this->reflClass = new \ReflectionClass($this->name); } @@ -535,7 +560,7 @@ public function setIdentifier($identifier) */ public function getIdentifier() { - return array($this->identifier); + return [$this->identifier]; } /** @@ -546,7 +571,7 @@ public function getIdentifier() */ public function getIdentifierFieldNames() { - return array($this->identifier); + return [$this->identifier]; } /** @@ -560,7 +585,7 @@ public function hasField($fieldName) /** * Sets the inheritance type used by the class and it's subclasses. * - * @param integer $type + * @param int $type */ public function setInheritanceType($type) { @@ -572,7 +597,7 @@ public function setInheritanceType($type) * * @param string $fieldName * - * @return boolean TRUE if the field is inherited, FALSE otherwise. + * @return bool TRUE if the field is inherited, FALSE otherwise. */ public function isInheritedField($fieldName) { @@ -607,9 +632,9 @@ public function setCustomRepositoryClass($repositoryClassName) * @throws \InvalidArgumentException if document class is not this class or * a Proxy of this class */ - public function invokeLifecycleCallbacks($event, $document, array $arguments = null) + public function invokeLifecycleCallbacks($event, $document, ?array $arguments = null) { - if ( ! $document instanceof $this->name) { + if (! $document instanceof $this->name) { throw new \InvalidArgumentException(sprintf('Expected document class "%s"; found: "%s"', $this->name, get_class($document))); } @@ -619,7 +644,7 @@ public function invokeLifecycleCallbacks($event, $document, array $arguments = n foreach ($this->lifecycleCallbacks[$event] as $callback) { if ($arguments !== null) { - call_user_func_array(array($document, $callback), $arguments); + call_user_func_array([$document, $callback], $arguments); } else { $document->$callback(); } @@ -631,7 +656,7 @@ public function invokeLifecycleCallbacks($event, $document, array $arguments = n * * @param string $event Lifecycle event * - * @return boolean + * @return bool */ public function hasLifecycleCallbacks($event) { @@ -646,7 +671,7 @@ public function hasLifecycleCallbacks($event) */ public function getLifecycleCallbacks($event) { - return $this->lifecycleCallbacks[$event] ?? array(); + return $this->lifecycleCallbacks[$event] ?? []; } /** @@ -689,7 +714,7 @@ public function setLifecycleCallbacks(array $callbacks) */ public function registerAlsoLoadMethod($method, $fields) { - $this->alsoLoadMethods[$method] = is_array($fields) ? $fields : array($fields); + $this->alsoLoadMethods[$method] = is_array($fields) ? $fields : [$fields]; } /** @@ -734,7 +759,7 @@ public function setDiscriminatorField($discriminatorField) } foreach ($this->fieldMappings as $fieldMapping) { - if ($discriminatorField == $fieldMapping['name']) { + if ($discriminatorField === $fieldMapping['name']) { throw MappingException::discriminatorFieldConflict($this->name, $discriminatorField); } } @@ -757,10 +782,10 @@ public function setDiscriminatorMap(array $map) $className = $this->namespace . '\\' . $className; } $this->discriminatorMap[$value] = $className; - if ($this->name == $className) { + if ($this->name === $className) { $this->discriminatorValue = $value; } else { - if ( ! class_exists($className)) { + if (! class_exists($className)) { throw MappingException::invalidClassInDiscriminatorMap($className, $this->name); } if (is_subclass_of($className, $this->name)) { @@ -786,7 +811,7 @@ public function setDefaultDiscriminatorValue($defaultDiscriminatorValue) return; } - if (!array_key_exists($defaultDiscriminatorValue, $this->discriminatorMap)) { + if (! array_key_exists($defaultDiscriminatorValue, $this->discriminatorMap)) { throw MappingException::invalidDiscriminatorValue($defaultDiscriminatorValue, $this->name); } @@ -809,14 +834,14 @@ public function setDiscriminatorValue($value) /** * Add a index for this Document. * - * @param array $keys Array of keys for the index. + * @param array $keys Array of keys for the index. * @param array $options Array of options for the index. */ - public function addIndex($keys, array $options = array()) + public function addIndex($keys, array $options = []) { - $this->indexes[] = array( - 'keys' => array_map(function($value) { - if ($value == 1 || $value == -1) { + $this->indexes[] = [ + 'keys' => array_map(function ($value) { + if ($value === 1 || $value === -1) { return (int) $value; } if (is_string($value)) { @@ -829,8 +854,8 @@ public function addIndex($keys, array $options = array()) } return $value; }, $keys), - 'options' => $options - ); + 'options' => $options, + ]; } /** @@ -846,7 +871,7 @@ public function getIndexes() /** * Checks whether this document has indexes or not. * - * @return boolean + * @return bool */ public function hasIndexes() { @@ -856,14 +881,14 @@ public function hasIndexes() /** * Set shard key for this Document. * - * @param array $keys Array of document keys. + * @param array $keys Array of document keys. * @param array $options Array of sharding options. * * @throws MappingException */ - public function setShardKey(array $keys, array $options = array()) + public function setShardKey(array $keys, array $options = []) { - if ($this->inheritanceType === self::INHERITANCE_TYPE_SINGLE_COLLECTION && !is_null($this->shardKey)) { + if ($this->inheritanceType === self::INHERITANCE_TYPE_SINGLE_COLLECTION && ! is_null($this->shardKey)) { throw MappingException::shardKeyInSingleCollInheritanceSubclass($this->getName()); } @@ -885,9 +910,9 @@ public function setShardKey(array $keys, array $options = array()) } } - $this->shardKey = array( - 'keys' => array_map(function($value) { - if ($value == 1 || $value == -1) { + $this->shardKey = [ + 'keys' => array_map(function ($value) { + if ($value === 1 || $value === -1) { return (int) $value; } if (is_string($value)) { @@ -900,8 +925,8 @@ public function setShardKey(array $keys, array $options = array()) } return $value; }, $keys), - 'options' => $options - ); + 'options' => $options, + ]; } /** @@ -925,7 +950,7 @@ public function isSharded() /** * Sets the read preference used by this class. * - * @param string $readPreference + * @param string $readPreference * @param array|null $tags */ public function setReadPreference($readPreference, $tags) @@ -965,7 +990,7 @@ public function hasWriteConcern() /** * Sets the change tracking policy used by this class. * - * @param integer $policy + * @param int $policy */ public function setChangeTrackingPolicy($policy) { @@ -975,31 +1000,31 @@ public function setChangeTrackingPolicy($policy) /** * Whether the change tracking policy of this class is "deferred explicit". * - * @return boolean + * @return bool */ public function isChangeTrackingDeferredExplicit() { - return $this->changeTrackingPolicy == self::CHANGETRACKING_DEFERRED_EXPLICIT; + return $this->changeTrackingPolicy === self::CHANGETRACKING_DEFERRED_EXPLICIT; } /** * Whether the change tracking policy of this class is "deferred implicit". * - * @return boolean + * @return bool */ public function isChangeTrackingDeferredImplicit() { - return $this->changeTrackingPolicy == self::CHANGETRACKING_DEFERRED_IMPLICIT; + return $this->changeTrackingPolicy === self::CHANGETRACKING_DEFERRED_IMPLICIT; } /** * Whether the change tracking policy of this class is "notify". * - * @return boolean + * @return bool */ public function isChangeTrackingNotify() { - return $this->changeTrackingPolicy == self::CHANGETRACKING_NOTIFY; + return $this->changeTrackingPolicy === self::CHANGETRACKING_NOTIFY; } /** @@ -1082,7 +1107,7 @@ public function getCollection() public function setCollection($name) { if (is_array($name)) { - if ( ! isset($name['name'])) { + if (! isset($name['name'])) { throw new \InvalidArgumentException('A name key is required when passing an array to setCollection()'); } $this->collectionCapped = $name['capped'] ?? false; @@ -1097,7 +1122,7 @@ public function setCollection($name) /** * Get whether or not the documents collection is capped. * - * @return boolean + * @return bool */ public function getCollectionCapped() { @@ -1107,7 +1132,7 @@ public function getCollectionCapped() /** * Set whether or not the documents collection is capped. * - * @param boolean $bool + * @param bool $bool */ public function setCollectionCapped($bool) { @@ -1117,7 +1142,7 @@ public function setCollectionCapped($bool) /** * Get the collection size * - * @return integer + * @return int */ public function getCollectionSize() { @@ -1127,7 +1152,7 @@ public function getCollectionSize() /** * Set the collection size. * - * @param integer $size + * @param int $size */ public function setCollectionSize($size) { @@ -1137,7 +1162,7 @@ public function setCollectionSize($size) /** * Get the collection max. * - * @return integer + * @return int */ public function getCollectionMax() { @@ -1147,7 +1172,7 @@ public function getCollectionMax() /** * Set the collection max. * - * @param integer $max + * @param int $max */ public function setCollectionMax($max) { @@ -1157,7 +1182,7 @@ public function setCollectionMax($max) /** * Returns TRUE if this Document is mapped to a collection FALSE otherwise. * - * @return boolean + * @return bool */ public function isMappedToCollection() { @@ -1167,7 +1192,7 @@ public function isMappedToCollection() /** * Validates the storage strategy of a mapping for consistency * @param array $mapping - * @throws \Doctrine\ODM\MongoDB\Mapping\MappingException + * @throws MappingException */ private function applyStorageStrategy(array &$mapping) { @@ -1176,13 +1201,13 @@ private function applyStorageStrategy(array &$mapping) } switch (true) { - case $mapping['type'] == 'int': - case $mapping['type'] == 'float': + case $mapping['type'] === 'int': + case $mapping['type'] === 'float': $defaultStrategy = self::STORAGE_STRATEGY_SET; $allowedStrategies = [self::STORAGE_STRATEGY_SET, self::STORAGE_STRATEGY_INCREMENT]; break; - case $mapping['type'] == 'many': + case $mapping['type'] === 'many': $defaultStrategy = CollectionHelper::DEFAULT_STRATEGY; $allowedStrategies = [ self::STORAGE_STRATEGY_PUSH_ALL, @@ -1284,7 +1309,6 @@ public function addInheritedFieldMapping(array $fieldMapping) * * @param array $mapping * - * @return void * * @throws MappingException */ @@ -1297,7 +1321,7 @@ public function addInheritedAssociationMapping(array $mapping/*, $owningClassNam * Checks whether the class has a mapped association with the given field name. * * @param string $fieldName - * @return boolean + * @return bool */ public function hasReference($fieldName) { @@ -1308,7 +1332,7 @@ public function hasReference($fieldName) * Checks whether the class has a mapped embed with the given field name. * * @param string $fieldName - * @return boolean + * @return bool */ public function hasEmbed($fieldName) { @@ -1352,7 +1376,7 @@ public function isCollectionValuedAssociation($fieldName) * and if yes, checks whether it is a single-valued association (to-one). * * @param string $fieldName - * @return boolean TRUE if the association exists and is single-valued, FALSE otherwise. + * @return bool TRUE if the association exists and is single-valued, FALSE otherwise. */ public function isSingleValuedReference($fieldName) { @@ -1365,7 +1389,7 @@ public function isSingleValuedReference($fieldName) * and if yes, checks whether it is a collection-valued association (to-many). * * @param string $fieldName - * @return boolean TRUE if the association exists and is collection-valued, FALSE otherwise. + * @return bool TRUE if the association exists and is collection-valued, FALSE otherwise. */ public function isCollectionValuedReference($fieldName) { @@ -1378,7 +1402,7 @@ public function isCollectionValuedReference($fieldName) * and if yes, checks whether it is a single-valued association (to-one). * * @param string $fieldName - * @return boolean TRUE if the association exists and is single-valued, FALSE otherwise. + * @return bool TRUE if the association exists and is single-valued, FALSE otherwise. */ public function isSingleValuedEmbed($fieldName) { @@ -1391,7 +1415,7 @@ public function isSingleValuedEmbed($fieldName) * and if yes, checks whether it is a collection-valued association (to-many). * * @param string $fieldName - * @return boolean TRUE if the association exists and is collection-valued, FALSE otherwise. + * @return bool TRUE if the association exists and is collection-valued, FALSE otherwise. */ public function isCollectionValuedEmbed($fieldName) { @@ -1402,7 +1426,7 @@ public function isCollectionValuedEmbed($fieldName) /** * Sets the ID generator used to generate IDs for instances of this class. * - * @param \Doctrine\ODM\MongoDB\Id\AbstractIdGenerator $generator + * @param AbstractIdGenerator $generator */ public function setIdGenerator($generator) { @@ -1439,7 +1463,7 @@ public function getDatabaseIdentifierValue($id) * The value will be converted to a PHP type before being set. * * @param object $document - * @param mixed $id + * @param mixed $id */ public function setIdentifierValue($document, $id) { @@ -1467,7 +1491,7 @@ public function getIdentifierValue($document) */ public function getIdentifierValues($object) { - return array($this->identifier => $this->getIdentifierValue($object)); + return [$this->identifier => $this->getIdentifierValue($object)]; } /** @@ -1475,7 +1499,7 @@ public function getIdentifierValues($object) * * @param object $document * - * @return \MongoDB\BSON\ObjectId $id The ObjectId + * @return ObjectId $id The ObjectId */ public function getIdentifierObject($document) { @@ -1487,7 +1511,7 @@ public function getIdentifierObject($document) * * @param object $document * @param string $field - * @param mixed $value + * @param mixed $value */ public function setFieldValue($document, $field, $value) { @@ -1520,7 +1544,7 @@ public function getFieldValue($document, $field) /** * Gets the mapping of a field. * - * @param string $fieldName The field name. + * @param string $fieldName The field name. * * @return array The field mapping. * @@ -1528,7 +1552,7 @@ public function getFieldValue($document, $field) */ public function getFieldMapping($fieldName) { - if ( ! isset($this->fieldMappings[$fieldName])) { + if (! isset($this->fieldMappings[$fieldName])) { throw MappingException::mappingNotFound($this->name, $fieldName); } return $this->fieldMappings[$fieldName]; @@ -1543,7 +1567,9 @@ public function getEmbeddedFieldsMappings() { return array_filter( $this->associationMappings, - function($assoc) { return ! empty($assoc['embedded']); } + function ($assoc) { + return ! empty($assoc['embedded']); + } ); } @@ -1559,7 +1585,7 @@ function($assoc) { return ! empty($assoc['embedded']); } public function getFieldMappingByDbFieldName($dbFieldName) { foreach ($this->fieldMappings as $mapping) { - if ($mapping['name'] == $dbFieldName) { + if ($mapping['name'] === $dbFieldName) { return $mapping; } } @@ -1570,15 +1596,15 @@ public function getFieldMappingByDbFieldName($dbFieldName) /** * Check if the field is not null. * - * @param string $fieldName The field name + * @param string $fieldName The field name * - * @return boolean TRUE if the field is not null, FALSE otherwise. + * @return bool TRUE if the field is not null, FALSE otherwise. */ public function isNullable($fieldName) { $mapping = $this->getFieldMapping($fieldName); if ($mapping !== false) { - return isset($mapping['nullable']) && $mapping['nullable'] == true; + return isset($mapping['nullable']) && $mapping['nullable'] === true; } return false; } @@ -1586,7 +1612,7 @@ public function isNullable($fieldName) /** * Checks whether the document has a discriminator field and value configured. * - * @return boolean + * @return bool */ public function hasDiscriminator() { @@ -1614,31 +1640,31 @@ public function setIdGeneratorOptions($generatorOptions) } /** - * @return boolean + * @return bool */ public function isInheritanceTypeNone() { - return $this->inheritanceType == self::INHERITANCE_TYPE_NONE; + return $this->inheritanceType === self::INHERITANCE_TYPE_NONE; } /** * Checks whether the mapped class uses the SINGLE_COLLECTION inheritance mapping strategy. * - * @return boolean + * @return bool */ public function isInheritanceTypeSingleCollection() { - return $this->inheritanceType == self::INHERITANCE_TYPE_SINGLE_COLLECTION; + return $this->inheritanceType === self::INHERITANCE_TYPE_SINGLE_COLLECTION; } /** * Checks whether the mapped class uses the COLLECTION_PER_CLASS inheritance mapping strategy. * - * @return boolean + * @return bool */ public function isInheritanceTypeCollectionPerClass() { - return $this->inheritanceType == self::INHERITANCE_TYPE_COLLECTION_PER_CLASS; + return $this->inheritanceType === self::INHERITANCE_TYPE_COLLECTION_PER_CLASS; } /** @@ -1676,48 +1702,48 @@ public function setParentClasses(array $classNames) /** * Checks whether the class will generate a new \MongoDB\BSON\ObjectId instance for us. * - * @return boolean TRUE if the class uses the AUTO generator, FALSE otherwise. + * @return bool TRUE if the class uses the AUTO generator, FALSE otherwise. */ public function isIdGeneratorAuto() { - return $this->generatorType == self::GENERATOR_TYPE_AUTO; + return $this->generatorType === self::GENERATOR_TYPE_AUTO; } /** * Checks whether the class will use a collection to generate incremented identifiers. * - * @return boolean TRUE if the class uses the INCREMENT generator, FALSE otherwise. + * @return bool TRUE if the class uses the INCREMENT generator, FALSE otherwise. */ public function isIdGeneratorIncrement() { - return $this->generatorType == self::GENERATOR_TYPE_INCREMENT; + return $this->generatorType === self::GENERATOR_TYPE_INCREMENT; } /** * Checks whether the class will generate a uuid id. * - * @return boolean TRUE if the class uses the UUID generator, FALSE otherwise. + * @return bool TRUE if the class uses the UUID generator, FALSE otherwise. */ public function isIdGeneratorUuid() { - return $this->generatorType == self::GENERATOR_TYPE_UUID; + return $this->generatorType === self::GENERATOR_TYPE_UUID; } /** * Checks whether the class uses no id generator. * - * @return boolean TRUE if the class does not use any id generator, FALSE otherwise. + * @return bool TRUE if the class does not use any id generator, FALSE otherwise. */ public function isIdGeneratorNone() { - return $this->generatorType == self::GENERATOR_TYPE_NONE; + return $this->generatorType === self::GENERATOR_TYPE_NONE; } /** * Sets the version field mapping used for versioning. Sets the default * value to use depending on the column type. * - * @param array $mapping The version field mapping array + * @param array $mapping The version field mapping array * * @throws LockException */ @@ -1734,7 +1760,7 @@ public function setVersionMapping(array &$mapping) /** * Sets whether this class is to be versioned for optimistic locking. * - * @param boolean $bool + * @param bool $bool */ public function setVersioned($bool) { @@ -1756,9 +1782,9 @@ public function setVersionField($versionField) * Sets the version field mapping used for versioning. Sets the default * value to use depending on the column type. * - * @param array $mapping The version field mapping array + * @param array $mapping The version field mapping array * - * @throws \Doctrine\ODM\MongoDB\LockException + * @throws LockException */ public function setLockMapping(array &$mapping) { @@ -1773,7 +1799,7 @@ public function setLockMapping(array &$mapping) /** * Sets whether this class is to allow pessimistic locking. * - * @param boolean $bool + * @param bool $bool */ public function setLockable($bool) { @@ -1829,7 +1855,7 @@ public function getTypeOfField($fieldName) */ public function getAssociationTargetClass($assocName) { - if ( ! isset($this->associationMappings[$assocName])) { + if (! isset($this->associationMappings[$assocName])) { throw new InvalidArgumentException("Association name expected, '" . $assocName . "' is not an association."); } @@ -1843,11 +1869,11 @@ public function getAssociationTargetClass($assocName) */ public function getAssociationCollectionClass($assocName) { - if ( ! isset($this->associationMappings[$assocName])) { + if (! isset($this->associationMappings[$assocName])) { throw new InvalidArgumentException("Association name expected, '" . $assocName . "' is not an association."); } - if ( ! array_key_exists('collectionClass', $this->associationMappings[$assocName])) { + if (! array_key_exists('collectionClass', $this->associationMappings[$assocName])) { throw new InvalidArgumentException("collectionClass can only be applied to 'embedMany' and 'referenceMany' associations."); } @@ -1881,22 +1907,19 @@ public function getAssociationMappedByTargetField($fieldName) */ public function mapField(array $mapping) { - if ( ! isset($mapping['fieldName']) && isset($mapping['name'])) { + if (! isset($mapping['fieldName']) && isset($mapping['name'])) { $mapping['fieldName'] = $mapping['name']; } - if ( ! isset($mapping['fieldName'])) { + if (! isset($mapping['fieldName'])) { throw MappingException::missingFieldName($this->name); } - if ( ! isset($mapping['name'])) { + if (! isset($mapping['name'])) { $mapping['name'] = $mapping['fieldName']; } if ($this->identifier === $mapping['name'] && empty($mapping['id'])) { throw MappingException::mustNotChangeIdentifierFieldsType($this->name, $mapping['name']); } - if (isset($this->fieldMappings[$mapping['fieldName']])) { - //throw MappingException::duplicateFieldMapping($this->name, $mapping['fieldName']); - } - if ($this->discriminatorField !== null && $this->discriminatorField == $mapping['name']) { + if ($this->discriminatorField !== null && $this->discriminatorField === $mapping['name']) { throw MappingException::discriminatorFieldConflict($this->name, $this->discriminatorField); } if (isset($mapping['targetDocument']) && strpos($mapping['targetDocument'], '\\') === false && strlen($this->namespace)) { @@ -1908,9 +1931,9 @@ public function mapField(array $mapping) } $mapping['collectionClass'] = ltrim($mapping['collectionClass'], '\\'); } - if ( ! empty($mapping['collectionClass'])) { + if (! empty($mapping['collectionClass'])) { $rColl = new \ReflectionClass($mapping['collectionClass']); - if ( ! $rColl->implementsInterface('Doctrine\\Common\\Collections\\Collection')) { + if (! $rColl->implementsInterface('Doctrine\\Common\\Collections\\Collection')) { throw MappingException::collectionClassDoesNotImplementCommonInterface($this->name, $mapping['fieldName'], $mapping['collectionClass']); } } @@ -1927,10 +1950,10 @@ public function mapField(array $mapping) throw MappingException::cascadeOnEmbeddedNotAllowed($this->name, $mapping['fieldName']); } - $cascades = isset($mapping['cascade']) ? array_map('strtolower', (array) $mapping['cascade']) : array(); + $cascades = isset($mapping['cascade']) ? array_map('strtolower', (array) $mapping['cascade']) : []; if (in_array('all', $cascades) || isset($mapping['embedded'])) { - $cascades = array('remove', 'persist', 'refresh', 'merge', 'detach'); + $cascades = ['remove', 'persist', 'refresh', 'merge', 'detach']; } if (isset($mapping['embedded'])) { @@ -1949,15 +1972,15 @@ public function mapField(array $mapping) $mapping['name'] = '_id'; $this->identifier = $mapping['fieldName']; if (isset($mapping['strategy'])) { - $this->generatorType = constant(ClassMetadata::class . '::GENERATOR_TYPE_' . strtoupper($mapping['strategy'])); + $this->generatorType = constant(self::class . '::GENERATOR_TYPE_' . strtoupper($mapping['strategy'])); } - $this->generatorOptions = $mapping['options'] ?? array(); + $this->generatorOptions = $mapping['options'] ?? []; switch ($this->generatorType) { case self::GENERATOR_TYPE_AUTO: $mapping['type'] = 'id'; break; default: - if ( ! empty($this->generatorOptions['type'])) { + if (! empty($this->generatorOptions['type'])) { $mapping['type'] = $this->generatorOptions['type']; } elseif (empty($mapping['type'])) { $mapping['type'] = $this->generatorType === self::GENERATOR_TYPE_INCREMENT ? 'int_id' : 'custom_id'; @@ -1966,13 +1989,13 @@ public function mapField(array $mapping) unset($this->generatorOptions['type']); } - if ( ! isset($mapping['nullable'])) { + if (! isset($mapping['nullable'])) { $mapping['nullable'] = false; } if (isset($mapping['reference']) && isset($mapping['storeAs']) - && $mapping['storeAs'] === ClassMetadata::REFERENCE_STORE_AS_ID + && $mapping['storeAs'] === self::REFERENCE_STORE_AS_ID && ! isset($mapping['targetDocument']) ) { throw MappingException::simpleReferenceRequiresTargetDocument($this->name, $mapping['fieldName']); @@ -2032,12 +2055,12 @@ public function mapField(array $mapping) $mapping['isInverseSide'] = true; $mapping['isOwningSide'] = false; } - if (!isset($mapping['orphanRemoval'])) { + if (! isset($mapping['orphanRemoval'])) { $mapping['orphanRemoval'] = false; } } - if (!empty($mapping['prime']) && ($mapping['association'] !== self::REFERENCE_MANY || !$mapping['isInverseSide'])) { + if (! empty($mapping['prime']) && ($mapping['association'] !== self::REFERENCE_MANY || ! $mapping['isInverseSide'])) { throw MappingException::referencePrimersOnlySupportedForInverseReferenceMany($this->name, $mapping['fieldName']); } @@ -2071,7 +2094,7 @@ public function mapField(array $mapping) public function __sleep() { // This metadata is always serialized/cached. - $serialized = array( + $serialized = [ 'fieldMappings', 'associationMappings', 'identifier', @@ -2088,10 +2111,10 @@ public function __sleep() 'idGenerator', 'indexes', 'shardKey', - ); + ]; // The rest of the metadata is only serialized if necessary. - if ($this->changeTrackingPolicy != self::CHANGETRACKING_DEFERRED_IMPLICIT) { + if ($this->changeTrackingPolicy !== self::CHANGETRACKING_DEFERRED_IMPLICIT) { $serialized[] = 'changeTrackingPolicy'; } @@ -2099,7 +2122,7 @@ public function __sleep() $serialized[] = 'customRepositoryClassName'; } - if ($this->inheritanceType != self::INHERITANCE_TYPE_NONE || $this->discriminatorField !== null) { + if ($this->inheritanceType !== self::INHERITANCE_TYPE_NONE || $this->discriminatorField !== null) { $serialized[] = 'inheritanceType'; $serialized[] = 'discriminatorField'; $serialized[] = 'discriminatorValue'; @@ -2146,7 +2169,6 @@ public function __sleep() /** * Restores some state that can not be serialized/unserialized. * - * @return void */ public function __wakeup() { diff --git a/lib/Doctrine/ODM/MongoDB/Mapping/ClassMetadataFactory.php b/lib/Doctrine/ODM/MongoDB/Mapping/ClassMetadataFactory.php index 04537a6514..6d28497ef3 100644 --- a/lib/Doctrine/ODM/MongoDB/Mapping/ClassMetadataFactory.php +++ b/lib/Doctrine/ODM/MongoDB/Mapping/ClassMetadataFactory.php @@ -1,9 +1,13 @@ identifier && ! $class->isMappedSuperclass && ! $class->isEmbeddedDocument && ! $class->isQueryResultDocument) { + if (! $class->identifier && ! $class->isMappedSuperclass && ! $class->isEmbeddedDocument && ! $class->isQueryResultDocument) { throw MappingException::identifierRequired($class->name); } } @@ -190,7 +196,7 @@ protected function validateIdentifier($class) * Creates a new ClassMetadata instance for the given class name. * * @param string $className - * @return \Doctrine\ODM\MongoDB\Mapping\ClassMetadata + * @return ClassMetadata */ protected function newClassMetadataInstance($className) { @@ -240,16 +246,16 @@ private function completeIdGeneratorMapping(ClassMetadata $class) throw MappingException::missingIdGeneratorClass($class->name); } - $customGenerator = new $idGenOptions['class']; + $customGenerator = new $idGenOptions['class'](); unset($idGenOptions['class']); - if ( ! $customGenerator instanceof AbstractIdGenerator) { + if (! $customGenerator instanceof AbstractIdGenerator) { throw MappingException::classIsNotAValidGenerator(get_class($customGenerator)); } $methods = get_class_methods($customGenerator); foreach ($idGenOptions as $name => $value) { $method = 'set' . ucfirst($name); - if ( ! in_array($method, $methods)) { + if (! in_array($method, $methods)) { throw MappingException::missingGeneratorSetter(get_class($customGenerator), $name); } @@ -267,16 +273,14 @@ private function completeIdGeneratorMapping(ClassMetadata $class) /** * Adds inherited fields to the subclass mapping. * - * @param ClassMetadata $subClass - * @param ClassMetadata $parentClass */ private function addInheritedFields(ClassMetadata $subClass, ClassMetadata $parentClass) { foreach ($parentClass->fieldMappings as $fieldName => $mapping) { - if ( ! isset($mapping['inherited']) && ! $parentClass->isMappedSuperclass) { + if (! isset($mapping['inherited']) && ! $parentClass->isMappedSuperclass) { $mapping['inherited'] = $parentClass->name; } - if ( ! isset($mapping['declared'])) { + if (! isset($mapping['declared'])) { $mapping['declared'] = $parentClass->name; } $subClass->addInheritedFieldMapping($mapping); @@ -290,10 +294,7 @@ private function addInheritedFields(ClassMetadata $subClass, ClassMetadata $pare /** * Adds inherited association mappings to the subclass mapping. * - * @param \Doctrine\ODM\MongoDB\Mapping\ClassMetadata $subClass - * @param \Doctrine\ODM\MongoDB\Mapping\ClassMetadata $parentClass * - * @return void * * @throws MappingException */ @@ -304,10 +305,10 @@ private function addInheritedRelations(ClassMetadata $subClass, ClassMetadata $p $mapping['sourceDocument'] = $subClass->name; } - if ( ! isset($mapping['inherited']) && ! $parentClass->isMappedSuperclass) { + if (! isset($mapping['inherited']) && ! $parentClass->isMappedSuperclass) { $mapping['inherited'] = $parentClass->name; } - if ( ! isset($mapping['declared'])) { + if (! isset($mapping['declared'])) { $mapping['declared'] = $parentClass->name; } $subClass->addInheritedAssociationMapping($mapping); @@ -317,8 +318,6 @@ private function addInheritedRelations(ClassMetadata $subClass, ClassMetadata $p /** * Adds inherited indexes to the subclass mapping. * - * @param ClassMetadata $subClass - * @param ClassMetadata $parentClass */ private function addInheritedIndexes(ClassMetadata $subClass, ClassMetadata $parentClass) { @@ -330,8 +329,6 @@ private function addInheritedIndexes(ClassMetadata $subClass, ClassMetadata $par /** * Adds inherited shard key to the subclass mapping. * - * @param ClassMetadata $subClass - * @param ClassMetadata $parentClass */ private function setInheritedShardKey(ClassMetadata $subClass, ClassMetadata $parentClass) { diff --git a/lib/Doctrine/ODM/MongoDB/Mapping/Driver/AnnotationDriver.php b/lib/Doctrine/ODM/MongoDB/Mapping/Driver/AnnotationDriver.php index aac40f8924..28916671d6 100644 --- a/lib/Doctrine/ODM/MongoDB/Mapping/Driver/AnnotationDriver.php +++ b/lib/Doctrine/ODM/MongoDB/Mapping/Driver/AnnotationDriver.php @@ -1,41 +1,50 @@ 1, ODM\MappedSuperclass::class => 2, ODM\EmbeddedDocument::class => 3, ODM\QueryResultDocument::class => 4, - ); + ]; /** * {@inheritdoc} */ public function loadMetadataForClass($className, \Doctrine\Common\Persistence\Mapping\ClassMetadata $class) { - /** @var $class ClassMetadata */ + /** @var ClassMetadata $class */ $reflClass = $class->getReflectionClass(); $classAnnotations = $this->reader->getClassAnnotations($reflClass); - $documentAnnots = array(); + $documentAnnots = []; foreach ($classAnnotations as $annot) { $classAnnotations[get_class($annot)] = $annot; @@ -51,11 +60,11 @@ public function loadMetadataForClass($className, \Doctrine\Common\Persistence\Ma $this->addIndex($class, $annot); } if ($annot instanceof ODM\Indexes) { - foreach (is_array($annot->value) ? $annot->value : array($annot->value) as $index) { + foreach (is_array($annot->value) ? $annot->value : [$annot->value] as $index) { $this->addIndex($class, $index); } } elseif ($annot instanceof ODM\InheritanceType) { - $class->setInheritanceType(constant(ClassMetadata::class . '::INHERITANCE_TYPE_'.$annot->value)); + $class->setInheritanceType(constant(ClassMetadata::class . '::INHERITANCE_TYPE_' . $annot->value)); } elseif ($annot instanceof ODM\DiscriminatorField) { $class->setDiscriminatorField($annot->value); } elseif ($annot instanceof ODM\DiscriminatorMap) { @@ -63,16 +72,15 @@ public function loadMetadataForClass($className, \Doctrine\Common\Persistence\Ma } elseif ($annot instanceof ODM\DiscriminatorValue) { $class->setDiscriminatorValue($annot->value); } elseif ($annot instanceof ODM\ChangeTrackingPolicy) { - $class->setChangeTrackingPolicy(constant(ClassMetadata::class . '::CHANGETRACKING_'.$annot->value)); + $class->setChangeTrackingPolicy(constant(ClassMetadata::class . '::CHANGETRACKING_' . $annot->value)); } elseif ($annot instanceof ODM\DefaultDiscriminatorValue) { $class->setDefaultDiscriminatorValue($annot->value); } elseif ($annot instanceof ODM\ReadPreference) { $class->setReadPreference($annot->value, $annot->tags); } - } - if ( ! $documentAnnots) { + if (! $documentAnnots) { throw MappingException::classIsNotAValidDocument($className); } @@ -115,8 +123,8 @@ public function loadMetadataForClass($className, \Doctrine\Common\Persistence\Ma continue; } - $indexes = array(); - $mapping = array('fieldName' => $property->getName()); + $indexes = []; + $mapping = ['fieldName' => $property->getName()]; $fieldAnnot = null; foreach ($this->reader->getPropertyAnnotations($property) as $annot) { @@ -130,7 +138,7 @@ public function loadMetadataForClass($className, \Doctrine\Common\Persistence\Ma $indexes[] = $annot; } if ($annot instanceof ODM\Indexes) { - foreach (is_array($annot->value) ? $annot->value : array($annot->value) as $index) { + foreach (is_array($annot->value) ? $annot->value : [$annot->value] as $index) { $indexes[] = $index; } } elseif ($annot instanceof ODM\AlsoLoad) { @@ -150,7 +158,7 @@ public function loadMetadataForClass($className, \Doctrine\Common\Persistence\Ma if ($indexes) { foreach ($indexes as $index) { $name = $mapping['name'] ?? $mapping['fieldName']; - $keys = array($name => $index->order ?: 'asc'); + $keys = [$name => $index->order ?: 'asc']; $this->addIndex($class, $index, $keys); } } @@ -175,7 +183,7 @@ public function loadMetadataForClass($className, \Doctrine\Common\Persistence\Ma $class->registerAlsoLoadMethod($method->getName(), $annot->value); } - if ( ! isset($classAnnotations[ODM\HasLifecycleCallbacks::class])) { + if (! isset($classAnnotations[ODM\HasLifecycleCallbacks::class])) { continue; } @@ -202,11 +210,11 @@ public function loadMetadataForClass($className, \Doctrine\Common\Persistence\Ma } } - private function addIndex(ClassMetadata $class, $index, array $keys = array()) + private function addIndex(ClassMetadata $class, $index, array $keys = []) { $keys = array_merge($keys, $index->keys); - $options = array(); - $allowed = array('name', 'dropDups', 'background', 'unique', 'sparse', 'expireAfterSeconds'); + $options = []; + $allowed = ['name', 'dropDups', 'background', 'unique', 'sparse', 'expireAfterSeconds']; foreach ($allowed as $name) { if (isset($index->$name)) { $options[$name] = $index->$name; @@ -220,15 +228,13 @@ private function addIndex(ClassMetadata $class, $index, array $keys = array()) } /** - * @param ClassMetadata $class - * @param ODM\ShardKey $shardKey * * @throws MappingException */ private function setShardKey(ClassMetadata $class, ODM\ShardKey $shardKey) { - $options = array(); - $allowed = array('unique', 'numInitialChunks'); + $options = []; + $allowed = ['unique', 'numInitialChunks']; foreach ($allowed as $name) { if (isset($shardKey->$name)) { $options[$name] = $shardKey->$name; @@ -242,10 +248,9 @@ private function setShardKey(ClassMetadata $class, ODM\ShardKey $shardKey) * Factory method for the Annotation Driver * * @param array|string $paths - * @param Reader $reader * @return AnnotationDriver */ - public static function create($paths = array(), Reader $reader = null) + public static function create($paths = [], ?Reader $reader = null) { if ($reader === null) { $reader = new AnnotationReader(); diff --git a/lib/Doctrine/ODM/MongoDB/Mapping/Driver/SimplifiedXmlDriver.php b/lib/Doctrine/ODM/MongoDB/Mapping/Driver/SimplifiedXmlDriver.php index 3a9f8ead11..e638a0be16 100644 --- a/lib/Doctrine/ODM/MongoDB/Mapping/Driver/SimplifiedXmlDriver.php +++ b/lib/Doctrine/ODM/MongoDB/Mapping/Driver/SimplifiedXmlDriver.php @@ -1,5 +1,7 @@ getElement($className); - if ( ! $xmlRoot) { + if (! $xmlRoot) { return; } - if ($xmlRoot->getName() == 'document') { + if ($xmlRoot->getName() === 'document') { if (isset($xmlRoot['repository-class'])) { $class->setCustomRepositoryClass((string) $xmlRoot['repository-class']); } - } elseif ($xmlRoot->getName() == 'mapped-superclass') { + } elseif ($xmlRoot->getName() === 'mapped-superclass') { $class->setCustomRepositoryClass( isset($xmlRoot['repository-class']) ? (string) $xmlRoot['repository-class'] : null ); $class->isMappedSuperclass = true; - } elseif ($xmlRoot->getName() == 'embedded-document') { + } elseif ($xmlRoot->getName() === 'embedded-document') { $class->isEmbeddedDocument = true; - } elseif ($xmlRoot->getName() == 'query-result-document') { + } elseif ($xmlRoot->getName() === 'query-result-document') { $class->isQueryResultDocument = true; } if (isset($xmlRoot['db'])) { @@ -54,7 +68,7 @@ public function loadMetadataForClass($className, \Doctrine\Common\Persistence\Ma } if (isset($xmlRoot['collection'])) { if (isset($xmlRoot['capped-collection'])) { - $config = array('name' => (string) $xmlRoot['collection']); + $config = ['name' => (string) $xmlRoot['collection']]; $config['capped'] = (bool) $xmlRoot['capped-collection']; if (isset($xmlRoot['capped-collection-max'])) { $config['max'] = (int) $xmlRoot['capped-collection-max']; @@ -87,7 +101,7 @@ public function loadMetadataForClass($className, \Doctrine\Common\Persistence\Ma ); } if (isset($xmlRoot->{'discriminator-map'})) { - $map = array(); + $map = []; foreach ($xmlRoot->{'discriminator-map'}->{'discriminator-mapping'} as $discrMapElement) { $map[(string) $discrMapElement['value']] = (string) $discrMapElement['class']; } @@ -104,7 +118,7 @@ public function loadMetadataForClass($className, \Doctrine\Common\Persistence\Ma if (isset($xmlRoot->{'shard-key'})) { $this->setShardKey($class, $xmlRoot->{'shard-key'}[0]); } - if (isset($xmlRoot['read-only']) && 'true' === (string) $xmlRoot['read-only']) { + if (isset($xmlRoot['read-only']) && (string) $xmlRoot['read-only'] === 'true') { $class->markReadOnly(); } if (isset($xmlRoot->{'read-preference'})) { @@ -112,17 +126,17 @@ public function loadMetadataForClass($className, \Doctrine\Common\Persistence\Ma } if (isset($xmlRoot->field)) { foreach ($xmlRoot->field as $field) { - $mapping = array(); + $mapping = []; $attributes = $field->attributes(); foreach ($attributes as $key => $value) { $mapping[$key] = (string) $value; - $booleanAttributes = array('id', 'reference', 'embed', 'unique', 'sparse'); + $booleanAttributes = ['id', 'reference', 'embed', 'unique', 'sparse']; if (in_array($key, $booleanAttributes)) { - $mapping[$key] = ('true' === $mapping[$key]); + $mapping[$key] = ($mapping[$key] === 'true'); } } if (isset($mapping['id']) && $mapping['id'] === true && isset($mapping['strategy'])) { - $mapping['options'] = array(); + $mapping['options'] = []; if (isset($field->{'id-generator-option'})) { foreach ($field->{'id-generator-option'} as $generatorOptions) { $attributesGenerator = iterator_to_array($generatorOptions->attributes()); @@ -134,15 +148,15 @@ public function loadMetadataForClass($className, \Doctrine\Common\Persistence\Ma } if (isset($attributes['not-saved'])) { - $mapping['notSaved'] = ('true' === (string) $attributes['not-saved']); + $mapping['notSaved'] = ((string) $attributes['not-saved'] === 'true'); } if (isset($attributes['also-load'])) { $mapping['alsoLoadFields'] = explode(',', $attributes['also-load']); } elseif (isset($attributes['version'])) { - $mapping['version'] = ('true' === (string) $attributes['version']); + $mapping['version'] = ((string) $attributes['version'] === 'true'); } elseif (isset($attributes['lock'])) { - $mapping['lock'] = ('true' === (string) $attributes['lock']); + $mapping['lock'] = ((string) $attributes['lock'] === 'true'); } $this->addFieldMapping($class, $mapping); @@ -193,27 +207,27 @@ private function addFieldMapping(ClassMetadata $class, $mapping) $class->mapField($mapping); // Index this field if either "index", "unique", or "sparse" are set - if ( ! (isset($mapping['index']) || isset($mapping['unique']) || isset($mapping['sparse']))) { + if (! (isset($mapping['index']) || isset($mapping['unique']) || isset($mapping['sparse']))) { return; } - $keys = array($name => $mapping['order'] ?? 'asc'); - $options = array(); + $keys = [$name => $mapping['order'] ?? 'asc']; + $options = []; if (isset($mapping['background'])) { - $options['background'] = (boolean) $mapping['background']; + $options['background'] = (bool) $mapping['background']; } if (isset($mapping['drop-dups'])) { - $options['dropDups'] = (boolean) $mapping['drop-dups']; + $options['dropDups'] = (bool) $mapping['drop-dups']; } if (isset($mapping['index-name'])) { $options['name'] = (string) $mapping['index-name']; } if (isset($mapping['sparse'])) { - $options['sparse'] = (boolean) $mapping['sparse']; + $options['sparse'] = (bool) $mapping['sparse']; } if (isset($mapping['unique'])) { - $options['unique'] = (boolean) $mapping['unique']; + $options['unique'] = (bool) $mapping['unique']; } $class->addIndex($keys, $options); @@ -222,15 +236,15 @@ private function addFieldMapping(ClassMetadata $class, $mapping) private function addEmbedMapping(ClassMetadata $class, $embed, $type) { $attributes = $embed->attributes(); - $defaultStrategy = $type == 'one' ? ClassMetadata::STORAGE_STRATEGY_SET : CollectionHelper::DEFAULT_STRATEGY; - $mapping = array( + $defaultStrategy = $type === 'one' ? ClassMetadata::STORAGE_STRATEGY_SET : CollectionHelper::DEFAULT_STRATEGY; + $mapping = [ 'type' => $type, 'embedded' => true, 'targetDocument' => isset($attributes['target-document']) ? (string) $attributes['target-document'] : null, 'collectionClass' => isset($attributes['collection-class']) ? (string) $attributes['collection-class'] : null, 'name' => (string) $attributes['field'], 'strategy' => (string) ($attributes['strategy'] ?? $defaultStrategy), - ); + ]; if (isset($attributes['fieldName'])) { $mapping['fieldName'] = (string) $attributes['fieldName']; } @@ -248,7 +262,7 @@ private function addEmbedMapping(ClassMetadata $class, $embed, $type) $mapping['defaultDiscriminatorValue'] = (string) $embed->{'default-discriminator-value'}['value']; } if (isset($attributes['not-saved'])) { - $mapping['notSaved'] = ('true' === (string) $attributes['not-saved']); + $mapping['notSaved'] = ((string) $attributes['not-saved'] === 'true'); } if (isset($attributes['also-load'])) { $mapping['alsoLoadFields'] = explode(',', $attributes['also-load']); @@ -259,14 +273,14 @@ private function addEmbedMapping(ClassMetadata $class, $embed, $type) private function addReferenceMapping(ClassMetadata $class, $reference, $type) { $cascade = array_keys((array) $reference->cascade); - if (1 === count($cascade)) { + if (count($cascade) === 1) { $cascade = current($cascade) ?: next($cascade); } $attributes = $reference->attributes(); - $defaultStrategy = $type == 'one' ? ClassMetadata::STORAGE_STRATEGY_SET : CollectionHelper::DEFAULT_STRATEGY; - $mapping = array( + $defaultStrategy = $type === 'one' ? ClassMetadata::STORAGE_STRATEGY_SET : CollectionHelper::DEFAULT_STRATEGY; + $mapping = [ 'cascade' => $cascade, - 'orphanRemoval' => isset($attributes['orphan-removal']) ? ('true' === (string) $attributes['orphan-removal']) : false, + 'orphanRemoval' => isset($attributes['orphan-removal']) ? ((string) $attributes['orphan-removal'] === 'true') : false, 'type' => $type, 'reference' => true, 'storeAs' => (string) ($attributes['store-as'] ?? ClassMetadata::REFERENCE_STORE_AS_DB_REF), @@ -277,10 +291,10 @@ private function addReferenceMapping(ClassMetadata $class, $reference, $type) 'inversedBy' => isset($attributes['inversed-by']) ? (string) $attributes['inversed-by'] : null, 'mappedBy' => isset($attributes['mapped-by']) ? (string) $attributes['mapped-by'] : null, 'repositoryMethod' => isset($attributes['repository-method']) ? (string) $attributes['repository-method'] : null, - 'limit' => isset($attributes['limit']) ? (integer) $attributes['limit'] : null, - 'skip' => isset($attributes['skip']) ? (integer) $attributes['skip'] : null, + 'limit' => isset($attributes['limit']) ? (int) $attributes['limit'] : null, + 'skip' => isset($attributes['skip']) ? (int) $attributes['skip'] : null, 'prime' => [], - ); + ]; if (isset($attributes['fieldName'])) { $mapping['fieldName'] = (string) $attributes['fieldName']; @@ -311,7 +325,7 @@ private function addReferenceMapping(ClassMetadata $class, $reference, $type) } } if (isset($attributes['not-saved'])) { - $mapping['notSaved'] = ('true' === (string) $attributes['not-saved']); + $mapping['notSaved'] = ((string) $attributes['not-saved'] === 'true'); } if (isset($attributes['also-load'])) { $mapping['alsoLoadFields'] = explode(',', $attributes['also-load']); @@ -330,28 +344,28 @@ private function addIndex(ClassMetadata $class, \SimpleXmlElement $xmlIndex) { $attributes = $xmlIndex->attributes(); - $keys = array(); + $keys = []; foreach ($xmlIndex->{'key'} as $key) { $keys[(string) $key['name']] = (string) ($key['order'] ?? 'asc'); } - $options = array(); + $options = []; if (isset($attributes['background'])) { - $options['background'] = ('true' === (string) $attributes['background']); + $options['background'] = ((string) $attributes['background'] === 'true'); } if (isset($attributes['drop-dups'])) { - $options['dropDups'] = ('true' === (string) $attributes['drop-dups']); + $options['dropDups'] = ((string) $attributes['drop-dups'] === 'true'); } if (isset($attributes['name'])) { $options['name'] = (string) $attributes['name']; } if (isset($attributes['sparse'])) { - $options['sparse'] = ('true' === (string) $attributes['sparse']); + $options['sparse'] = ((string) $attributes['sparse'] === 'true'); } if (isset($attributes['unique'])) { - $options['unique'] = ('true' === (string) $attributes['unique']); + $options['unique'] = ((string) $attributes['unique'] === 'true'); } if (isset($xmlIndex->{'option'})) { @@ -362,7 +376,7 @@ private function addIndex(ClassMetadata $class, \SimpleXmlElement $xmlIndex) } elseif ($value === 'false') { $value = false; } elseif (is_numeric($value)) { - $value = preg_match('/^[-]?\d+$/', $value) ? (integer) $value : (float) $value; + $value = preg_match('/^[-]?\d+$/', $value) ? (int) $value : (float) $value; } $options[(string) $option['name']] = $value; } @@ -422,7 +436,7 @@ private function getPartialFilterExpression(\SimpleXMLElement $fields) } elseif ($value === 'false') { $value = false; } elseif (is_numeric($value)) { - $value = preg_match('/^[-]?\d+$/', $value) ? (integer) $value : (float) $value; + $value = preg_match('/^[-]?\d+$/', $value) ? (int) $value : (float) $value; } $partialFilterExpression[(string) $field['name']] = $operator ? ['$' . $operator => $value] : $value; @@ -435,14 +449,14 @@ private function setShardKey(ClassMetadata $class, \SimpleXmlElement $xmlShardke { $attributes = $xmlShardkey->attributes(); - $keys = array(); - $options = array(); + $keys = []; + $options = []; foreach ($xmlShardkey->{'key'} as $key) { $keys[(string) $key['name']] = (string) ($key['order'] ?? 'asc'); } if (isset($attributes['unique'])) { - $options['unique'] = ('true' === (string) $attributes['unique']); + $options['unique'] = ((string) $attributes['unique'] === 'true'); } if (isset($attributes['numInitialChunks'])) { @@ -457,7 +471,7 @@ private function setShardKey(ClassMetadata $class, \SimpleXmlElement $xmlShardke } elseif ($value === 'false') { $value = false; } elseif (is_numeric($value)) { - $value = preg_match('/^[-]?\d+$/', $value) ? (integer) $value : (float) $value; + $value = preg_match('/^[-]?\d+$/', $value) ? (int) $value : (float) $value; } $options[(string) $option['name']] = $value; } @@ -495,10 +509,10 @@ private function transformReadPreference($xmlReadPreference) */ protected function loadMappingFile($file) { - $result = array(); + $result = []; $xmlElement = simplexml_load_file($file); - foreach (array('document', 'embedded-document', 'mapped-superclass', 'query-result-document') as $type) { + foreach (['document', 'embedded-document', 'mapped-superclass', 'query-result-document'] as $type) { if (isset($xmlElement->$type)) { foreach ($xmlElement->$type as $documentElement) { $documentName = (string) $documentElement['name']; diff --git a/lib/Doctrine/ODM/MongoDB/Mapping/MappingException.php b/lib/Doctrine/ODM/MongoDB/Mapping/MappingException.php index 7b53880084..e15d0756a9 100644 --- a/lib/Doctrine/ODM/MongoDB/Mapping/MappingException.php +++ b/lib/Doctrine/ODM/MongoDB/Mapping/MappingException.php @@ -1,5 +1,7 @@ collectionDir) { + if (! $this->collectionDir) { throw PersistentCollectionException::directoryRequired(); } - if ( ! $this->collectionNamespace) { + if (! $this->collectionNamespace) { throw PersistentCollectionException::namespaceRequired(); } $collClassName = str_replace('\\', '', $collectionClass) . 'Persistent'; $className = $this->collectionNamespace . '\\' . $collClassName; - if ( ! class_exists($className, false)) { + if (! class_exists($className, false)) { $fileName = $this->collectionDir . DIRECTORY_SEPARATOR . $collClassName . '.php'; switch ($autoGenerate) { case Configuration::AUTOGENERATE_NEVER: @@ -74,7 +96,7 @@ public function loadClass($collectionClass, $autoGenerate) break; case Configuration::AUTOGENERATE_FILE_NOT_EXISTS: - if ( ! file_exists($fileName)) { + if (! file_exists($fileName)) { $this->generateCollectionClass($collectionClass, $className, $fileName); } require $fileName; @@ -129,8 +151,7 @@ public function __construct(BaseCollection \$coll, DocumentManager \$dm, UnitOfW $rc = new \ReflectionClass($for); $rt = new \ReflectionClass('Doctrine\\ODM\\MongoDB\\PersistentCollection\\PersistentCollectionTrait'); foreach ($rc->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { - if ( - $rt->hasMethod($method->name) || + if ($rt->hasMethod($method->name) || $method->isConstructor() || $method->isFinal() || $method->isStatic() @@ -142,17 +163,17 @@ public function __construct(BaseCollection \$coll, DocumentManager \$dm, UnitOfW $code .= "}\n"; if ($fileName === false) { - if ( ! class_exists($targetFqcn)) { + if (! class_exists($targetFqcn)) { eval(substr($code, 5)); } } else { $parentDirectory = dirname($fileName); - if ( ! is_dir($parentDirectory) && (false === @mkdir($parentDirectory, 0775, true))) { + if (! is_dir($parentDirectory) && (@mkdir($parentDirectory, 0775, true) === false)) { throw PersistentCollectionException::directoryNotWritable(); } - if ( ! is_writable($parentDirectory)) { + if (! is_writable($parentDirectory)) { throw PersistentCollectionException::directoryNotWritable(); } @@ -186,14 +207,13 @@ public function {$method->name}($parametersString){$this->getMethodReturnType($m } /** - * @param \ReflectionMethod $method * * @return string */ private function buildParametersString(\ReflectionMethod $method) { $parameters = $method->getParameters(); - $parameterDefinitions = array(); + $parameterDefinitions = []; /* @var $param \ReflectionParameter */ foreach ($parameters as $param) { @@ -227,7 +247,6 @@ private function buildParametersString(\ReflectionMethod $method) } /** - * @param \ReflectionParameter $parameter * * @return string|null */ @@ -282,7 +301,6 @@ function (\ReflectionParameter $parameter) { } /** - * @param \ReflectionMethod $method * * @return string * @@ -290,16 +308,13 @@ function (\ReflectionParameter $parameter) { */ private function getMethodReturnType(\ReflectionMethod $method) { - if ( ! method_exists($method, 'hasReturnType') || ! $method->hasReturnType()) { + if (! method_exists($method, 'hasReturnType') || ! $method->hasReturnType()) { return ''; } return ': ' . $this->formatType($method->getReturnType(), $method); } /** - * @param \ReflectionType $type - * @param \ReflectionMethod $method - * @param \ReflectionParameter|null $parameter * * @return string * @@ -308,18 +323,18 @@ private function getMethodReturnType(\ReflectionMethod $method) private function formatType( \ReflectionType $type, \ReflectionMethod $method, - \ReflectionParameter $parameter = null + ?\ReflectionParameter $parameter = null ) { $name = method_exists($type, 'getName') ? $type->getName() : (string) $type; $nameLower = strtolower($name); - if ('self' === $nameLower) { + if ($nameLower === 'self') { $name = $method->getDeclaringClass()->getName(); } - if ('parent' === $nameLower) { + if ($nameLower === 'parent') { $name = $method->getDeclaringClass()->getParentClass()->getName(); } - if ( ! $type->isBuiltin() && ! class_exists($name) && ! interface_exists($name)) { - if (null !== $parameter) { + if (! $type->isBuiltin() && ! class_exists($name) && ! interface_exists($name)) { + if ($parameter !== null) { throw PersistentCollectionException::invalidParameterTypeHint( $method->getDeclaringClass()->getName(), $method->getName(), @@ -331,11 +346,11 @@ private function formatType( $method->getName() ); } - if ( ! $type->isBuiltin()) { + if (! $type->isBuiltin()) { $name = '\\' . $name; } if ($type->allowsNull() - && (null === $parameter || ! $parameter->isDefaultValueAvailable() || null !== $parameter->getDefaultValue()) + && ($parameter === null || ! $parameter->isDefaultValueAvailable() || $parameter->getDefaultValue() !== null) ) { $name = '?' . $name; } diff --git a/lib/Doctrine/ODM/MongoDB/PersistentCollection/PersistentCollectionException.php b/lib/Doctrine/ODM/MongoDB/PersistentCollection/PersistentCollectionException.php index bcdf2e1047..aea90240e2 100644 --- a/lib/Doctrine/ODM/MongoDB/PersistentCollection/PersistentCollectionException.php +++ b/lib/Doctrine/ODM/MongoDB/PersistentCollection/PersistentCollectionException.php @@ -1,13 +1,15 @@ isDirty) { // Remember any NEW objects added through add() @@ -137,7 +144,7 @@ public function initialize() $this->uow->loadCollection($this); $this->takeSnapshot(); - $this->mongoData = array(); + $this->mongoData = []; // Reattach any NEW objects added through add() if ($newObjects) { @@ -216,7 +223,7 @@ public function takeSnapshot() /** {@inheritdoc} */ public function clearSnapshot() { - $this->snapshot = array(); + $this->snapshot = []; $this->isDirty = $this->coll->count() ? true : false; } @@ -232,7 +239,9 @@ public function getDeleteDiff() return array_udiff_assoc( $this->snapshot, $this->coll->toArray(), - function ($a, $b) { return $a === $b ? 0 : 1; } + function ($a, $b) { + return $a === $b ? 0 : 1; + } ); } @@ -257,7 +266,9 @@ public function getInsertDiff() return array_udiff_assoc( $this->coll->toArray(), $this->snapshot, - function ($a, $b) { return $a === $b ? 0 : 1; } + function ($a, $b) { + return $a === $b ? 0 : 1; + } ); } @@ -345,7 +356,7 @@ public function removeElement($element) $this->initialize(); $removed = $this->coll->removeElement($element); - if ( ! $removed) { + if (! $removed) { return $removed; } @@ -522,11 +533,11 @@ public function clear() } } - $this->mongoData = array(); + $this->mongoData = []; $this->coll->clear(); // Nothing to do for inverse-side collections - if ( ! $this->mapping['isOwningSide']) { + if (! $this->mapping['isOwningSide']) { return; } @@ -558,7 +569,7 @@ public function slice($offset, $length = null) */ public function __sleep() { - return array('coll', 'initialized'); + return ['coll', 'initialized']; } /* ArrayAccess implementation */ @@ -587,7 +598,7 @@ public function offsetGet($offset) */ public function offsetSet($offset, $value) { - if ( ! isset($offset)) { + if (! isset($offset)) { return $this->doAdd($value, true); } @@ -651,7 +662,7 @@ public function __clone() $this->initialize(); $this->owner = null; - $this->snapshot = array(); + $this->snapshot = []; $this->changed(); } @@ -660,7 +671,7 @@ public function __clone() * Actual logic for adding an element to the collection. * * @param mixed $value - * @param bool $arrayAccess + * @param bool $arrayAccess * @return bool */ private function doAdd($value, $arrayAccess) @@ -686,7 +697,7 @@ private function doAdd($value, $arrayAccess) * Actual logic for removing element by its key. * * @param mixed $offset - * @param bool $arrayAccess + * @param bool $arrayAccess * @return mixed|void */ private function doRemove($offset, $arrayAccess) @@ -694,7 +705,7 @@ private function doRemove($offset, $arrayAccess) $this->initialize(); $removed = $arrayAccess ? $this->coll->offsetUnset($offset) : $this->coll->remove($offset); - if ( ! $removed && ! $arrayAccess) { + if (! $removed && ! $arrayAccess) { return $removed; } @@ -708,8 +719,7 @@ private function doRemove($offset, $arrayAccess) * * @param mixed $offset * @param mixed $value - * @param bool $arrayAccess - * @return bool + * @param bool $arrayAccess */ private function doSet($offset, $value, $arrayAccess) { @@ -729,7 +739,7 @@ private function doSet($offset, $value, $arrayAccess) * Embedded documents are automatically considered as "orphan removal enabled" because they might have references * that require to trigger cascade remove operations. * - * @return boolean + * @return bool */ private function isOrphanRemovalEnabled() { diff --git a/lib/Doctrine/ODM/MongoDB/Persisters/CollectionPersister.php b/lib/Doctrine/ODM/MongoDB/Persisters/CollectionPersister.php index d9ee1c982e..b88ae37baa 100644 --- a/lib/Doctrine/ODM/MongoDB/Persisters/CollectionPersister.php +++ b/lib/Doctrine/ODM/MongoDB/Persisters/CollectionPersister.php @@ -1,5 +1,7 @@ getPathAndParent($coll); - $query = array('$unset' => array($propertyPath => true)); + $query = ['$unset' => [$propertyPath => true]]; $this->executeQuery($parent, $query, $options); } @@ -82,7 +84,6 @@ public function delete(PersistentCollectionInterface $coll, array $options) * Updates a PersistentCollection instance deleting removed rows and * inserting new rows. * - * @param PersistentCollectionInterface $coll * @param array $options */ public function update(PersistentCollectionInterface $coll, array $options) @@ -123,7 +124,6 @@ public function update(PersistentCollectionInterface $coll, array $options) * set as a BSON array, which means the collection elements will be * reindexed numerically before storage. * - * @param PersistentCollectionInterface $coll * @param array $options */ private function setCollection(PersistentCollectionInterface $coll, array $options) @@ -132,7 +132,7 @@ private function setCollection(PersistentCollectionInterface $coll, array $optio $coll->initialize(); $mapping = $coll->getMapping(); $setData = $this->pb->prepareAssociatedCollectionValue($coll, CollectionHelper::usesSet($mapping['strategy'])); - $query = array('$set' => array($propertyPath => $setData)); + $query = ['$set' => [$propertyPath => $setData]]; $this->executeQuery($parent, $query, $options); } @@ -142,7 +142,6 @@ private function setCollection(PersistentCollectionInterface $coll, array $optio * This method is intended to be used with the "pushAll" and "addToSet" * strategies. * - * @param PersistentCollectionInterface $coll * @param array $options */ private function deleteElements(PersistentCollectionInterface $coll, array $options) @@ -155,7 +154,7 @@ private function deleteElements(PersistentCollectionInterface $coll, array $opti list($propertyPath, $parent) = $this->getPathAndParent($coll); - $query = array('$unset' => array()); + $query = ['$unset' => []]; foreach ($deleteDiff as $key => $document) { $query['$unset'][$propertyPath . '.' . $key] = true; @@ -169,7 +168,7 @@ private function deleteElements(PersistentCollectionInterface $coll, array $opti * in the element being left in the array as null so we have to pull * null values. */ - $this->executeQuery($parent, array('$pull' => array($propertyPath => null)), $options); + $this->executeQuery($parent, ['$pull' => [$propertyPath => null]], $options); } /** @@ -178,7 +177,6 @@ private function deleteElements(PersistentCollectionInterface $coll, array $opti * This method is intended to be used with the "pushAll" and "addToSet" * strategies. * - * @param PersistentCollectionInterface $coll * @param array $options */ private function insertElements(PersistentCollectionInterface $coll, array $options) @@ -207,8 +205,12 @@ private function insertElements(PersistentCollectionInterface $coll, array $opti list($propertyPath, $parent) = $this->getPathAndParent($coll); $callback = isset($mapping['embedded']) - ? function($v) use ($mapping) { return $this->pb->prepareEmbeddedDocumentValue($mapping, $v); } - : function($v) use ($mapping) { return $this->pb->prepareReferencedDocumentValue($mapping, $v); }; + ? function ($v) use ($mapping) { + return $this->pb->prepareEmbeddedDocumentValue($mapping, $v); + } + : function ($v) use ($mapping) { + return $this->pb->prepareReferencedDocumentValue($mapping, $v); + }; $value = array_values(array_map($callback, $insertDiff)); @@ -228,15 +230,14 @@ private function insertElements(PersistentCollectionInterface $coll, array $opti * list($path, $parent) = $this->getPathAndParent($coll) * * - * @param PersistentCollectionInterface $coll * @return array $pathAndParent */ private function getPathAndParent(PersistentCollectionInterface $coll) { $mapping = $coll->getMapping(); - $fields = array(); + $fields = []; $parent = $coll->getOwner(); - while (null !== ($association = $this->uow->getParentAssociation($parent))) { + while (($association = $this->uow->getParentAssociation($parent)) !== null) { list($m, $owner, $field) = $association; if (isset($m['reference'])) { break; @@ -249,22 +250,22 @@ private function getPathAndParent(PersistentCollectionInterface $coll) if ($propertyPath) { $path = $propertyPath . '.' . $path; } - return array($path, $parent); + return [$path, $parent]; } /** * Executes a query updating the given document. * * @param object $document - * @param array $newObj - * @param array $options + * @param array $newObj + * @param array $options */ private function executeQuery($document, array $newObj, array $options) { $className = get_class($document); $class = $this->dm->getClassMetadata($className); $id = $class->getDatabaseIdentifierValue($this->uow->getDocumentIdentifier($document)); - $query = array('_id' => $id); + $query = ['_id' => $id]; if ($class->isVersioned) { $query[$class->fieldMappings[$class->versionField]['name']] = $class->reflFields[$class->versionField]->getValue($document); } diff --git a/lib/Doctrine/ODM/MongoDB/Persisters/DocumentPersister.php b/lib/Doctrine/ODM/MongoDB/Persisters/DocumentPersister.php index 8cf54e94ef..c394b60f86 100644 --- a/lib/Doctrine/ODM/MongoDB/Persisters/DocumentPersister.php +++ b/lib/Doctrine/ODM/MongoDB/Persisters/DocumentPersister.php @@ -1,17 +1,17 @@ pb = $pb; $this->dm = $dm; @@ -180,7 +197,7 @@ public function getUpserts() /** * @param object $document - * @return boolean + * @return bool */ public function isQueuedForUpsert($document) { @@ -218,13 +235,13 @@ public function getClassMetadata() * * @param array $options Options for batchInsert() and update() driver methods */ - public function executeInserts(array $options = array()) + public function executeInserts(array $options = []) { - if ( ! $this->queuedInserts) { + if (! $this->queuedInserts) { return; } - $inserts = array(); + $inserts = []; $options = $this->getWriteOptions($options); foreach ($this->queuedInserts as $oid => $document) { $data = $this->pb->prepareInsertData($document); @@ -251,7 +268,7 @@ public function executeInserts(array $options = array()) try { $this->collection->insertMany($inserts, $options); } catch (DriverException $e) { - $this->queuedInserts = array(); + $this->queuedInserts = []; throw $e; } } @@ -264,7 +281,7 @@ public function executeInserts(array $options = array()) $this->handleCollections($document, $options); } - $this->queuedInserts = array(); + $this->queuedInserts = []; } /** @@ -276,9 +293,9 @@ public function executeInserts(array $options = array()) * * @param array $options Options for batchInsert() and update() driver methods */ - public function executeUpserts(array $options = array()) + public function executeUpserts(array $options = []) { - if ( ! $this->queuedUpserts) { + if (! $this->queuedUpserts) { return; } @@ -347,7 +364,7 @@ private function executeUpsert($document, array $options) */ if (empty($data)) { $retry = true; - $data = array('$set' => array('_id' => $criteria['_id'])); + $data = ['$set' => ['_id' => $criteria['_id']]]; } try { @@ -359,17 +376,17 @@ private function executeUpsert($document, array $options) } } - $this->collection->updateOne($criteria, array('$set' => new \stdClass), $options); + $this->collection->updateOne($criteria, ['$set' => new \stdClass()], $options); } /** * Updates the already persisted document if it has any new changesets. * * @param object $document - * @param array $options Array of options to be used with update() - * @throws \Doctrine\ODM\MongoDB\LockException + * @param array $options Array of options to be used with update() + * @throws LockException */ - public function update($document, array $options = array()) + public function update($document, array $options = []) { $update = $this->pb->prepareUpdateData($document); @@ -383,7 +400,6 @@ public function update($document, array $options = array()) unset($update['$set']); } - // Include versioning logic to set the new version value in the database // and to ensure the version has not changed since this document object instance // was fetched from the database @@ -402,16 +418,16 @@ public function update($document, array $options = array()) } } - if ( ! empty($update)) { + if (! empty($update)) { // Include locking logic so that if the document object in memory is currently // locked then it will remove it, otherwise it ensures the document is not locked. if ($this->class->isLockable) { $isLocked = $this->class->reflFields[$this->class->lockField]->getValue($document); $lockMapping = $this->class->fieldMappings[$this->class->lockField]; if ($isLocked) { - $update['$unset'] = array($lockMapping['name'] => true); + $update['$unset'] = [$lockMapping['name'] => true]; } else { - $query[$lockMapping['name']] = array('$exists' => false); + $query[$lockMapping['name']] = ['$exists' => false]; } } @@ -433,15 +449,15 @@ public function update($document, array $options = array()) * Removes document from mongo * * @param mixed $document - * @param array $options Array of options to be used with remove() - * @throws \Doctrine\ODM\MongoDB\LockException + * @param array $options Array of options to be used with remove() + * @throws LockException */ - public function delete($document, array $options = array()) + public function delete($document, array $options = []) { $query = $this->getQueryForDocument($document); if ($this->class->isLockable) { - $query[$this->class->lockField] = array('$exists' => false); + $query[$this->class->lockField] = ['$exists' => false]; } $options = $this->getWriteOptions($options); @@ -472,20 +488,20 @@ public function refresh($document) * If a scalar or MongoDB\BSON\ObjectId is provided for $criteria, it will * be used to match an _id value. * - * @param mixed $criteria Query criteria - * @param object $document Document to load the data into. If not specified, a new document is created. - * @param array $hints Hints for document creation - * @param integer $lockMode - * @param array $sort Sort array for Cursor::sort() - * @throws \Doctrine\ODM\MongoDB\LockException + * @param mixed $criteria Query criteria + * @param object $document Document to load the data into. If not specified, a new document is created. + * @param array $hints Hints for document creation + * @param int $lockMode + * @param array $sort Sort array for Cursor::sort() + * @throws LockException * @return object|null The loaded and managed document instance or null if no document was found * @todo Check identity map? loadById method? Try to guess whether $criteria is the id? */ - public function load($criteria, $document = null, array $hints = array(), $lockMode = 0, array $sort = null) + public function load($criteria, $document = null, array $hints = [], $lockMode = 0, ?array $sort = null) { // TODO: remove this - if ($criteria === null || is_scalar($criteria) || $criteria instanceof \MongoDB\BSON\ObjectId) { - $criteria = array('_id' => $criteria); + if ($criteria === null || is_scalar($criteria) || $criteria instanceof ObjectId) { + $criteria = ['_id' => $criteria]; } $criteria = $this->prepareQueryOrNewObj($criteria); @@ -493,7 +509,7 @@ public function load($criteria, $document = null, array $hints = array(), $lockM $criteria = $this->addFilterToPreparedQuery($criteria); $options = []; - if (null !== $sort) { + if ($sort !== null) { $options['sort'] = $this->prepareSort($sort); } $result = $this->collection->findOne($criteria, $options); @@ -511,28 +527,28 @@ public function load($criteria, $document = null, array $hints = array(), $lockM /** * Finds documents by a set of criteria. * - * @param array $criteria Query criteria - * @param array $sort Sort array for Cursor::sort() - * @param integer|null $limit Limit for Cursor::limit() - * @param integer|null $skip Skip for Cursor::skip() + * @param array $criteria Query criteria + * @param array $sort Sort array for Cursor::sort() + * @param int|null $limit Limit for Cursor::limit() + * @param int|null $skip Skip for Cursor::skip() * @return Iterator */ - public function loadAll(array $criteria = array(), array $sort = null, $limit = null, $skip = null) + public function loadAll(array $criteria = [], ?array $sort = null, $limit = null, $skip = null) { $criteria = $this->prepareQueryOrNewObj($criteria); $criteria = $this->addDiscriminatorToPreparedQuery($criteria); $criteria = $this->addFilterToPreparedQuery($criteria); $options = []; - if (null !== $sort) { + if ($sort !== null) { $options['sort'] = $this->prepareSort($sort); } - if (null !== $limit) { + if ($limit !== null) { $options['limit'] = $limit; } - if (null !== $skip) { + if ($skip !== null) { $options['skip'] = $skip; } @@ -550,15 +566,15 @@ public function loadAll(array $criteria = array(), array $sort = null, $limit = */ private function getShardKeyQuery($document) { - if ( ! $this->class->isSharded()) { - return array(); + if (! $this->class->isSharded()) { + return []; } $shardKey = $this->class->getShardKey(); $keys = array_keys($shardKey['keys']); $data = $this->uow->getDocumentActualData($document); - $shardKeyQueryPart = array(); + $shardKeyQueryPart = []; foreach ($keys as $key) { $mapping = $this->class->getFieldMappingByDbFieldName($key); $this->guardMissingShardKey($document, $key, $data); @@ -585,8 +601,6 @@ private function getShardKeyQuery($document) /** * Wraps the supplied base cursor in the corresponding ODM class. * - * @param Cursor $baseCursor - * @return Iterator */ private function wrapCursor(Cursor $baseCursor): Iterator { @@ -597,26 +611,26 @@ private function wrapCursor(Cursor $baseCursor): Iterator * Checks whether the given managed document exists in the database. * * @param object $document - * @return boolean TRUE if the document exists in the database, FALSE otherwise. + * @return bool TRUE if the document exists in the database, FALSE otherwise. */ public function exists($document) { $id = $this->class->getIdentifierObject($document); - return (boolean) $this->collection->findOne(array('_id' => $id), array('_id')); + return (bool) $this->collection->findOne(['_id' => $id], ['_id']); } /** * Locks document by storing the lock mode on the mapped lock field. * * @param object $document - * @param int $lockMode + * @param int $lockMode */ public function lock($document, $lockMode) { $id = $this->uow->getDocumentIdentifier($document); - $criteria = array('_id' => $this->class->getDatabaseIdentifierValue($id)); + $criteria = ['_id' => $this->class->getDatabaseIdentifierValue($id)]; $lockMapping = $this->class->fieldMappings[$this->class->lockField]; - $this->collection->updateOne($criteria, array('$set' => array($lockMapping['name'] => $lockMode))); + $this->collection->updateOne($criteria, ['$set' => [$lockMapping['name'] => $lockMode]]); $this->class->reflFields[$this->class->lockField]->setValue($document, $lockMode); } @@ -628,21 +642,21 @@ public function lock($document, $lockMode) public function unlock($document) { $id = $this->uow->getDocumentIdentifier($document); - $criteria = array('_id' => $this->class->getDatabaseIdentifierValue($id)); + $criteria = ['_id' => $this->class->getDatabaseIdentifierValue($id)]; $lockMapping = $this->class->fieldMappings[$this->class->lockField]; - $this->collection->updateOne($criteria, array('$unset' => array($lockMapping['name'] => true))); + $this->collection->updateOne($criteria, ['$unset' => [$lockMapping['name'] => true]]); $this->class->reflFields[$this->class->lockField]->setValue($document, null); } /** * Creates or fills a single document object from an query result. * - * @param object $result The query result. + * @param object $result The query result. * @param object $document The document object to fill, if any. - * @param array $hints Hints for document creation. + * @param array $hints Hints for document creation. * @return object The filled and managed document object or NULL, if the query result is empty. */ - private function createDocument($result, $document = null, array $hints = array()) + private function createDocument($result, $document = null, array $hints = []) { if ($result === null) { return null; @@ -660,7 +674,6 @@ private function createDocument($result, $document = null, array $hints = array( /** * Loads a PersistentCollection data. Used in the initialize() method. * - * @param PersistentCollectionInterface $collection */ public function loadCollection(PersistentCollectionInterface $collection) { @@ -698,7 +711,7 @@ private function loadEmbedManyCollection(PersistentCollectionInterface $collecti $this->uow->setParentAssociation($embeddedDocumentObject, $mapping, $owner, $mapping['name'] . '.' . $key); $data = $this->hydratorFactory->hydrate($embeddedDocumentObject, $embeddedDocument, $collection->getHints()); - $id = $embeddedMetadata->identifier && $data[$embeddedMetadata->identifier] ?? null; + $id = $data[$embeddedMetadata->identifier] ?? null; if (empty($collection->getHints()[Query::HINT_READ_ONLY])) { $this->uow->registerManaged($embeddedDocumentObject, $id, $data); @@ -716,7 +729,7 @@ private function loadReferenceManyCollectionOwningSide(PersistentCollectionInter { $hints = $collection->getHints(); $mapping = $collection->getMapping(); - $groupedIds = array(); + $groupedIds = []; $sorted = isset($mapping['sort']) && $mapping['sort']; @@ -729,7 +742,7 @@ private function loadReferenceManyCollectionOwningSide(PersistentCollectionInter $reference = $this->dm->getReference($className, $id); // no custom sort so add the references right now in the order they are embedded - if ( ! $sorted) { + if (! $sorted) { if (CollectionHelper::isHash($mapping['strategy'])) { $collection->set($key, $reference); } else { @@ -746,9 +759,9 @@ private function loadReferenceManyCollectionOwningSide(PersistentCollectionInter $class = $this->dm->getClassMetadata($className); $mongoCollection = $this->dm->getDocumentCollection($className); $criteria = $this->cm->merge( - array('_id' => array('$in' => array_values($ids))), + ['_id' => ['$in' => array_values($ids)]], $this->dm->getFilterCollection()->getFilterCriteria($class), - $mapping['criteria'] ?? array() + $mapping['criteria'] ?? [] ); $criteria = $this->uow->getDocumentPersister($className)->prepareQueryOrNewObj($criteria); @@ -762,7 +775,7 @@ private function loadReferenceManyCollectionOwningSide(PersistentCollectionInter if (isset($mapping['skip'])) { $options['skip'] = $mapping['skip']; } - if ( ! empty($hints[Query::HINT_READ_PREFERENCE])) { + if (! empty($hints[Query::HINT_READ_PREFERENCE])) { $options['readPreference'] = $hints[Query::HINT_READ_PREFERENCE]; } @@ -792,7 +805,6 @@ private function loadReferenceManyCollectionInverseSide(PersistentCollectionInte } /** - * @param PersistentCollectionInterface $collection * * @return Query */ @@ -803,13 +815,13 @@ public function createReferenceManyInverseSideQuery(PersistentCollectionInterfac $owner = $collection->getOwner(); $ownerClass = $this->dm->getClassMetadata(get_class($owner)); $targetClass = $this->dm->getClassMetadata($mapping['targetDocument']); - $mappedByMapping = $targetClass->fieldMappings[$mapping['mappedBy']] ?? array(); + $mappedByMapping = $targetClass->fieldMappings[$mapping['mappedBy']] ?? []; $mappedByFieldName = ClassMetadata::getReferenceFieldName($mappedByMapping['storeAs'] ?? ClassMetadata::REFERENCE_STORE_AS_DB_REF, $mapping['mappedBy']); $criteria = $this->cm->merge( - array($mappedByFieldName => $ownerClass->getIdentifierObject($owner)), + [$mappedByFieldName => $ownerClass->getIdentifierObject($owner)], $this->dm->getFilterCollection()->getFilterCriteria($targetClass), - $mapping['criteria'] ?? array() + $mapping['criteria'] ?? [] ); $criteria = $this->uow->getDocumentPersister($mapping['targetDocument'])->prepareQueryOrNewObj($criteria); $qb = $this->dm->createQueryBuilder($mapping['targetDocument']) @@ -825,7 +837,7 @@ public function createReferenceManyInverseSideQuery(PersistentCollectionInterfac $qb->skip($mapping['skip']); } - if ( ! empty($hints[Query::HINT_READ_PREFERENCE])) { + if (! empty($hints[Query::HINT_READ_PREFERENCE])) { $qb->setReadPreference($hints[Query::HINT_READ_PREFERENCE]); } @@ -851,7 +863,6 @@ private function loadReferenceManyWithRepositoryMethod(PersistentCollectionInter } /** - * @param PersistentCollectionInterface $collection * * @return \Iterator */ @@ -862,11 +873,11 @@ public function createReferenceManyWithRepositoryMethodCursor(PersistentCollecti $cursor = $this->dm->getRepository($mapping['targetDocument']) ->$repositoryMethod($collection->getOwner()); - if ( ! $cursor instanceof Iterator) { + if (! $cursor instanceof Iterator) { throw new \BadMethodCallException("Expected repository method {$repositoryMethod} to return an iterable object"); } - if (!empty($mapping['prime'])) { + if (! empty($mapping['prime'])) { $referencePrimer = new ReferencePrimer($this->dm, $this->dm->getUnitOfWork()); $primers = array_combine($mapping['prime'], array_fill(0, count($mapping['prime']), true)); $class = $this->dm->getClassMetadata($mapping['targetDocument']); @@ -886,7 +897,7 @@ public function createReferenceManyWithRepositoryMethodCursor(PersistentCollecti */ public function prepareProjection(array $fields) { - $preparedFields = array(); + $preparedFields = []; foreach ($fields as $key => $value) { $preparedFields[$this->prepareFieldName($key)] = $value; @@ -901,7 +912,7 @@ public function prepareProjection(array $fields) */ private function getSortDirection($sort) { - switch (strtolower($sort)) { + switch (strtolower((string) $sort)) { case 'desc': return -1; @@ -963,7 +974,7 @@ public function addDiscriminatorToPreparedQuery(array $preparedQuery) if (count($discriminatorValues) === 1) { $preparedQuery[$this->class->discriminatorField] = $discriminatorValues[0]; } else { - $preparedQuery[$this->class->discriminatorField] = array('$in' => $discriminatorValues); + $preparedQuery[$this->class->discriminatorField] = ['$in' => $discriminatorValues]; } } @@ -1001,16 +1012,16 @@ public function addFilterToPreparedQuery(array $preparedQuery) * PHP field names and types will be converted to those used by MongoDB. * * @param array $query - * @param bool $isNewObj + * @param bool $isNewObj * @return array */ public function prepareQueryOrNewObj(array $query, $isNewObj = false) { - $preparedQuery = array(); + $preparedQuery = []; foreach ($query as $key => $value) { // Recursively prepare logical query clauses - if (in_array($key, array('$and', '$or', '$nor')) && is_array($value)) { + if (in_array($key, ['$and', '$or', '$nor']) && is_array($value)) { foreach ($value as $k2 => $v2) { $preparedQuery[$key][$k2] = $this->prepareQueryOrNewObj($v2, $isNewObj); } @@ -1022,7 +1033,7 @@ public function prepareQueryOrNewObj(array $query, $isNewObj = false) continue; } - $preparedQueryElements = $this->prepareQueryElement($key, $value, null, true, $isNewObj); + $preparedQueryElements = $this->prepareQueryElement((string) $key, $value, null, true, $isNewObj); foreach ($preparedQueryElements as list($preparedKey, $preparedValue)) { $preparedQuery[$preparedKey] = is_array($preparedValue) ? array_map('\Doctrine\ODM\MongoDB\Types\Type::convertPHPToDatabaseValue', $preparedValue) @@ -1039,11 +1050,11 @@ public function prepareQueryOrNewObj(array $query, $isNewObj = false) * * It also handles converting $fieldName to the database name if they are different. * - * @param string $fieldName - * @param mixed $value + * @param string $fieldName + * @param mixed $value * @param ClassMetadata $class Defaults to $this->class - * @param bool $prepareValue Whether or not to prepare the value - * @param bool $inNewObj Whether or not newObj is being prepared + * @param bool $prepareValue Whether or not to prepare the value + * @param bool $inNewObj Whether or not newObj is being prepared * @return array An array of tuples containing prepared field names and values */ private function prepareQueryElement($fieldName, $value = null, $class = null, $prepareValue = true, $inNewObj = false) @@ -1057,17 +1068,17 @@ private function prepareQueryElement($fieldName, $value = null, $class = null, $ $mapping = $class->fieldMappings[$fieldName]; $fieldName = $mapping['name']; - if ( ! $prepareValue) { + if (! $prepareValue) { return [[$fieldName, $value]]; } // Prepare mapped, embedded objects - if ( ! empty($mapping['embedded']) && is_object($value) && + if (! empty($mapping['embedded']) && is_object($value) && ! $this->dm->getMetadataFactory()->isTransient(get_class($value))) { return [[$fieldName, $this->pb->prepareEmbeddedDocumentValue($mapping, $value)]]; } - if (! empty($mapping['reference']) && is_object($value) && ! ($value instanceof \MongoDB\BSON\ObjectId)) { + if (! empty($mapping['reference']) && is_object($value) && ! ($value instanceof ObjectId)) { try { return $this->prepareReference($fieldName, $value, $mapping, $inNewObj); } catch (MappingException $e) { @@ -1085,12 +1096,12 @@ private function prepareQueryElement($fieldName, $value = null, $class = null, $ // Additional preparation for one or more simple reference values $targetClass = $this->dm->getClassMetadata($mapping['targetDocument']); - if ( ! is_array($value)) { + if (! is_array($value)) { return [[$fieldName, $targetClass->getDatabaseIdentifierValue($value)]]; } // Objects without operators or with DBRef fields can be converted immediately - if ( ! $this->hasQueryOperators($value) || $this->hasDBRefFields($value)) { + if (! $this->hasQueryOperators($value) || $this->hasDBRefFields($value)) { return [[$fieldName, $targetClass->getDatabaseIdentifierValue($value)]]; } @@ -1101,16 +1112,16 @@ private function prepareQueryElement($fieldName, $value = null, $class = null, $ if (($class->hasField($fieldName) && $class->isIdentifier($fieldName)) || $fieldName === '_id') { $fieldName = '_id'; - if ( ! $prepareValue) { + if (! $prepareValue) { return [[$fieldName, $value]]; } - if ( ! is_array($value)) { + if (! is_array($value)) { return [[$fieldName, $class->getDatabaseIdentifierValue($value)]]; } // Objects without operators or with DBRef fields can be converted immediately - if ( ! $this->hasQueryOperators($value) || $this->hasDBRefFields($value)) { + if (! $this->hasQueryOperators($value) || $this->hasDBRefFields($value)) { return [[$fieldName, $class->getDatabaseIdentifierValue($value)]]; } @@ -1131,7 +1142,7 @@ private function prepareQueryElement($fieldName, $value = null, $class = null, $ $e = explode('.', $fieldName, 4); // No further processing for unmapped fields - if ( ! isset($class->fieldMappings[$e[0]])) { + if (! isset($class->fieldMappings[$e[0]])) { return [[$fieldName, $value]]; } @@ -1145,12 +1156,12 @@ private function prepareQueryElement($fieldName, $value = null, $class = null, $ return [[$fieldName, $value]]; } - if ($mapping['type'] == 'many' && CollectionHelper::isHash($mapping['strategy']) + if ($mapping['type'] === 'many' && CollectionHelper::isHash($mapping['strategy']) && isset($e[2])) { $objectProperty = $e[2]; $objectPropertyPrefix = $e[1] . '.'; $nextObjectProperty = implode('.', array_slice($e, 3)); - } elseif ($e[1] != '$') { + } elseif ($e[1] !== '$') { $fieldName = $e[0] . '.' . $e[1]; $objectProperty = $e[1]; $objectPropertyPrefix = ''; @@ -1167,9 +1178,9 @@ private function prepareQueryElement($fieldName, $value = null, $class = null, $ } // No further processing for fields without a targetDocument mapping - if ( ! isset($mapping['targetDocument'])) { + if (! isset($mapping['targetDocument'])) { if ($nextObjectProperty) { - $fieldName .= '.'.$nextObjectProperty; + $fieldName .= '.' . $nextObjectProperty; } return [[$fieldName, $value]]; @@ -1178,9 +1189,9 @@ private function prepareQueryElement($fieldName, $value = null, $class = null, $ $targetClass = $this->dm->getClassMetadata($mapping['targetDocument']); // No further processing for unmapped targetDocument fields - if ( ! $targetClass->hasField($objectProperty)) { + if (! $targetClass->hasField($objectProperty)) { if ($nextObjectProperty) { - $fieldName .= '.'.$nextObjectProperty; + $fieldName .= '.' . $nextObjectProperty; } return [[$fieldName, $value]]; @@ -1196,16 +1207,16 @@ private function prepareQueryElement($fieldName, $value = null, $class = null, $ // Process targetDocument identifier fields if ($objectPropertyIsId) { - if ( ! $prepareValue) { + if (! $prepareValue) { return [[$fieldName, $value]]; } - if ( ! is_array($value)) { + if (! is_array($value)) { return [[$fieldName, $targetClass->getDatabaseIdentifierValue($value)]]; } // Objects without operators or with DBRef fields can be converted immediately - if ( ! $this->hasQueryOperators($value) || $this->hasDBRefFields($value)) { + if (! $this->hasQueryOperators($value) || $this->hasDBRefFields($value)) { return [[$fieldName, $targetClass->getDatabaseIdentifierValue($value)]]; } @@ -1245,12 +1256,12 @@ private function prepareQueryExpression($expression, $class) { foreach ($expression as $k => $v) { // Ignore query operators whose arguments need no type conversion - if (in_array($k, array('$exists', '$type', '$mod', '$size'))) { + if (in_array($k, ['$exists', '$type', '$mod', '$size'])) { continue; } // Process query operators whose argument arrays need type conversion - if (in_array($k, array('$in', '$nin', '$all')) && is_array($v)) { + if (in_array($k, ['$in', '$nin', '$all']) && is_array($v)) { foreach ($v as $k2 => $v2) { $expression[$k][$k2] = $class->getDatabaseIdentifierValue($v2); } @@ -1278,11 +1289,11 @@ private function prepareQueryExpression($expression, $class) * $elemMatch criteria for matching a DBRef. * * @param mixed $value - * @return boolean + * @return bool */ private function hasDBRefFields($value) { - if ( ! is_array($value) && ! is_object($value)) { + if (! is_array($value) && ! is_object($value)) { return false; } @@ -1303,11 +1314,11 @@ private function hasDBRefFields($value) * Checks whether the value has query operators. * * @param mixed $value - * @return boolean + * @return bool */ private function hasQueryOperators($value) { - if ( ! is_array($value) && ! is_object($value)) { + if (! is_array($value) && ! is_object($value)) { return false; } @@ -1327,12 +1338,11 @@ private function hasQueryOperators($value) /** * Gets the array of discriminator values for the given ClassMetadata * - * @param ClassMetadata $metadata * @return array */ private function getClassDiscriminatorValues(ClassMetadata $metadata) { - $discriminatorValues = array($metadata->discriminatorValue); + $discriminatorValues = [$metadata->discriminatorValue]; foreach ($metadata->subClasses as $className) { if ($key = array_search($className, $metadata->discriminatorMap)) { $discriminatorValues[] = $key; @@ -1385,11 +1395,11 @@ private function guardMissingShardKey($document, $shardKeyField, $actualDocument $fieldMapping = $this->class->getFieldMappingByDbFieldName($shardKeyField); $fieldName = $fieldMapping['fieldName']; - if ($isUpdate && isset($dcs[$fieldName]) && $dcs[$fieldName][0] != $dcs[$fieldName][1]) { + if ($isUpdate && isset($dcs[$fieldName]) && $dcs[$fieldName][0] !== $dcs[$fieldName][1]) { throw MongoDBException::shardKeyFieldCannotBeChanged($shardKeyField, $this->class->getName()); } - if (!isset($actualDocumentData[$fieldName])) { + if (! isset($actualDocumentData[$fieldName])) { throw MongoDBException::shardKeyFieldMissing($shardKeyField, $this->class->getName()); } } @@ -1407,7 +1417,7 @@ private function getQueryForDocument($document) $id = $this->class->getDatabaseIdentifierValue($id); $shardKeyQueryPart = $this->getShardKeyQuery($document); - $query = array_merge(array('_id' => $id), $shardKeyQueryPart); + $query = array_merge(['_id' => $id], $shardKeyQueryPart); return $query; } @@ -1417,7 +1427,7 @@ private function getQueryForDocument($document) * * @return array */ - private function getWriteOptions(array $options = array()) + private function getWriteOptions(array $options = []) { $defaultOptions = $this->dm->getConfiguration()->getDefaultCommitOptions(); $documentOptions = []; @@ -1430,9 +1440,9 @@ private function getWriteOptions(array $options = array()) /** * @param string $fieldName - * @param mixed $value - * @param array $mapping - * @param bool $inNewObj + * @param mixed $value + * @param array $mapping + * @param bool $inNewObj * @return array */ private function prepareReference($fieldName, $value, array $mapping, $inNewObj) @@ -1451,7 +1461,7 @@ private function prepareReference($fieldName, $value, array $mapping, $inNewObj) case ClassMetadata::REFERENCE_STORE_AS_DB_REF_WITH_DB: $keys = ['$ref' => true, '$id' => true, '$db' => true]; - if ($mapping['storeAs'] === ClassMetadata::REFERENCE_STORE_AS_DB_REF) { + if ($mapping['storeAs'] === ClassMetadata::REFERENCE_STORE_AS_DB_REF) { unset($keys['$db']); } diff --git a/lib/Doctrine/ODM/MongoDB/Persisters/PersistenceBuilder.php b/lib/Doctrine/ODM/MongoDB/Persisters/PersistenceBuilder.php index 0b9368cc75..0dbd45ad70 100644 --- a/lib/Doctrine/ODM/MongoDB/Persisters/PersistenceBuilder.php +++ b/lib/Doctrine/ODM/MongoDB/Persisters/PersistenceBuilder.php @@ -1,4 +1,7 @@ dm->getClassMetadata(get_class($document)); $changeset = $this->uow->getDocumentChangeSet($document); - $insertData = array(); + $insertData = []; foreach ($class->fieldMappings as $mapping) { - $new = $changeset[$mapping['fieldName']][1] ?? null; if ($new === null && $mapping['nullable']) { @@ -71,7 +74,7 @@ public function prepareInsertData($document) } // @Field, @String, @Date, etc. - if ( ! isset($mapping['association'])) { + if (! isset($mapping['association'])) { $insertData[$mapping['name']] = Type::getType($mapping['type'])->convertToDatabaseValue($new); // @ReferenceOne @@ -110,19 +113,19 @@ public function prepareUpdateData($document) $class = $this->dm->getClassMetadata(get_class($document)); $changeset = $this->uow->getDocumentChangeSet($document); - $updateData = array(); + $updateData = []; foreach ($changeset as $fieldName => $change) { $mapping = $class->fieldMappings[$fieldName]; // skip non embedded document identifiers - if ( ! $class->isEmbeddedDocument && ! empty($mapping['id'])) { + if (! $class->isEmbeddedDocument && ! empty($mapping['id'])) { continue; } list($old, $new) = $change; // Scalar fields - if ( ! isset($mapping['association'])) { + if (! isset($mapping['association'])) { if ($new === null && $mapping['nullable'] !== true) { $updateData['$unset'][$mapping['name']] = true; } else { @@ -144,7 +147,7 @@ public function prepareUpdateData($document) $updateData['$set'][$mapping['name']] = $this->prepareEmbeddedDocumentValue($mapping, $new); // If we don't have a new value then lets unset the embedded document - } elseif ( ! $new) { + } elseif (! $new) { $updateData['$unset'][$mapping['name']] = true; // Update existing embedded document @@ -169,7 +172,7 @@ public function prepareUpdateData($document) $this->uow->unscheduleCollectionDeletion($old); } elseif ($mapping['association'] === ClassMetadata::EMBED_MANY) { foreach ($new as $key => $embeddedDoc) { - if ( ! $this->uow->isScheduledForInsert($embeddedDoc)) { + if (! $this->uow->isScheduledForInsert($embeddedDoc)) { $update = $this->prepareUpdateData($embeddedDoc); foreach ($update as $cmd => $values) { foreach ($values as $name => $value) { @@ -215,14 +218,14 @@ public function prepareUpsertData($document) $class = $this->dm->getClassMetadata(get_class($document)); $changeset = $this->uow->getDocumentChangeSet($document); - $updateData = array(); + $updateData = []; foreach ($changeset as $fieldName => $change) { $mapping = $class->fieldMappings[$fieldName]; list($old, $new) = $change; // Scalar fields - if ( ! isset($mapping['association'])) { + if (! isset($mapping['association'])) { if ($new !== null || $mapping['nullable'] === true) { if ($new !== null && empty($mapping['id']) && isset($mapping['strategy']) && $mapping['strategy'] === ClassMetadata::STORAGE_STRATEGY_INCREMENT) { $operator = '$inc'; @@ -280,7 +283,7 @@ 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 array $referenceMapping + * @param array $referenceMapping * @param object $document * @return array|null */ @@ -303,20 +306,20 @@ public function prepareReferencedDocumentValue(array $referenceMapping, $documen * within this value were previously scheduled for deletion or update, they * will also be unscheduled. * - * @param array $embeddedMapping + * @param array $embeddedMapping * @param object $embeddedDocument - * @param boolean $includeNestedCollections + * @param bool $includeNestedCollections * @return array|object * @throws \UnexpectedValueException if an unsupported associating mapping is found */ public function prepareEmbeddedDocumentValue(array $embeddedMapping, $embeddedDocument, $includeNestedCollections = false) { - $embeddedDocumentValue = array(); + $embeddedDocumentValue = []; $class = $this->dm->getClassMetadata(get_class($embeddedDocument)); foreach ($class->fieldMappings as $mapping) { // Skip notSaved fields - if ( ! empty($mapping['notSaved'])) { + if (! empty($mapping['notSaved'])) { continue; } @@ -341,7 +344,7 @@ public function prepareEmbeddedDocumentValue(array $embeddedMapping, $embeddedDo case ClassMetadata::EMBED_MANY: case ClassMetadata::REFERENCE_MANY: // Skip PersistentCollections already scheduled for deletion - if ( ! $includeNestedCollections && $rawValue instanceof PersistentCollectionInterface + if (! $includeNestedCollections && $rawValue instanceof PersistentCollectionInterface && $this->uow->isCollectionScheduledForDeletion($rawValue)) { break; } @@ -365,7 +368,7 @@ public function prepareEmbeddedDocumentValue(array $embeddedMapping, $embeddedDo /* Add a discriminator value if the embedded document is not mapped * explicitly to a targetDocument class. */ - if ( ! isset($embeddedMapping['targetDocument'])) { + if (! isset($embeddedMapping['targetDocument'])) { $discriminatorField = $embeddedMapping['discriminatorField']; $discriminatorValue = isset($embeddedMapping['discriminatorMap']) ? array_search($class->name, $embeddedMapping['discriminatorMap']) @@ -430,7 +433,6 @@ 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 array */ @@ -439,10 +441,12 @@ public function prepareAssociatedCollectionValue(PersistentCollectionInterface $ $mapping = $coll->getMapping(); $pb = $this; $callback = isset($mapping['embedded']) - ? function($v) use ($pb, $mapping, $includeNestedCollections) { + ? function ($v) use ($pb, $mapping, $includeNestedCollections) { return $pb->prepareEmbeddedDocumentValue($mapping, $v, $includeNestedCollections); } - : function($v) use ($pb, $mapping) { return $pb->prepareReferencedDocumentValue($mapping, $v); }; + : function ($v) use ($pb, $mapping) { + return $pb->prepareReferencedDocumentValue($mapping, $v); + }; $setData = $coll->map($callback)->toArray(); if (CollectionHelper::isList($mapping['strategy'])) { diff --git a/lib/Doctrine/ODM/MongoDB/Proxy/Proxy.php b/lib/Doctrine/ODM/MongoDB/Proxy/Proxy.php index 88e970434a..994872b847 100644 --- a/lib/Doctrine/ODM/MongoDB/Proxy/Proxy.php +++ b/lib/Doctrine/ODM/MongoDB/Proxy/Proxy.php @@ -1,5 +1,7 @@ ProxyFactory class that is * connected to the given DocumentManager. * - * @param \Doctrine\ODM\MongoDB\DocumentManager $documentManager The DocumentManager the new factory works for. - * @param string $proxyDir The directory to use for the proxy classes. It - * must exist. - * @param string $proxyNamespace The namespace to use for the proxy classes. - * @param integer $autoGenerate Whether to automatically generate proxy classes. + * @param DocumentManager $documentManager The DocumentManager the new factory works for. + * @param string $proxyDir The directory to use for the proxy classes. It + * must exist. + * @param string $proxyNamespace The namespace to use for the proxy classes. + * @param int $autoGenerate Whether to automatically generate proxy classes. */ public function __construct(DocumentManager $documentManager, $proxyDir, $proxyNamespace, $autoGenerate = AbstractProxyFactory::AUTOGENERATE_NEVER) { @@ -96,13 +101,10 @@ public function createProxyDefinition($className) /** * Generates a closure capable of initializing a proxy * - * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $classMetadata - * @param \Doctrine\ODM\MongoDB\Persisters\DocumentPersister $documentPersister - * @param \ReflectionProperty $reflectionId * * @return \Closure * - * @throws \Doctrine\ODM\MongoDB\DocumentNotFoundException + * @throws DocumentNotFoundException */ private function createInitializer( BaseClassMetadata $classMetadata, @@ -121,7 +123,7 @@ private function createInitializer( $properties = $proxy->__getLazyProperties(); foreach ($properties as $propertyName => $property) { - if ( ! isset($proxy->$propertyName)) { + if (! isset($proxy->$propertyName)) { $proxy->$propertyName = $properties[$propertyName]; } } @@ -131,8 +133,8 @@ private function createInitializer( $id = $reflectionId->getValue($proxy); - if (null === $documentPersister->load(array('_id' => $id), $proxy)) { - if ( ! $this->lifecycleEventManager->documentNotFound($proxy, $id)) { + if ($documentPersister->load(['_id' => $id], $proxy) === null) { + if (! $this->lifecycleEventManager->documentNotFound($proxy, $id)) { throw DocumentNotFoundException::documentNotFound(get_class($proxy), $id); } } @@ -154,7 +156,7 @@ private function createInitializer( $properties = $proxy->__getLazyProperties(); foreach ($properties as $propertyName => $property) { - if ( ! isset($proxy->$propertyName)) { + if (! isset($proxy->$propertyName)) { $proxy->$propertyName = $properties[$propertyName]; } } @@ -163,8 +165,8 @@ private function createInitializer( $id = $reflectionId->getValue($proxy); - if (null === $documentPersister->load(array('_id' => $id), $proxy)) { - if ( ! $this->lifecycleEventManager->documentNotFound($proxy, $id)) { + if ($documentPersister->load(['_id' => $id], $proxy) === null) { + if (! $this->lifecycleEventManager->documentNotFound($proxy, $id)) { throw DocumentNotFoundException::documentNotFound(get_class($proxy), $id); } } @@ -178,13 +180,10 @@ private function createInitializer( /** * Generates a closure capable of finalizing a cloned proxy * - * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $classMetadata - * @param \Doctrine\ODM\MongoDB\Persisters\DocumentPersister $documentPersister - * @param \ReflectionProperty $reflectionId * * @return \Closure * - * @throws \Doctrine\ODM\MongoDB\DocumentNotFoundException + * @throws DocumentNotFoundException */ private function createCloner( BaseClassMetadata $classMetadata, @@ -200,10 +199,10 @@ private function createCloner( $proxy->__setInitializer(null); $id = $reflectionId->getValue($proxy); - $original = $documentPersister->load(array('_id' => $id)); + $original = $documentPersister->load(['_id' => $id]); - if (null === $original) { - if ( ! $this->lifecycleEventManager->documentNotFound($proxy, $id)) { + if ($original === null) { + if (! $this->lifecycleEventManager->documentNotFound($proxy, $id)) { throw DocumentNotFoundException::documentNotFound(get_class($proxy), $id); } } diff --git a/lib/Doctrine/ODM/MongoDB/Query/Builder.php b/lib/Doctrine/ODM/MongoDB/Query/Builder.php index 8af027e822..104c03e59e 100644 --- a/lib/Doctrine/ODM/MongoDB/Query/Builder.php +++ b/lib/Doctrine/ODM/MongoDB/Query/Builder.php @@ -1,18 +1,31 @@ primers)) { + if (! $bool && ! empty($this->primers)) { throw new \BadMethodCallException("Can't set eagerCursor to false when using reference primers"); } - $this->query['eagerCursor'] = (boolean) $bool; + $this->query['eagerCursor'] = (bool) $bool; return $this; } @@ -464,7 +474,7 @@ public function equals($value) */ public function exclude($fieldName = null) { - if ( ! isset($this->query['select'])) { + if (! isset($this->query['select'])) { $this->query['select'] = []; } @@ -482,12 +492,12 @@ public function exclude($fieldName = null) * * @see Expr::exists() * @see http://docs.mongodb.org/manual/reference/operator/exists/ - * @param boolean $bool + * @param bool $bool * @return $this */ public function exists($bool) { - $this->expr->exists((boolean) $bool); + $this->expr->exists((bool) $bool); return $this; } @@ -521,7 +531,7 @@ public function field($field) /** * Set the "finalize" option for a mapReduce or group command. * - * @param string|\MongoDB\BSON\Javascript $finalize + * @param string|Javascript $finalize * @return $this * @throws \BadMethodCallException if the query is not a mapReduce or group command */ @@ -688,9 +698,9 @@ public function geoWithinCenterSphere($x, $y, $radius) * * @see Expr::geoWithinPolygon() * @see http://docs.mongodb.org/manual/reference/operator/polygon/ - * @param array $point1 First point of the polygon - * @param array $point2 Second point of the polygon - * @param array $point3 Third point of the polygon + * @param array $point1 First point of the polygon + * @param array $point2 Second point of the polygon + * @param array $point3 Third point of the polygon * @param array ...$points Additional points of the polygon * @return $this */ @@ -717,7 +727,7 @@ public function getNewObj() * @param array $options * @return Query $query */ - public function getQuery(array $options = array()) + public function getQuery(array $options = []) { if ($this->query['type'] === Query::TYPE_MAP_REDUCE) { $this->hydrate = false; @@ -743,11 +753,13 @@ public function getQuery(array $options = array()) 'discriminator. Either not use base class or set \'' . $this->class->discriminatorField . '\' field manually.'); } - if ( ! empty($query['select'])) { + if (! empty($query['select'])) { $query['select'] = $documentPersister->prepareProjection($query['select']); if ($this->hydrate && $this->class->inheritanceType === ClassMetadata::INHERITANCE_TYPE_SINGLE_COLLECTION && ! isset($query['select'][$this->class->discriminatorField])) { - $includeMode = 0 < count(array_filter($query['select'], function($mode) { return $mode == 1; })); + $includeMode = 0 < count(array_filter($query['select'], function ($mode) { + return $mode === 1; + })); if ($includeMode && ! isset($query['select'][$this->class->discriminatorField])) { $query['select'][$this->class->discriminatorField] = 1; } @@ -789,7 +801,7 @@ public function getQueryArray() /** * Get the type of this query. * - * @return integer $type + * @return int $type */ public function getType() { @@ -849,12 +861,12 @@ public function hydrate($bool = true) /** * Set the immortal cursor flag. * - * @param boolean $bool + * @param bool $bool * @return $this */ public function immortal($bool = true) { - $this->query['immortal'] = (boolean) $bool; + $this->query['immortal'] = (bool) $bool; return $this; } @@ -879,7 +891,7 @@ public function in(array $values) * * @see Expr::inc() * @see http://docs.mongodb.org/manual/reference/operator/inc/ - * @param float|integer $value + * @param float|int $value * @return $this */ public function inc($value) @@ -933,12 +945,12 @@ public function language($language) * commands. * * @see Query::prepareCursor() - * @param integer $limit + * @param int $limit * @return $this */ public function limit($limit) { - $this->query['limit'] = (integer) $limit; + $this->query['limit'] = (int) $limit; return $this; } @@ -979,7 +991,7 @@ public function lte($value) * The "out" option defaults to inline, like {@link Builder::mapReduce()}. * * @see http://docs.mongodb.org/manual/reference/command/mapReduce/ - * @param string|\MongoDB\BSON\Javascript $map + * @param string|Javascript $map * @return $this */ public function map($map) @@ -998,10 +1010,10 @@ public function map($map) * Change the query type to a mapReduce command. * * @see http://docs.mongodb.org/manual/reference/command/mapReduce/ - * @param string|\MongoDB\BSON\Javascript $map - * @param string|\MongoDB\BSON\Javascript $reduce - * @param array|string $out - * @param array $options + * @param string|Javascript $map + * @param string|Javascript $reduce + * @param array|string $out + * @param array $options * @return $this */ public function mapReduce($map, $reduce, $out = ['inline' => true], array $options = []) @@ -1011,7 +1023,7 @@ public function mapReduce($map, $reduce, $out = ['inline' => true], array $optio 'map' => $map, 'reduce' => $reduce, 'out' => $out, - 'options' => $options + 'options' => $options, ]; return $this; } @@ -1078,8 +1090,8 @@ public function min($value) * * @see Expr::mod() * @see http://docs.mongodb.org/manual/reference/operator/mod/ - * @param float|integer $divisor - * @param float|integer $remainder + * @param float|int $divisor + * @param float|int $remainder * @return $this */ public function mod($divisor, $remainder = 0) @@ -1095,7 +1107,7 @@ public function mod($divisor, $remainder = 0) * * @see Expr::mul() * @see http://docs.mongodb.org/manual/reference/operator/mul/ - * @param float|integer $value + * @param float|int $value * @return $this */ public function mul($value) @@ -1114,7 +1126,7 @@ public function mul($value) * @see Expr::near() * @see http://docs.mongodb.org/manual/reference/operator/near/ * @param float|array|Point $x - * @param float $y + * @param float $y * @return $this */ public function near($x, $y = null) @@ -1133,7 +1145,7 @@ public function near($x, $y = null) * @see Expr::nearSphere() * @see http://docs.mongodb.org/manual/reference/operator/nearSphere/ * @param float|array|Point $x - * @param float $y + * @param float $y * @return $this */ public function nearSphere($x, $y = null) @@ -1243,13 +1255,13 @@ public function popLast() * If a custom callable is used, its signature should conform to the default * Closure defined in {@link ReferencePrimer::__construct()}. * - * @param boolean|callable $primer + * @param bool|callable $primer * @return $this * @throws \InvalidArgumentException If $primer is not boolean or callable */ public function prime($primer = true) { - if ( ! is_bool($primer) && ! is_callable($primer)) { + if (! is_bool($primer) && ! is_callable($primer)) { throw new \InvalidArgumentException('$primer is not a boolean or callable'); } @@ -1259,7 +1271,7 @@ public function prime($primer = true) return $this; } - if (array_key_exists('eagerCursor', $this->query) && !$this->query['eagerCursor']) { + if (array_key_exists('eagerCursor', $this->query) && ! $this->query['eagerCursor']) { throw new \BadMethodCallException("Can't call prime() when setting eagerCursor to false"); } @@ -1352,7 +1364,7 @@ public function readOnly($bool = true) /** * Set the "reduce" option for a mapReduce or group command. * - * @param string|\MongoDB\BSON\Javascript $reduce + * @param string|Javascript $reduce * @return $this * @throws \BadMethodCallException if the query is not a mapReduce or group command */ @@ -1427,7 +1439,7 @@ public function rename($name) public function returnNew($bool = true) { $this->refresh(true); - $this->query['new'] = (boolean) $bool; + $this->query['new'] = (bool) $bool; return $this; } @@ -1440,7 +1452,7 @@ public function returnNew($bool = true) */ public function select($fieldName = null) { - if ( ! isset($this->query['select'])) { + if (! isset($this->query['select'])) { $this->query['select'] = []; } @@ -1458,7 +1470,7 @@ public function select($fieldName = null) * projection. * * @see http://docs.mongodb.org/manual/reference/projection/elemMatch/ - * @param string $fieldName + * @param string $fieldName * @param array|Expr $expression * @return $this */ @@ -1494,8 +1506,8 @@ public function selectMeta($fieldName, $metaDataKeyword) * * @see http://docs.mongodb.org/manual/reference/projection/slice/ * @param string $fieldName - * @param integer $countOrSkip Count parameter, or skip if limit is specified - * @param integer $limit Limit parameter used in conjunction with skip + * @param int $countOrSkip Count parameter, or skip if limit is specified + * @param int $limit Limit parameter used in conjunction with skip * @return $this */ public function selectSlice($fieldName, $countOrSkip, $limit = null) @@ -1518,7 +1530,7 @@ public function selectSlice($fieldName, $countOrSkip, $limit = null) * @see Expr::set() * @see http://docs.mongodb.org/manual/reference/operator/set/ * @param mixed $value - * @param boolean $atomic + * @param bool $atomic * @return $this */ public function set($value, $atomic = true) @@ -1566,7 +1578,6 @@ public function setOnInsert($value) * This is only relevant for read-only queries and commands. * * @see http://docs.mongodb.org/manual/core/read-preference/ - * @param ReadPreference $readPreference * @return $this */ public function setReadPreference(ReadPreference $readPreference) @@ -1593,12 +1604,12 @@ public function setQueryArray(array $query) * * @see Expr::size() * @see http://docs.mongodb.org/manual/reference/operator/size/ - * @param integer $size + * @param int $size * @return $this */ public function size($size) { - $this->expr->size((integer) $size); + $this->expr->size((int) $size); return $this; } @@ -1609,24 +1620,24 @@ public function size($size) * results in an output collecton and return a cursor. * * @see Query::prepareCursor() - * @param integer $skip + * @param int $skip * @return $this */ public function skip($skip) { - $this->query['skip'] = (integer) $skip; + $this->query['skip'] = (int) $skip; return $this; } /** * Set the snapshot cursor flag. * - * @param boolean $bool + * @param bool $bool * @return $this */ public function snapshot($bool = true) { - $this->query['snapshot'] = (boolean) $bool; + $this->query['snapshot'] = (bool) $bool; return $this; } @@ -1637,12 +1648,12 @@ public function snapshot($bool = true) * field name (key) and order (value) pairs. * * @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 $order Field order (if one field is specified) * @return $this */ public function sort($fieldName, $order = 1) { - if ( ! isset($this->query['sort'])) { + if (! isset($this->query['sort'])) { $this->query['sort'] = []; } @@ -1652,7 +1663,7 @@ public function sort($fieldName, $order = 1) if (is_string($order)) { $order = strtolower($order) === 'asc' ? 1 : -1; } - $this->query['sort'][$fieldName] = (integer) $order; + $this->query['sort'][$fieldName] = (int) $order; } return $this; @@ -1677,7 +1688,7 @@ public function sortMeta($fieldName, $metaDataKeyword) * operator. We'll assume that the user knows what they're doing in that * case and will not attempt to override the projection. */ - if ( ! isset($this->query['select'][$fieldName])) { + if (! isset($this->query['select'][$fieldName])) { $this->selectMeta($fieldName, $metaDataKeyword); } @@ -1707,7 +1718,7 @@ public function text($search) * * @see Expr::type() * @see http://docs.mongodb.org/manual/reference/operator/type/ - * @param integer $type + * @param int $type * @return $this */ public function type($type) @@ -1760,12 +1771,12 @@ public function updateMany($documentName = null) /** * Set the "upsert" option for an update or findAndUpdate query. * - * @param boolean $bool + * @param bool $bool * @return $this */ public function upsert($bool = true) { - $this->query['upsert'] = (boolean) $bool; + $this->query['upsert'] = (bool) $bool; return $this; } @@ -1774,7 +1785,7 @@ public function upsert($bool = true) * * @see Expr::where() * @see http://docs.mongodb.org/manual/reference/operator/where/ - * @param string|\MongoDB\BSON\Javascript $javascript + * @param string|Javascript $javascript * @return $this */ public function where($javascript) @@ -1792,8 +1803,8 @@ public function where($javascript) */ private function getDiscriminatorValues($classNames) { - $discriminatorValues = array(); - $collections = array(); + $discriminatorValues = []; + $collections = []; foreach ($classNames as $className) { $class = $this->dm->getClassMetadata($className); $discriminatorValues[] = $class->discriminatorValue; diff --git a/lib/Doctrine/ODM/MongoDB/Query/CriteriaMerger.php b/lib/Doctrine/ODM/MongoDB/Query/CriteriaMerger.php index a6a6a284f5..d531890f9a 100644 --- a/lib/Doctrine/ODM/MongoDB/Query/CriteriaMerger.php +++ b/lib/Doctrine/ODM/MongoDB/Query/CriteriaMerger.php @@ -1,7 +1,13 @@ dm = $dm; @@ -105,7 +117,9 @@ public function addNor($expression, ...$expressions) $this->query['$nor'] = array_merge( $this->query['$nor'], - array_map(function ($expression) { return $expression instanceof Expr ? $expression->getQuery() : $expression; }, func_get_args()) + array_map(function ($expression) { + return $expression instanceof Expr ? $expression->getQuery() : $expression; + }, func_get_args()) ); return $this; @@ -128,7 +142,9 @@ public function addOr($expression, ...$expressions) $this->query['$or'] = array_merge( $this->query['$or'], - array_map(function ($expression) { return $expression instanceof Expr ? $expression->getQuery() : $expression; }, func_get_args()) + array_map(function ($expression) { + return $expression instanceof Expr ? $expression->getQuery() : $expression; + }, func_get_args()) ); return $this; @@ -180,7 +196,7 @@ public function all(array $values) * * @see http://docs.mongodb.org/manual/reference/operator/update/bit/ * @param string $operator - * @param int $value + * @param int $value * @return $this */ protected function bit($operator, $value) @@ -222,7 +238,7 @@ public function bitOr($value) * * @see Builder::bitsAllClear() * @see https://docs.mongodb.org/manual/reference/operator/query/bitsAllClear/ - * @param int|array|\MongoDB\BSON\Binary $value + * @param int|array|Binary $value * @return $this */ public function bitsAllClear($value) @@ -237,7 +253,7 @@ public function bitsAllClear($value) * * @see Builder::bitsAllSet() * @see https://docs.mongodb.org/manual/reference/operator/query/bitsAllSet/ - * @param int|array|\MongoDB\BSON\Binary $value + * @param int|array|Binary $value * @return $this */ public function bitsAllSet($value) @@ -252,7 +268,7 @@ public function bitsAllSet($value) * * @see Builder::bitsAnyClear() * @see https://docs.mongodb.org/manual/reference/operator/query/bitsAnyClear/ - * @param int|array|\MongoDB\BSON\Binary $value + * @param int|array|Binary $value * @return $this */ public function bitsAnyClear($value) @@ -267,7 +283,7 @@ public function bitsAnyClear($value) * * @see Builder::bitsAnySet() * @see https://docs.mongodb.org/manual/reference/operator/query/bitsAnySet/ - * @param int|array|\MongoDB\BSON\Binary $value + * @param int|array|Binary $value * @return $this */ public function bitsAnySet($value) @@ -301,11 +317,10 @@ public function bitXor($value) * @return $this * @throws \BadMethodCallException if the query does not already have $text criteria * - * @since 1.3 */ public function caseSensitive($caseSensitive) { - if ( ! isset($this->query['$text'])) { + if (! isset($this->query['$text'])) { throw new \BadMethodCallException('This method requires a $text operator (call text() first)'); } @@ -365,11 +380,10 @@ public function currentDate($type = 'date') * @return $this * @throws \BadMethodCallException if the query does not already have $text criteria * - * @since 1.3 */ public function diacriticSensitive($diacriticSensitive) { - if ( ! isset($this->query['$text'])) { + if (! isset($this->query['$text'])) { throw new \BadMethodCallException('This method requires a $text operator (call text() first)'); } @@ -431,12 +445,12 @@ public function equals($value) * * @see Builder::exists() * @see http://docs.mongodb.org/manual/reference/operator/exists/ - * @param boolean $bool + * @param bool $bool * @return $this */ public function exists($bool) { - return $this->operator('$exists', (boolean) $bool); + return $this->operator('$exists', (bool) $bool); } /** @@ -568,9 +582,9 @@ public function geoWithinCenterSphere($x, $y, $radius) * * @see Builder::geoWithinPolygon() * @see http://docs.mongodb.org/manual/reference/operator/polygon/ - * @param array $point1 First point of the polygon - * @param array $point2 Second point of the polygon - * @param array $point3 Third point of the polygon + * @param array $point1 First point of the polygon + * @param array $point2 Second point of the polygon + * @param array $point3 Third point of the polygon * @param array ...$points Additional points of the polygon * @return $this * @throws \InvalidArgumentException if less than three points are given @@ -662,7 +676,7 @@ public function in(array $values) * * @see Builder::inc() * @see http://docs.mongodb.org/manual/reference/operator/inc/ - * @param float|integer $value + * @param float|int $value * @return $this */ public function inc($value) @@ -733,7 +747,7 @@ public function includesReferenceTo($document) */ public function language($language) { - if ( ! isset($this->query['$text'])) { + if (! isset($this->query['$text'])) { throw new \BadMethodCallException('This method requires a $text operator (call text() first)'); } @@ -803,8 +817,8 @@ public function min($value) * * @see Builder::mod() * @see http://docs.mongodb.org/manual/reference/operator/mod/ - * @param float|integer $divisor - * @param float|integer $remainder + * @param float|int $divisor + * @param float|int $remainder * @return $this */ public function mod($divisor, $remainder = 0) @@ -819,7 +833,7 @@ public function mod($divisor, $remainder = 0) * * @see Builder::mul() * @see http://docs.mongodb.org/manual/reference/operator/mul/ - * @param float|integer $value + * @param float|int $value * @return $this */ public function mul($value) @@ -839,7 +853,7 @@ public function mul($value) * @see Builder::near() * @see http://docs.mongodb.org/manual/reference/operator/near/ * @param float|array|Point $x - * @param float $y + * @param float $y * @return $this */ public function near($x, $y = null) @@ -865,7 +879,7 @@ public function near($x, $y = null) * @see Builder::nearSphere() * @see http://docs.mongodb.org/manual/reference/operator/nearSphere/ * @param float|array|Point $x - * @param float $y + * @param float $y * @return $this */ public function nearSphere($x, $y = null) @@ -927,7 +941,7 @@ public function notIn(array $values) * the operator is set at the top level of the query. * * @param string $operator - * @param mixed $value + * @param mixed $value * @return $this */ public function operator($operator, $value) @@ -977,7 +991,7 @@ public function popLast() * {@link Expr::push()} operation. * * @see http://docs.mongodb.org/manual/reference/operator/update/position/ - * @param integer $position + * @param int $position * @return $this */ public function position($position) @@ -1143,7 +1157,7 @@ public function rename($name) * @see Builder::set() * @see http://docs.mongodb.org/manual/reference/operator/set/ * @param mixed $value - * @param boolean $atomic + * @param bool $atomic * @return $this */ public function set($value, $atomic = true) @@ -1173,7 +1187,6 @@ public function set($value, $atomic = true) /** * Sets ClassMetadata for document being queried. * - * @param ClassMetadata $class */ public function setClassMetadata(ClassMetadata $class) { @@ -1233,12 +1246,12 @@ public function setQuery(array $query) * * @see Builder::size() * @see http://docs.mongodb.org/manual/reference/operator/size/ - * @param integer $size + * @param int $size * @return $this */ public function size($size) { - return $this->operator('$size', (integer) $size); + return $this->operator('$size', (int) $size); } /** @@ -1249,7 +1262,7 @@ public function size($size) * used for specifying $slice for a query projection. * * @see http://docs.mongodb.org/manual/reference/operator/slice/ - * @param integer $slice + * @param int $slice * @return $this */ public function slice($slice) @@ -1269,7 +1282,7 @@ public function slice($slice) * * @see http://docs.mongodb.org/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 $order Field order (if one field is specified) * @return $this */ public function sort($fieldName, $order = null) @@ -1301,7 +1314,7 @@ public function text($search) * @todo Remove support for string $type argument in 2.0 * @see Builder::type() * @see http://docs.mongodb.org/manual/reference/operator/type/ - * @param integer $type + * @param int $type * @return $this */ public function type($type) @@ -1356,7 +1369,7 @@ public function unsetField() * * @see Builder::where() * @see http://docs.mongodb.org/manual/reference/operator/where/ - * @param string|\MongoDB\BSON\Javascript $javascript + * @param string|Javascript $javascript * @return $this */ public function where($javascript) @@ -1401,7 +1414,6 @@ private function getReferenceMapping() /** * @param int|string $order * - * @return int */ private function normalizeSortOrder($order): int { @@ -1419,7 +1431,7 @@ private function normalizeSortOrder($order): int */ private function requiresCurrentField() { - if ( ! $this->currentField) { + if (! $this->currentField) { throw new \LogicException('This method requires you set a current field using field().'); } } diff --git a/lib/Doctrine/ODM/MongoDB/Query/Filter/BsonFilter.php b/lib/Doctrine/ODM/MongoDB/Query/Filter/BsonFilter.php index 2068acd85f..b8bf5762ba 100644 --- a/lib/Doctrine/ODM/MongoDB/Query/Filter/BsonFilter.php +++ b/lib/Doctrine/ODM/MongoDB/Query/Filter/BsonFilter.php @@ -1,9 +1,12 @@ parameters)) { + if (! array_key_exists($name, $this->parameters)) { throw new \InvalidArgumentException("Filter parameter '" . $name . "' is not set."); } return $this->parameters[$name]; @@ -72,7 +75,6 @@ final public function getParameter($name) * * If there is no criteria for the class, an empty array should be returned. * - * @param ClassMetadata $class * @return array */ abstract public function addFilterCriteria(ClassMetadata $class); diff --git a/lib/Doctrine/ODM/MongoDB/Query/FilterCollection.php b/lib/Doctrine/ODM/MongoDB/Query/FilterCollection.php index 75f93985d3..d1d03b4f6d 100644 --- a/lib/Doctrine/ODM/MongoDB/Query/FilterCollection.php +++ b/lib/Doctrine/ODM/MongoDB/Query/FilterCollection.php @@ -1,10 +1,15 @@ dm = $dm; $this->cm = $cm ?: new CriteriaMerger(); @@ -70,15 +69,15 @@ public function getEnabledFilters() * * @throws \InvalidArgumentException If the filter does not exist. * - * @return \Doctrine\ODM\MongoDB\Query\Filter\BsonFilter The enabled filter. + * @return BsonFilter The enabled filter. */ public function enable($name) { - if ( ! $this->has($name)) { + if (! $this->has($name)) { throw new \InvalidArgumentException("Filter '" . $name . "' does not exist."); } - if ( ! $this->isEnabled($name)) { + if (! $this->isEnabled($name)) { $filterClass = $this->config->getFilterClassName($name); $filterParameters = $this->config->getFilterParameters($name); $filter = new $filterClass($this->dm); @@ -98,7 +97,7 @@ public function enable($name) * * @param string $name Name of the filter. * - * @return \Doctrine\ODM\MongoDB\Query\Filter\BsonFilter The disabled filter. + * @return BsonFilter The disabled filter. * * @throws \InvalidArgumentException If the filter does not exist. */ @@ -117,13 +116,13 @@ public function disable($name) * * @param string $name Name of the filter. * - * @return \Doctrine\ODM\MongoDB\Query\Filter\BsonFilter The filter. + * @return BsonFilter The filter. * * @throws \InvalidArgumentException If the filter is not enabled. */ public function getFilter($name) { - if ( ! $this->isEnabled($name)) { + if (! $this->isEnabled($name)) { throw new \InvalidArgumentException("Filter '" . $name . "' is not enabled."); } return $this->enabledFilters[$name]; @@ -137,7 +136,7 @@ public function getFilter($name) */ public function has($name) { - return null !== $this->config->getFilterClassName($name); + return $this->config->getFilterClassName($name) !== null; } /** @@ -154,19 +153,20 @@ public function isEnabled($name) /** * Gets enabled filter criteria. * - * @param ClassMetadata $class * @return array */ public function getFilterCriteria(ClassMetadata $class) { if (empty($this->enabledFilters)) { - return array(); + return []; } return call_user_func_array( - array($this->cm, 'merge'), + [$this->cm, 'merge'], array_map( - function($filter) use ($class) { return $filter->addFilterCriteria($class); }, + function ($filter) use ($class) { + return $filter->addFilterCriteria($class); + }, $this->enabledFilters ) ); diff --git a/lib/Doctrine/ODM/MongoDB/Query/Query.php b/lib/Doctrine/ODM/MongoDB/Query/Query.php index 42a61a7e63..e1074633af 100644 --- a/lib/Doctrine/ODM/MongoDB/Query/Query.php +++ b/lib/Doctrine/ODM/MongoDB/Query/Query.php @@ -1,5 +1,7 @@ runQuery(); - if ( ! $this->hydrate) { + if (! $this->hydrate) { return $results; } @@ -209,15 +217,14 @@ public function execute() if (($this->query['type'] === self::TYPE_FIND_AND_UPDATE || $this->query['type'] === self::TYPE_FIND_AND_REMOVE) && is_array($results) && isset($results['_id'])) { - $results = $uow->getOrCreateDocument($this->class->name, $results, $this->unitOfWorkHints); - if ( ! empty($this->primers)) { + if (! empty($this->primers)) { $referencePrimer = new ReferencePrimer($this->dm, $uow); foreach ($this->primers as $fieldName => $primer) { $primer = is_callable($primer) ? $primer : null; - $referencePrimer->primeReferences($this->class, array($results), $fieldName, $this->unitOfWorkHints, $primer); + $referencePrimer->primeReferences($this->class, [$results], $fieldName, $this->unitOfWorkHints, $primer); } } } @@ -303,7 +310,7 @@ public function getSingleResult() /** * Return the query type. * - * @return integer + * @return int */ public function getType() { @@ -313,11 +320,11 @@ public function getType() /** * Sets whether or not to hydrate the documents to objects. * - * @param boolean $hydrate + * @param bool $hydrate */ public function setHydrate($hydrate) { - $this->hydrate = (boolean) $hydrate; + $this->hydrate = (bool) $hydrate; } /** @@ -326,11 +333,11 @@ public function setHydrate($hydrate) * * This option has no effect if hydration is disabled. * - * @param boolean $readOnly + * @param bool $readOnly */ public function setReadOnly($readOnly) { - $this->unitOfWorkHints[Query::HINT_READ_ONLY] = (boolean) $readOnly; + $this->unitOfWorkHints[self::HINT_READ_ONLY] = (bool) $readOnly; } /** @@ -339,11 +346,11 @@ public function setReadOnly($readOnly) * * This option has no effect if hydration is disabled. * - * @param boolean $refresh + * @param bool $refresh */ public function setRefresh($refresh) { - $this->unitOfWorkHints[Query::HINT_REFRESH] = (boolean) $refresh; + $this->unitOfWorkHints[self::HINT_REFRESH] = (bool) $refresh; } /** @@ -368,7 +375,9 @@ private function getQueryOptions(string ...$keys) { return array_filter( array_intersect_key($this->query, array_flip($keys)), - function($value) { return $value !== null; } + function ($value) { + return $value !== null; + } ); } @@ -380,7 +389,7 @@ private function makeIterator(Cursor $cursor): Iterator $cursor = new CachingIterator($cursor); - if ( ! empty($this->primers)) { + if (! empty($this->primers)) { $referencePrimer = new ReferencePrimer($this->dm, $this->dm->getUnitOfWork()); $cursor = new PrimingIterator($cursor, $this->class, $referencePrimer, $this->primers, $this->unitOfWorkHints); } @@ -402,7 +411,9 @@ private function renameQueryOptions(array $options, array $rename) return array_combine( array_map( - function($key) use ($rename) { return $rename[$key] ?? $key; }, + function ($key) use ($rename) { + return $rename[$key] ?? $key; + }, array_keys($options) ), array_values($options) diff --git a/lib/Doctrine/ODM/MongoDB/Query/QueryExpressionVisitor.php b/lib/Doctrine/ODM/MongoDB/Query/QueryExpressionVisitor.php index 2ec17e8c3e..8cdc2fdfcb 100644 --- a/lib/Doctrine/ODM/MongoDB/Query/QueryExpressionVisitor.php +++ b/lib/Doctrine/ODM/MongoDB/Query/QueryExpressionVisitor.php @@ -1,16 +1,18 @@ 'equals', Comparison::GT => 'gt', Comparison::GTE => 'gte', @@ -30,28 +32,23 @@ class QueryExpressionVisitor extends ExpressionVisitor Comparison::LTE => 'lte', Comparison::NEQ => 'notEqual', Comparison::NIN => 'notIn', - ); + ]; /** * Map Criteria API composite types to query builder methods * * @var array */ - private static $compositeMethods = array( + private static $compositeMethods = [ CompositeExpression::TYPE_AND => 'addAnd', CompositeExpression::TYPE_OR => 'addOr', - ); + ]; /** * @var Builder */ protected $builder; - /** - * Constructor. - * - * @param Builder $builder - */ public function __construct(Builder $builder) { $this->builder = $builder; @@ -61,8 +58,7 @@ public function __construct(Builder $builder) * Converts a comparison expression into the target query language output. * * @see ExpressionVisitor::walkComparison() - * @param Comparison $comparison - * @return \Doctrine\ODM\MongoDB\Query\Expr + * @return Expr */ public function walkComparison(Comparison $comparison) { @@ -87,7 +83,7 @@ public function walkComparison(Comparison $comparison) return $this->builder->expr() ->field($comparison->getField()) - ->equals(new \MongoDB\BSON\Regex($value, '')); + ->equals(new Regex($value, '')); default: throw new \RuntimeException('Unknown comparison operator: ' . $comparison->getOperator()); @@ -98,12 +94,11 @@ public function walkComparison(Comparison $comparison) * Converts a composite expression into the target query language output. * * @see ExpressionVisitor::walkCompositeExpression() - * @param CompositeExpression $compositeExpr - * @return \Doctrine\ODM\MongoDB\Query\Expr + * @return Expr */ public function walkCompositeExpression(CompositeExpression $compositeExpr) { - if ( ! isset(self::$compositeMethods[$compositeExpr->getType()])) { + if (! isset(self::$compositeMethods[$compositeExpr->getType()])) { throw new \RuntimeException('Unknown composite ' . $compositeExpr->getType()); } @@ -121,7 +116,6 @@ public function walkCompositeExpression(CompositeExpression $compositeExpr) * Converts a value expression into the target query language part. * * @see ExpressionVisitor::walkValue() - * @param Value $value * @return mixed */ public function walkValue(Value $value) diff --git a/lib/Doctrine/ODM/MongoDB/Query/ReferencePrimer.php b/lib/Doctrine/ODM/MongoDB/Query/ReferencePrimer.php index 29c3cb6c5b..bcbca29d4b 100644 --- a/lib/Doctrine/ODM/MongoDB/Query/ReferencePrimer.php +++ b/lib/Doctrine/ODM/MongoDB/Query/ReferencePrimer.php @@ -1,14 +1,26 @@ dm = $dm; $this->uow = $uow; - $this->defaultPrimer = function(DocumentManager $dm, ClassMetadata $class, array $ids, array $hints) { + $this->defaultPrimer = function (DocumentManager $dm, ClassMetadata $class, array $ids, array $hints) { $qb = $dm->createQueryBuilder($class->name) ->field($class->identifier)->in($ids); - if ( ! empty($hints[Query::HINT_READ_PREFERENCE])) { + if (! empty($hints[Query::HINT_READ_PREFERENCE])) { $qb->setReadPreference($hints[Query::HINT_READ_PREFERENCE]); } @@ -87,7 +98,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, $fieldName, array $hints = array(), $primer = null) + public function primeReferences(ClassMetadata $class, $documents, $fieldName, array $hints = [], $primer = null) { $data = $this->parseDotSyntaxForPrimer($fieldName, $class, $documents); $mapping = $data['mapping']; @@ -98,7 +109,7 @@ public function primeReferences(ClassMetadata $class, $documents, $fieldName, ar /* Inverse-side references would need to be populated before we can * collect references to be primed. This is not supported. */ - if ( ! isset($mapping['reference']) || ! $mapping['isOwningSide']) { + if (! isset($mapping['reference']) || ! $mapping['isOwningSide']) { throw new \InvalidArgumentException(sprintf('Field "%s" is not the owning side of a reference relationship in class "%s"', $fieldName, $class->name)); } @@ -114,7 +125,7 @@ public function primeReferences(ClassMetadata $class, $documents, $fieldName, ar } $primer = $primer ?: $this->defaultPrimer; - $groupedIds = array(); + $groupedIds = []; /* @var $document PersistentCollectionInterface */ foreach ($documents as $document) { @@ -123,7 +134,7 @@ public function primeReferences(ClassMetadata $class, $documents, $fieldName, ar /* The field will need to be either a Proxy (reference-one) or * PersistentCollection (reference-many) in order to prime anything. */ - if ( ! is_object($fieldValue)) { + if (! is_object($fieldValue)) { continue; } @@ -131,7 +142,7 @@ public function primeReferences(ClassMetadata $class, $documents, $fieldName, ar $refClass = $this->dm->getClassMetadata(get_class($fieldValue)); $id = $this->uow->getDocumentIdentifier($fieldValue); $groupedIds[$refClass->name][serialize($id)] = $id; - } elseif ($mapping['type'] == 'many' && $fieldValue instanceof PersistentCollectionInterface) { + } elseif ($mapping['type'] === 'many' && $fieldValue instanceof PersistentCollectionInterface) { $this->addManyReferences($fieldValue, $groupedIds); } } @@ -159,14 +170,14 @@ public function primeReferences(ClassMetadata $class, $documents, $fieldName, ar private function parseDotSyntaxForPrimer($fieldName, $class, $documents, $mapping = null) { // Recursion passthrough: - if ($mapping != null) { - return array('fieldName' => $fieldName, 'class' => $class, 'documents' => $documents, 'mapping' => $mapping); + if ($mapping !== null) { + return ['fieldName' => $fieldName, 'class' => $class, 'documents' => $documents, 'mapping' => $mapping]; } // Gather mapping data: $e = explode('.', $fieldName); - if ( ! isset($class->fieldMappings[$e[0]])) { + if (! isset($class->fieldMappings[$e[0]])) { throw new \InvalidArgumentException(sprintf('Field %s cannot be further parsed for priming because it is unmapped.', $fieldName)); } @@ -174,16 +185,16 @@ private function parseDotSyntaxForPrimer($fieldName, $class, $documents, $mappin $e[0] = $mapping['fieldName']; // Case of embedded document(s) to recurse through: - if ( ! isset($mapping['reference'])) { + if (! isset($mapping['reference'])) { if (empty($mapping['embedded'])) { throw new \InvalidArgumentException(sprintf('Field "%s" of fieldName "%s" is not an embedded document, therefore no children can be primed. Aborting. This feature does not support traversing nested referenced documents at this time.', $e[0], $fieldName)); } - if ( ! isset($mapping['targetDocument'])) { + if (! isset($mapping['targetDocument'])) { throw new \InvalidArgumentException(sprintf('No target document class has been specified for this embedded document. However, targetDocument mapping must be specified in order for prime to work on fieldName "%s" for mapping of field "%s".', $fieldName, $mapping['fieldName'])); } - $childDocuments = array(); + $childDocuments = []; foreach ($documents as $document) { $fieldValue = $class->getFieldValue($document, $e[0]); @@ -193,7 +204,7 @@ private function parseDotSyntaxForPrimer($fieldName, $class, $documents, $mappin array_push($childDocuments, $elemDocument); } } else { - array_push($childDocuments,$fieldValue); + array_push($childDocuments, $fieldValue); } } @@ -201,11 +212,11 @@ private function parseDotSyntaxForPrimer($fieldName, $class, $documents, $mappin $childClass = $this->dm->getClassMetadata($mapping['targetDocument']); - if ( ! $childClass->hasField($e[0])) { + if (! $childClass->hasField($e[0])) { throw new \InvalidArgumentException(sprintf('Field to prime must exist in embedded target document. Reference fieldName "%s" for mapping of target document class "%s".', $fieldName, $mapping['targetDocument'])); } - $childFieldName = implode('.',$e); + $childFieldName = implode('.', $e); return $this->parseDotSyntaxForPrimer($childFieldName, $childClass, $childDocuments); } @@ -216,7 +227,7 @@ private function parseDotSyntaxForPrimer($fieldName, $class, $documents, $mappin throw new \InvalidArgumentException(sprintf('Cannot prime more than one layer deep but field "%s" is a reference and has children in fieldName "%s".', $e[0], $fieldName)); } - return array('fieldName' => $fieldName, 'class' => $class, 'documents' => $documents, 'mapping' => $mapping); + return ['fieldName' => $fieldName, 'class' => $class, 'documents' => $documents, 'mapping' => $mapping]; } } @@ -227,8 +238,7 @@ private function parseDotSyntaxForPrimer($fieldName, $class, $documents, $mappin * have a target document class defined. Without that, there is no way to * infer the class of the referenced documents. * - * @param PersistentCollectionInterface $persistentCollection - * @param array $groupedIds + * @param array $groupedIds */ private function addManyReferences(PersistentCollectionInterface $persistentCollection, array &$groupedIds) { @@ -251,7 +261,7 @@ private function addManyReferences(PersistentCollectionInterface $persistentColl $document = $this->uow->tryGetById($id, $class); - if ( ! $document || ($document instanceof Proxy && ! $document->__isInitialized())) { + if (! $document || ($document instanceof Proxy && ! $document->__isInitialized())) { $id = $class->getPHPIdentifierValue($id); $groupedIds[$className][serialize($id)] = $id; } diff --git a/lib/Doctrine/ODM/MongoDB/Repository/AbstractRepositoryFactory.php b/lib/Doctrine/ODM/MongoDB/Repository/AbstractRepositoryFactory.php index 9c3f555fcf..6b05f65508 100644 --- a/lib/Doctrine/ODM/MongoDB/Repository/AbstractRepositoryFactory.php +++ b/lib/Doctrine/ODM/MongoDB/Repository/AbstractRepositoryFactory.php @@ -1,15 +1,18 @@ dm = $dm; @@ -35,7 +36,7 @@ public function __construct(DocumentManager $dm, ClassMetadataFactory $cmf) * Ensure indexes are created for all documents that can be loaded with the * metadata factory. * - * @param integer $timeout Timeout (ms) for acknowledged index creation + * @param int $timeout Timeout (ms) for acknowledged index creation */ public function ensureIndexes($timeout = null) { @@ -53,7 +54,7 @@ public function ensureIndexes($timeout = null) * Indexes that exist in MongoDB but not the document metadata will be * deleted. * - * @param integer $timeout Timeout (ms) for acknowledged index creation + * @param int $timeout Timeout (ms) for acknowledged index creation */ public function updateIndexes($timeout = null) { @@ -72,7 +73,7 @@ public function updateIndexes($timeout = null) * deleted. * * @param string $documentName - * @param integer $timeout Timeout (ms) for acknowledged index creation + * @param int $timeout Timeout (ms) for acknowledged index creation * @throws \InvalidArgumentException */ public function updateDocumentIndexes($documentName, $timeout = null) @@ -92,7 +93,7 @@ public function updateDocumentIndexes($documentName, $timeout = null) */ $self = $this; $mongoIndexes = array_filter($mongoIndexes, function (IndexInfo $mongoIndex) use ($documentIndexes, $self) { - if ('_id_' === $mongoIndex['name']) { + if ($mongoIndex['name'] === '_id_') { return false; } @@ -123,32 +124,32 @@ public function updateDocumentIndexes($documentName, $timeout = null) */ public function getDocumentIndexes($documentName) { - $visited = array(); + $visited = []; return $this->doGetDocumentIndexes($documentName, $visited); } /** * @param string $documentName - * @param array $visited + * @param array $visited * @return array */ private function doGetDocumentIndexes($documentName, array &$visited) { if (isset($visited[$documentName])) { - return array(); + return []; } $visited[$documentName] = true; $class = $this->dm->getClassMetadata($documentName); $indexes = $this->prepareIndexes($class); - $embeddedDocumentIndexes = array(); + $embeddedDocumentIndexes = []; // Add indexes from embedded & referenced documents foreach ($class->fieldMappings as $fieldMapping) { if (isset($fieldMapping['embedded'])) { if (isset($fieldMapping['targetDocument'])) { - $possibleEmbeds = array($fieldMapping['targetDocument']); + $possibleEmbeds = [$fieldMapping['targetDocument']]; } elseif (isset($fieldMapping['discriminatorMap'])) { $possibleEmbeds = array_unique($fieldMapping['discriminatorMap']); } else { @@ -171,9 +172,9 @@ private function doGetDocumentIndexes($documentName, array &$visited) } } elseif (isset($fieldMapping['reference']) && isset($fieldMapping['targetDocument'])) { foreach ($indexes as $idx => $index) { - $newKeys = array(); + $newKeys = []; foreach ($index['keys'] as $key => $v) { - if ($key == $fieldMapping['name']) { + if ($key === $fieldMapping['name']) { $key = ClassMetadata::getReferenceFieldName($fieldMapping['storeAs'], $key); } $newKeys[$key] = $v; @@ -186,20 +187,19 @@ private function doGetDocumentIndexes($documentName, array &$visited) } /** - * @param ClassMetadata $class * @return array */ private function prepareIndexes(ClassMetadata $class) { $persister = $this->dm->getUnitOfWork()->getDocumentPersister($class->name); $indexes = $class->getIndexes(); - $newIndexes = array(); + $newIndexes = []; foreach ($indexes as $index) { - $newIndex = array( - 'keys' => array(), - 'options' => $index['options'] - ); + $newIndex = [ + 'keys' => [], + 'options' => $index['options'], + ]; foreach ($index['keys'] as $key => $value) { $key = $persister->prepareFieldName($key); if ($class->hasField($key)) { @@ -220,7 +220,7 @@ private function prepareIndexes(ClassMetadata $class) * Ensure the given document's indexes are created. * * @param string $documentName - * @param integer $timeout Timeout (ms) for acknowledged index creation + * @param int $timeout Timeout (ms) for acknowledged index creation * @throws \InvalidArgumentException */ public function ensureDocumentIndexes($documentName, $timeout = null) @@ -235,7 +235,7 @@ public function ensureDocumentIndexes($documentName, $timeout = null) $keys = $index['keys']; $options = $index['options']; - if ( ! isset($options['timeout']) && isset($timeout)) { + if (! isset($options['timeout']) && isset($timeout)) { $options['timeout'] = $timeout; } @@ -384,15 +384,15 @@ public function dropDocumentDatabase($documentName) * the unique index. Additionally, the background option is only * relevant to index creation and is not considered. * - * @param array|IndexInfo $mongoIndex Mongo index data. - * @param array $documentIndex Document index data. + * @param array|IndexInfo $mongoIndex Mongo index data. + * @param array $documentIndex Document index data. * @return bool True if the indexes are equivalent, otherwise false. */ public function isMongoIndexEquivalentToDocumentIndex($mongoIndex, $documentIndex) { $documentIndexOptions = $documentIndex['options']; - if ($mongoIndex['key'] != $documentIndex['keys']) { + if ($mongoIndex['key'] !== $documentIndex['keys']) { return false; } @@ -404,20 +404,18 @@ public function isMongoIndexEquivalentToDocumentIndex($mongoIndex, $documentInde return false; } - if ( ! empty($mongoIndex['unique']) && empty($mongoIndex['dropDups']) && + if (! empty($mongoIndex['unique']) && empty($mongoIndex['dropDups']) && ! empty($documentIndexOptions['unique']) && ! empty($documentIndexOptions['dropDups'])) { - return false; } - foreach (array('bits', 'max', 'min') as $option) { + foreach (['bits', 'max', 'min'] as $option) { if (isset($mongoIndex[$option]) xor isset($documentIndexOptions[$option])) { return false; } if (isset($mongoIndex[$option]) && isset($documentIndexOptions[$option]) && $mongoIndex[$option] !== $documentIndexOptions[$option]) { - return false; } } @@ -428,7 +426,6 @@ public function isMongoIndexEquivalentToDocumentIndex($mongoIndex, $documentInde if (isset($mongoIndex['partialFilterExpression']) && isset($documentIndexOptions['partialFilterExpression']) && $mongoIndex['partialFilterExpression'] !== $documentIndexOptions['partialFilterExpression']) { - return false; } @@ -443,10 +440,10 @@ public function isMongoIndexEquivalentToDocumentIndex($mongoIndex, $documentInde * * @throws MongoDBException */ - public function ensureSharding(array $indexOptions = array()) + public function ensureSharding(array $indexOptions = []) { foreach ($this->metadataFactory->getAllMetadata() as $class) { - if ($class->isMappedSuperclass || !$class->isSharded()) { + if ($class->isMappedSuperclass || ! $class->isSharded()) { continue; } @@ -462,10 +459,10 @@ public function ensureSharding(array $indexOptions = array()) * * @throws MongoDBException */ - public function ensureDocumentSharding($documentName, array $indexOptions = array()) + public function ensureDocumentSharding($documentName, array $indexOptions = []) { $class = $this->dm->getClassMetadata($documentName); - if ( ! $class->isSharded()) { + if (! $class->isSharded()) { return; } @@ -478,7 +475,7 @@ public function ensureDocumentSharding($documentName, array $indexOptions = arra $done = true; // Need to check error message because MongoDB 3.0 does not return a code for this error - if ($result['ok'] != 1 && strpos($result['errmsg'], 'please create an index that starts') !== false) { + if (! (bool) $result['ok'] && strpos($result['errmsg'], 'please create an index that starts') !== false) { // The proposed key is not returned when using mongo-php-adapter with ext-mongodb. // See https://github.com/mongodb/mongo-php-driver/issues/296 for details $key = $result['proposedKey'] ?? $this->dm->getClassMetadata($documentName)->getShardKey()['keys']; @@ -487,7 +484,7 @@ public function ensureDocumentSharding($documentName, array $indexOptions = arra $done = false; } } catch (RuntimeException $e) { - if ($e->getCode() === 20 || $e->getMessage() == 'already sharded') { + if ($e->getCode() === 20 || $e->getCode() === 23 || $e->getMessage() === 'already sharded') { return; } @@ -497,7 +494,7 @@ public function ensureDocumentSharding($documentName, array $indexOptions = arra // Starting with MongoDB 3.2, this command returns code 20 when a collection is already sharded. // For older MongoDB versions, check the error message - if ($result['ok'] == 1 || (isset($result['code']) && $result['code'] == 20) || $result['errmsg'] == 'already sharded') { + if ((bool) $result['ok'] || (isset($result['code']) && $result['code'] === 20) || $result['errmsg'] === 'already sharded') { return; } @@ -517,7 +514,7 @@ public function enableShardingForDbByDocumentName($documentName) $adminDb = $this->dm->getClient()->selectDatabase('admin'); try { - $adminDb->command(array('enableSharding' => $dbName)); + $adminDb->command(['enableSharding' => $dbName]); } catch (RuntimeException $e) { if ($e->getCode() !== 23 || $e->getMessage() === 'already enabled') { throw MongoDBException::failedToEnableSharding($dbName, $e->getMessage()); @@ -538,10 +535,10 @@ private function runShardCollectionCommand($documentName) $adminDb = $this->dm->getClient()->selectDatabase('admin'); $result = $adminDb->command( - array( + [ 'shardCollection' => $dbName . '.' . $class->getCollection(), - 'key' => $shardKey['keys'] - ) + 'key' => $shardKey['keys'], + ] )->toArray()[0]; return $result; diff --git a/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/ClearCache/MetadataCommand.php b/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/ClearCache/MetadataCommand.php index c7b3cab89f..e7c4bca4a5 100644 --- a/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/ClearCache/MetadataCommand.php +++ b/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/ClearCache/MetadataCommand.php @@ -1,17 +1,18 @@ setName('odm:clear-cache:metadata') ->setDescription('Clear all metadata cache of the various cache drivers.') - ->setDefinition(array()) + ->setDefinition([]) ->setHelp(<<getHelper('documentManager')->getDocumentManager(); $cacheDriver = $dm->getConfiguration()->getMetadataCacheImpl(); - if ( ! $cacheDriver) { + if (! $cacheDriver) { throw new \InvalidArgumentException('No Metadata cache driver is configured on given DocumentManager.'); } if ($cacheDriver instanceof ApcCache) { - throw new \LogicException("Cannot clear APC Cache from Console, its shared in the Webserver memory and not accessible from the CLI."); + throw new \LogicException('Cannot clear APC Cache from Console, its shared in the Webserver memory and not accessible from the CLI.'); } $output->write('Clearing ALL Metadata cache entries' . PHP_EOL); diff --git a/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/GenerateHydratorsCommand.php b/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/GenerateHydratorsCommand.php index d2c3d4feaa..cb52181060 100644 --- a/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/GenerateHydratorsCommand.php +++ b/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/GenerateHydratorsCommand.php @@ -1,16 +1,25 @@ setName('odm:generate:hydrators') ->setDescription('Generates hydrator classes for document classes.') - ->setDefinition(array( + ->setDefinition([ new InputOption( - 'filter', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, + 'filter', + null, + InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'A string pattern used to match documents that should be processed.' ), new InputArgument( - 'dest-path', InputArgument::OPTIONAL, + 'dest-path', + InputArgument::OPTIONAL, 'The path to generate your hydrator classes. If none is provided, it will attempt to grab from configuration.' ), - )) + ]) ->setHelp(<<getHelper('documentManager')->getDocumentManager(); - + $metadatas = $dm->getMetadataFactory()->getAllMetadata(); $metadatas = MetadataFilter::filter($metadatas, $input->getOption('filter')); @@ -53,17 +65,17 @@ protected function execute(Console\Input\InputInterface $input, Console\Output\O $destPath = $dm->getConfiguration()->getHydratorDir(); } - if ( ! is_dir($destPath)) { + if (! is_dir($destPath)) { mkdir($destPath, 0775, true); } $destPath = realpath($destPath); - if ( ! file_exists($destPath)) { + if (! file_exists($destPath)) { throw new \InvalidArgumentException( sprintf("Hydrators destination directory '%s' does not exist.", $destPath) ); - } elseif ( ! is_writable($destPath)) { + } elseif (! is_writable($destPath)) { throw new \InvalidArgumentException( sprintf("Hydrators destination directory '%s' does not have write permissions.", $destPath) ); diff --git a/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/GeneratePersistentCollectionsCommand.php b/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/GeneratePersistentCollectionsCommand.php index ead7e9054d..48b90f7776 100644 --- a/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/GeneratePersistentCollectionsCommand.php +++ b/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/GeneratePersistentCollectionsCommand.php @@ -1,16 +1,25 @@ setName('odm:generate:persistent-collections') ->setDescription('Generates persistent collection classes for custom collections.') - ->setDefinition(array( + ->setDefinition([ new InputOption( - 'filter', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, + 'filter', + null, + InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'A string pattern used to match documents that should be processed.' ), new InputArgument( - 'dest-path', InputArgument::OPTIONAL, + 'dest-path', + InputArgument::OPTIONAL, 'The path to generate your proxy classes. If none is provided, it will attempt to grab from configuration.' ), - )) + ]) ->setHelp(<<getConfiguration()->getPersistentCollectionDir(); } - if ( ! is_dir($destPath)) { + if (! is_dir($destPath)) { mkdir($destPath, 0775, true); } $destPath = realpath($destPath); - if ( ! file_exists($destPath)) { + if (! file_exists($destPath)) { throw new \InvalidArgumentException( sprintf("Persistent collections destination directory '%s' does not exist.", $destPath) ); - } elseif ( ! is_writable($destPath)) { + } elseif (! is_writable($destPath)) { throw new \InvalidArgumentException( sprintf("Persistent collections destination directory '%s' does not have write permissions.", $destPath) ); diff --git a/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/GenerateProxiesCommand.php b/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/GenerateProxiesCommand.php index b5f650dc7c..043c3ba7a1 100644 --- a/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/GenerateProxiesCommand.php +++ b/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/GenerateProxiesCommand.php @@ -1,17 +1,27 @@ setName('odm:generate:proxies') ->setDescription('Generates proxy classes for document classes.') - ->setDefinition(array( + ->setDefinition([ new InputOption( - 'filter', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, + 'filter', + null, + InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'A string pattern used to match documents that should be processed.' ), new InputArgument( - 'dest-path', InputArgument::OPTIONAL, + 'dest-path', + InputArgument::OPTIONAL, 'The path to generate your proxy classes. If none is provided, it will attempt to grab from configuration.' ), - )) + ]) ->setHelp(<<getHelper('documentManager')->getDocumentManager(); - + $metadatas = array_filter($dm->getMetadataFactory()->getAllMetadata(), function (ClassMetadata $classMetadata) { - return !$classMetadata->isEmbeddedDocument && !$classMetadata->isMappedSuperclass && !$classMetadata->isQueryResultDocument; + return ! $classMetadata->isEmbeddedDocument && ! $classMetadata->isMappedSuperclass && ! $classMetadata->isQueryResultDocument; }); $metadatas = MetadataFilter::filter($metadatas, $input->getOption('filter')); @@ -56,17 +69,17 @@ protected function execute(Console\Input\InputInterface $input, Console\Output\O $destPath = $dm->getConfiguration()->getProxyDir(); } - if ( ! is_dir($destPath)) { + if (! is_dir($destPath)) { mkdir($destPath, 0775, true); } $destPath = realpath($destPath); - if ( ! file_exists($destPath)) { + if (! file_exists($destPath)) { throw new \InvalidArgumentException( sprintf("Proxies destination directory '%s' does not exist.", $destPath) ); - } elseif ( ! is_writable($destPath)) { + } elseif (! is_writable($destPath)) { throw new \InvalidArgumentException( sprintf("Proxies destination directory '%s' does not have write permissions.", $destPath) ); diff --git a/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/QueryCommand.php b/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/QueryCommand.php index 3c65f500be..f4372b6919 100644 --- a/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/QueryCommand.php +++ b/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/QueryCommand.php @@ -1,16 +1,19 @@ setName('odm:query') ->setDescription('Query mongodb and inspect the outputted results from your document classes.') - ->setDefinition(array( + ->setDefinition([ new InputArgument( - 'class', InputArgument::REQUIRED, + 'class', + InputArgument::REQUIRED, 'The class to query.' ), new InputArgument( - 'query', InputArgument::REQUIRED, + 'query', + InputArgument::REQUIRED, 'The query to execute and output the results for.' ), new InputOption( - 'hydrate', null, InputOption::VALUE_NONE, + 'hydrate', + null, + InputOption::VALUE_NONE, 'Whether or not to hydrate the results in to document objects.' ), new InputOption( - 'skip', null, InputOption::VALUE_REQUIRED, + 'skip', + null, + InputOption::VALUE_REQUIRED, 'The number of documents to skip in the cursor.' ), new InputOption( - 'limit', null, InputOption::VALUE_REQUIRED, + 'limit', + null, + InputOption::VALUE_REQUIRED, 'The number of documents to return.' ), new InputOption( - 'depth', null, InputOption::VALUE_REQUIRED, - 'Dumping depth of Document graph.', 7 - ) - )) + 'depth', + null, + InputOption::VALUE_REQUIRED, + 'Dumping depth of Document graph.', + 7 + ), + ]) ->setHelp(<<getOption('depth'); - if ( ! is_numeric($depth)) { + if (! is_numeric($depth)) { throw new \LogicException("Option 'depth' must contain an integer value"); } if (($skip = $input->getOption('skip')) !== null) { - if ( ! is_numeric($skip)) { + if (! is_numeric($skip)) { throw new \LogicException("Option 'skip' must contain an integer value"); } @@ -79,7 +93,7 @@ protected function execute(Console\Input\InputInterface $input, Console\Output\O } if (($limit = $input->getOption('limit')) !== null) { - if ( ! is_numeric($limit)) { + if (! is_numeric($limit)) { throw new \LogicException("Option 'limit' must contain an integer value"); } diff --git a/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/Schema/AbstractCommand.php b/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/Schema/AbstractCommand.php index d20bd4cda9..133bf00aef 100644 --- a/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/Schema/AbstractCommand.php +++ b/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/Schema/AbstractCommand.php @@ -1,15 +1,19 @@ writeln(sprintf( 'Created %s%s for %s', $option, - (isset($class) ? (self::INDEX === $option ? '(es)' : '') : (self::INDEX === $option ? 'es' : 's')), + (isset($class) ? ($option === self::INDEX ? '(es)' : '') : ($option === self::INDEX ? 'es' : 's')), ($class ?? 'all classes') )); - } catch (\Exception $e) { + } catch (\Throwable $e) { $output->writeln('' . $e->getMessage() . ''); $isErrored = true; } @@ -99,15 +104,15 @@ protected function processDocumentProxy(SchemaManager $sm, $document) { $classMetadata = $this->getMetadataFactory()->getMetadataFor($document); - if (!$classMetadata->isEmbeddedDocument && !$classMetadata->isMappedSuperclass && !$classMetadata->isQueryResultDocument) { - $this->getDocumentManager()->getProxyFactory()->generateProxyClasses(array($classMetadata)); + if (! $classMetadata->isEmbeddedDocument && ! $classMetadata->isMappedSuperclass && ! $classMetadata->isQueryResultDocument) { + $this->getDocumentManager()->getProxyFactory()->generateProxyClasses([$classMetadata]); } } protected function processProxy(SchemaManager $sm) { $classes = array_filter($this->getMetadataFactory()->getAllMetadata(), function (ClassMetadata $classMetadata) { - return !$classMetadata->isEmbeddedDocument && !$classMetadata->isMappedSuperclass && !$classMetadata->isQueryResultDocument; + return ! $classMetadata->isEmbeddedDocument && ! $classMetadata->isMappedSuperclass && ! $classMetadata->isQueryResultDocument; }); $this->getDocumentManager()->getProxyFactory()->generateProxyClasses($classes); diff --git a/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/Schema/DropCommand.php b/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/Schema/DropCommand.php index f5c099d418..e09d437dec 100644 --- a/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/Schema/DropCommand.php +++ b/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/Schema/DropCommand.php @@ -1,15 +1,20 @@ writeln(sprintf( 'Dropped %s%s for %s', $option, - (isset($class) ? (self::INDEX === $option ? '(es)' : '') : (self::INDEX === $option ? 'es' : 's')), + (isset($class) ? ($option === self::INDEX ? '(es)' : '') : ($option === self::INDEX ? 'es' : 's')), ($class ?? 'all classes') )); - } catch (\Exception $e) { + } catch (\Throwable $e) { $output->writeln('' . $e->getMessage() . ''); $isErrored = true; } diff --git a/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/Schema/ShardCommand.php b/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/Schema/ShardCommand.php index e95921e122..be3d959209 100644 --- a/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/Schema/ShardCommand.php +++ b/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/Schema/ShardCommand.php @@ -1,11 +1,14 @@ processIndex($sm); $output->writeln('Enabled sharding for all classes'); } - } catch (\Exception $e) { + } catch (\Throwable $e) { $output->writeln('' . $e->getMessage() . ''); $isErrored = true; } @@ -47,7 +48,6 @@ protected function execute(InputInterface $input, OutputInterface $output) } /** - * @param SchemaManager $sm * @param object $document */ protected function processDocumentIndex(SchemaManager $sm, $document) @@ -55,16 +55,12 @@ protected function processDocumentIndex(SchemaManager $sm, $document) $sm->ensureDocumentSharding($document); } - /** - * @param SchemaManager $sm - */ protected function processIndex(SchemaManager $sm) { $sm->ensureSharding(); } /** - * @param SchemaManager $sm * @param object $document * @throws \BadMethodCallException */ @@ -74,7 +70,6 @@ protected function processDocumentCollection(SchemaManager $sm, $document) } /** - * @param SchemaManager $sm * @throws \BadMethodCallException */ protected function processCollection(SchemaManager $sm) @@ -83,7 +78,6 @@ protected function processCollection(SchemaManager $sm) } /** - * @param SchemaManager $sm * @param object $document * @throws \BadMethodCallException */ @@ -93,7 +87,6 @@ protected function processDocumentDb(SchemaManager $sm, $document) } /** - * @param SchemaManager $sm * @throws \BadMethodCallException */ protected function processDb(SchemaManager $sm) diff --git a/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/Schema/UpdateCommand.php b/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/Schema/UpdateCommand.php index fafd67ab16..bf177ba8f0 100644 --- a/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/Schema/UpdateCommand.php +++ b/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/Schema/UpdateCommand.php @@ -1,11 +1,14 @@ processIndex($sm); $output->writeln('Updated indexes for all classes'); } - } catch (\Exception $e) { + } catch (\Throwable $e) { $output->writeln('' . $e->getMessage() . ''); $isErrored = true; } @@ -53,7 +54,6 @@ protected function execute(InputInterface $input, OutputInterface $output) } /** - * @param SchemaManager $sm * @param object $document */ protected function processDocumentIndex(SchemaManager $sm, $document) @@ -61,16 +61,12 @@ protected function processDocumentIndex(SchemaManager $sm, $document) $sm->updateDocumentIndexes($document, $this->timeout); } - /** - * @param SchemaManager $sm - */ protected function processIndex(SchemaManager $sm) { $sm->updateIndexes($this->timeout); } /** - * @param SchemaManager $sm * @param object $document * @throws \BadMethodCallException */ @@ -80,7 +76,6 @@ protected function processDocumentCollection(SchemaManager $sm, $document) } /** - * @param SchemaManager $sm * @throws \BadMethodCallException */ protected function processCollection(SchemaManager $sm) @@ -89,7 +84,6 @@ protected function processCollection(SchemaManager $sm) } /** - * @param SchemaManager $sm * @param object $document * @throws \BadMethodCallException */ @@ -99,7 +93,6 @@ protected function processDocumentDb(SchemaManager $sm, $document) } /** - * @param SchemaManager $sm * @throws \BadMethodCallException */ protected function processDb(SchemaManager $sm) diff --git a/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/Schema/ValidateCommand.php b/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/Schema/ValidateCommand.php index 0fe1e3c907..144e3e2c1e 100644 --- a/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/Schema/ValidateCommand.php +++ b/lib/Doctrine/ODM/MongoDB/Tools/Console/Command/Schema/ValidateCommand.php @@ -1,53 +1,58 @@ -setName('odm:schema:validate') - ->setDescription('Validates if document mapping stays the same after serializing into cache.') - ->setDefinition(array()) - ->setHelp(<<getHelper('documentManager')->getDocumentManager(); - $metadataFactory = $dm->getMetadataFactory(); - $metadataFactory->setCacheDriver(new VoidCache()); - - $errors = 0; - foreach ($metadataFactory->getAllMetadata() as $meta) { - if ($meta != unserialize(serialize($meta))) { - ++$errors; - $output->writeln(sprintf("%s has mapping issues.", $meta->name)); - } - } - if ($errors) { - $output->writeln(sprintf('%d document(s) have mapping issues.', $errors)); - } else { - $output->writeln('All documents are OK!'); - } - - return $errors ? 255 : 0; - } -} +setName('odm:schema:validate') + ->setDescription('Validates if document mapping stays the same after serializing into cache.') + ->setDefinition([]) + ->setHelp(<<getHelper('documentManager')->getDocumentManager(); + $metadataFactory = $dm->getMetadataFactory(); + $metadataFactory->setCacheDriver(new VoidCache()); + + $errors = 0; + foreach ($metadataFactory->getAllMetadata() as $meta) { + if ($meta !== unserialize(serialize($meta))) { + ++$errors; + $output->writeln(sprintf('%s has mapping issues.', $meta->name)); + } + } + if ($errors) { + $output->writeln(sprintf('%d document(s) have mapping issues.', $errors)); + } else { + $output->writeln('All documents are OK!'); + } + + return $errors ? 255 : 0; + } +} diff --git a/lib/Doctrine/ODM/MongoDB/Tools/Console/Helper/DocumentManagerHelper.php b/lib/Doctrine/ODM/MongoDB/Tools/Console/Helper/DocumentManagerHelper.php index 2bc2f4770b..e1f608ac1f 100644 --- a/lib/Doctrine/ODM/MongoDB/Tools/Console/Helper/DocumentManagerHelper.php +++ b/lib/Doctrine/ODM/MongoDB/Tools/Console/Helper/DocumentManagerHelper.php @@ -1,5 +1,7 @@ dm = $dm; diff --git a/lib/Doctrine/ODM/MongoDB/Tools/Console/MetadataFilter.php b/lib/Doctrine/ODM/MongoDB/Tools/Console/MetadataFilter.php index 6ba3a183e3..96a2d81221 100644 --- a/lib/Doctrine/ODM/MongoDB/Tools/Console/MetadataFilter.php +++ b/lib/Doctrine/ODM/MongoDB/Tools/Console/MetadataFilter.php @@ -1,18 +1,23 @@ _filter) == 0) { + if (count($this->_filter) === 0) { return true; } diff --git a/lib/Doctrine/ODM/MongoDB/Tools/ResolveTargetDocumentListener.php b/lib/Doctrine/ODM/MongoDB/Tools/ResolveTargetDocumentListener.php index 12985b10f8..912b9d1933 100644 --- a/lib/Doctrine/ODM/MongoDB/Tools/ResolveTargetDocumentListener.php +++ b/lib/Doctrine/ODM/MongoDB/Tools/ResolveTargetDocumentListener.php @@ -1,9 +1,13 @@ resolveTargetDocuments[ltrim($originalDocument, "\\")] = $mapping; + $mapping['targetDocument'] = ltrim($newDocument, '\\'); + $this->resolveTargetDocuments[ltrim($originalDocument, '\\')] = $mapping; } /** * Process event and resolve new target document names. * - * @param LoadClassMetadataEventArgs $args - * @return void */ public function loadClassMetadata(LoadClassMetadataEventArgs $args) { @@ -49,7 +50,6 @@ public function loadClassMetadata(LoadClassMetadataEventArgs $args) } /** - * @param ClassMetadata $classMetadata * @param array $mapping */ private function remapAssociation(ClassMetadata $classMetadata, array $mapping) diff --git a/lib/Doctrine/ODM/MongoDB/Types/BinDataByteArrayType.php b/lib/Doctrine/ODM/MongoDB/Types/BinDataByteArrayType.php index b581b86fa2..5b57833d5b 100644 --- a/lib/Doctrine/ODM/MongoDB/Types/BinDataByteArrayType.php +++ b/lib/Doctrine/ODM/MongoDB/Types/BinDataByteArrayType.php @@ -1,16 +1,19 @@ binDataType); + if (! $value instanceof Binary) { + return new Binary($value, $this->binDataType); } if ($value->getType() !== $this->binDataType) { - return new \MongoDB\BSON\Binary($value->getData(), $this->binDataType); + return new Binary($value->getData(), $this->binDataType); } return $value; @@ -36,7 +40,7 @@ public function convertToDatabaseValue($value) public function convertToPHPValue($value) { - return $value !== null ? ($value instanceof \MongoDB\BSON\Binary ? $value->getData() : $value) : null; + return $value !== null ? ($value instanceof Binary ? $value->getData() : $value) : null; } public function closureToMongo() diff --git a/lib/Doctrine/ODM/MongoDB/Types/BinDataUUIDRFC4122Type.php b/lib/Doctrine/ODM/MongoDB/Types/BinDataUUIDRFC4122Type.php index 6c2d3ce671..496fbb56f9 100644 --- a/lib/Doctrine/ODM/MongoDB/Types/BinDataUUIDRFC4122Type.php +++ b/lib/Doctrine/ODM/MongoDB/Types/BinDataUUIDRFC4122Type.php @@ -1,13 +1,16 @@ toDateTime(); $datetime->setTimezone(new \DateTimeZone(date_default_timezone_get())); } elseif (is_numeric($value)) { $seconds = $value; + $value = (string) $value; $microseconds = 0; - if (false !== strpos($value, '.')) { + if (strpos($value, '.') !== false) { list($seconds, $microseconds) = explode('.', $value); $microseconds = str_pad($microseconds, 6, '0'); // ensure microseconds } - $datetime = static::craftDateTime($seconds, $microseconds); + $datetime = static::craftDateTime((int) $seconds, $microseconds); } elseif (is_string($value)) { try { $datetime = new \DateTime($value); - } catch (\Exception $e) { + } catch (\Throwable $e) { $exception = $e; } } if ($datetime === false) { - throw new \InvalidArgumentException(sprintf('Could not convert %s to a date value', is_scalar($value) ? '"'.$value.'"' : gettype($value)), 0, $exception); + throw new \InvalidArgumentException(sprintf('Could not convert %s to a date value', is_scalar($value) ? '"' . $value . '"' : gettype($value)), 0, $exception); } return $datetime; } - private static function craftDateTime($seconds, $microseconds = 0) + // @todo fix typing for $microseconds + private static function craftDateTime(int $seconds, $microseconds = 0) { $datetime = new \DateTime(); $datetime->setTimestamp($seconds); @@ -65,13 +80,13 @@ private static function craftDateTime($seconds, $microseconds = 0) public function convertToDatabaseValue($value) { - if ($value === null || $value instanceof \MongoDB\BSON\UTCDateTime) { + if ($value === null || $value instanceof UTCDateTime) { return $value; } $datetime = static::getDateTime($value); - return new \MongoDB\BSON\UTCDateTime((int) $datetime->format('Uv')); + return new UTCDateTime((int) $datetime->format('Uv')); } public function convertToPHPValue($value) @@ -85,11 +100,11 @@ public function convertToPHPValue($value) public function closureToMongo() { - return 'if ($value === null || $value instanceof \MongoDB\BSON\UTCDateTime) { $return = $value; } else { $datetime = \\'.get_class($this).'::getDateTime($value); $return = new \MongoDB\BSON\UTCDateTime((int) $datetime->format(\'Uv\')); }'; + return 'if ($value === null || $value instanceof \MongoDB\BSON\UTCDateTime) { $return = $value; } else { $datetime = \\' . get_class($this) . '::getDateTime($value); $return = new \MongoDB\BSON\UTCDateTime((int) $datetime->format(\'Uv\')); }'; } public function closureToPHP() { - return 'if ($value === null) { $return = null; } else { $return = \\'.get_class($this).'::getDateTime($value); }'; + return 'if ($value === null) { $return = null; } else { $return = \\' . get_class($this) . '::getDateTime($value); }'; } } diff --git a/lib/Doctrine/ODM/MongoDB/Types/FileType.php b/lib/Doctrine/ODM/MongoDB/Types/FileType.php index 5e3ca82e94..284351d1dc 100644 --- a/lib/Doctrine/ODM/MongoDB/Types/FileType.php +++ b/lib/Doctrine/ODM/MongoDB/Types/FileType.php @@ -1,11 +1,12 @@ Types\IdType::class, self::INTID => Types\IntIdType::class, self::CUSTOMID => Types\CustomIdType::class, @@ -64,10 +73,12 @@ abstract class Type self::COLLECTION => Types\CollectionType::class, self::OBJECTID => Types\ObjectIdType::class, self::RAW => Types\RawType::class, - ); + ]; /* Prevent instantiation and force use of the factory method. */ - final private function __construct() {} + final private function __construct() + { + } /** * Converts a value from its PHP representation to its database representation @@ -106,7 +117,7 @@ public function closureToPHP() /** * Register a new type in the type map. * - * @param string $name The name of the type. + * @param string $name The name of the type. * @param string $class The class name. */ public static function registerType($name, $class) @@ -123,12 +134,12 @@ public static function registerType($name, $class) */ public static function getType($type) { - if ( ! isset(self::$typesMap[$type])) { + if (! isset(self::$typesMap[$type])) { throw new \InvalidArgumentException(sprintf('Invalid type specified "%s".', $type)); } - if ( ! isset(self::$typeObjects[$type])) { + if (! isset(self::$typeObjects[$type])) { $className = self::$typesMap[$type]; - self::$typeObjects[$type] = new $className; + self::$typeObjects[$type] = new $className(); } return self::$typeObjects[$type]; } @@ -145,7 +156,7 @@ public static function getTypeFromPHPVariable($variable) if (is_object($variable)) { if ($variable instanceof \DateTimeInterface) { return self::getType('date'); - } elseif ($variable instanceof \MongoDB\BSON\ObjectId) { + } elseif ($variable instanceof ObjectId) { return self::getType('id'); } } else { @@ -171,7 +182,7 @@ public static function convertPHPToDatabaseValue($value) * Adds a custom type to the type map. * * @static - * @param string $name Name of the type. This should correspond to what getName() returns. + * @param string $name Name of the type. This should correspond to what getName() returns. * @param string $className The class name of the custom type. * @throws MappingException */ @@ -189,7 +200,7 @@ public static function addType($name, $className) * * @static * @param string $name Name of the type - * @return boolean TRUE if type is supported; FALSE otherwise + * @return bool TRUE if type is supported; FALSE otherwise */ public static function hasType($name) { @@ -206,7 +217,7 @@ public static function hasType($name) */ public static function overrideType($name, $className) { - if ( ! isset(self::$typesMap[$name])) { + if (! isset(self::$typesMap[$name])) { throw MappingException::typeNotFound($name); } diff --git a/lib/Doctrine/ODM/MongoDB/UnitOfWork.php b/lib/Doctrine/ODM/MongoDB/UnitOfWork.php index 2c136a87ce..c066b26600 100644 --- a/lib/Doctrine/ODM/MongoDB/UnitOfWork.php +++ b/lib/Doctrine/ODM/MongoDB/UnitOfWork.php @@ -1,5 +1,7 @@ persistenceBuilder) { + if (! $this->persistenceBuilder) { $this->persistenceBuilder = new PersistenceBuilder($this->dm, $this); } return $this->persistenceBuilder; @@ -280,7 +292,7 @@ public function getPersistenceBuilder() * Sets the parent association for a given embedded document. * * @param object $document - * @param array $mapping + * @param array $mapping * @param object $parent * @param string $propertyPath */ @@ -288,7 +300,7 @@ public function setParentAssociation($document, $mapping, $parent, $propertyPath { $oid = spl_object_hash($document); $this->embeddedDocumentsRegistry[$oid] = $document; - $this->parentAssociations[$oid] = array($mapping, $parent, $propertyPath); + $this->parentAssociations[$oid] = [$mapping, $parent, $propertyPath]; } /** @@ -316,7 +328,7 @@ public function getParentAssociation($document) */ public function getDocumentPersister($documentName) { - if ( ! isset($this->persisters[$documentName])) { + if (! isset($this->persisters[$documentName])) { $class = $this->dm->getClassMetadata($documentName); $pb = $this->getPersistenceBuilder(); $this->persisters[$documentName] = new Persisters\DocumentPersister($pb, $this->dm, $this->evm, $this, $this->hydratorFactory, $class); @@ -327,11 +339,11 @@ public function getDocumentPersister($documentName) /** * Get the collection persister instance. * - * @return \Doctrine\ODM\MongoDB\Persisters\CollectionPersister + * @return CollectionPersister */ public function getCollectionPersister() { - if ( ! isset($this->collectionPersister)) { + if (! isset($this->collectionPersister)) { $pb = $this->getPersistenceBuilder(); $this->collectionPersister = new Persisters\CollectionPersister($this->dm, $pb, $this); } @@ -342,7 +354,6 @@ public function getCollectionPersister() * Set the document persister instance to use for the given document name * * @param string $documentName - * @param Persisters\DocumentPersister $persister */ public function setDocumentPersister($documentName, Persisters\DocumentPersister $persister) { @@ -362,7 +373,7 @@ public function setDocumentPersister($documentName, Persisters\DocumentPersister * * @param array $options Array of options to be used with batchInsert(), update() and remove() */ - public function commit(array $options = array()) + public function commit(array $options = []) { // Raise preFlush if ($this->evm->hasListeners(Events::preFlush)) { @@ -372,7 +383,7 @@ public function commit(array $options = array()) // Compute changes done since last commit. $this->computeChangeSets(); - if ( ! ($this->documentInsertions || + if (! ($this->documentInsertions || $this->documentUpserts || $this->documentDeletions || $this->documentUpdates || @@ -435,7 +446,7 @@ public function commit(array $options = array()) $this->visitedCollections = $this->scheduledForDirtyCheck = $this->orphanRemovals = - $this->hasScheduledCollections = array(); + $this->hasScheduledCollections = []; } finally { $this->commitsInProgress--; } @@ -444,17 +455,17 @@ public function commit(array $options = array()) /** * Groups a list of scheduled documents by their class. * - * @param array $documents Scheduled documents (e.g. $this->documentInsertions) - * @param bool $includeEmbedded + * @param array $documents Scheduled documents (e.g. $this->documentInsertions) + * @param bool $includeEmbedded * @return array Tuples of ClassMetadata and a corresponding array of objects */ private function getClassesForCommitAction($documents, $includeEmbedded = false) { if (empty($documents)) { - return array(); + return []; } - $divided = array(); - $embeds = array(); + $divided = []; + $embeds = []; foreach ($documents as $oid => $d) { $className = get_class($d); if (isset($embeds[$className])) { @@ -470,7 +481,7 @@ private function getClassesForCommitAction($documents, $includeEmbedded = false) continue; } if (empty($divided[$class->name])) { - $divided[$class->name] = array($class, array($oid => $d)); + $divided[$class->name] = [$class, [$oid => $d]]; } else { $divided[$class->name][1][$oid] = $d; } @@ -487,7 +498,7 @@ private function computeScheduleInsertsChangeSets() { foreach ($this->documentInsertions as $document) { $class = $this->dm->getClassMetadata(get_class($document)); - if ( ! $class->isEmbeddedDocument) { + if (! $class->isEmbeddedDocument) { $this->computeChangeSet($class, $document); } } @@ -502,7 +513,7 @@ private function computeScheduleUpsertsChangeSets() { foreach ($this->documentUpserts as $document) { $class = $this->dm->getClassMetadata(get_class($document)); - if ( ! $class->isEmbeddedDocument) { + if (! $class->isEmbeddedDocument) { $this->computeChangeSet($class, $document); } } @@ -518,7 +529,7 @@ public function getDocumentChangeSet($document) { $oid = spl_object_hash($document); - return $this->documentChangeSets[$oid] ?? array(); + return $this->documentChangeSets[$oid] ?? []; } /** @@ -526,7 +537,7 @@ public function getDocumentChangeSet($document) * Sets the changeset for a document. * * @param object $document - * @param array $changeset + * @param array $changeset */ public function setDocumentChangeSet($document, $changeset) { @@ -542,7 +553,7 @@ public function setDocumentChangeSet($document, $changeset) public function getDocumentActualData($document) { $class = $this->dm->getClassMetadata(get_class($document)); - $actualData = array(); + $actualData = []; foreach ($class->reflFields as $name => $refProp) { $mapping = $class->fieldMappings[$name]; // skip not saved fields @@ -553,14 +564,14 @@ public function getDocumentActualData($document) if ((isset($mapping['association']) && $mapping['type'] === 'many') && $value !== null && ! ($value instanceof PersistentCollectionInterface)) { // If $actualData[$name] is not a Collection then use an ArrayCollection. - if ( ! $value instanceof Collection) { + if (! $value instanceof Collection) { $value = new ArrayCollection($value); } // Inject PersistentCollection $coll = $this->dm->getConfiguration()->getPersistentCollectionFactory()->create($this->dm, $mapping, $value); $coll->setOwner($document, $mapping); - $coll->setDirty( ! $value->isEmpty()); + $coll->setDirty(! $value->isEmpty()); $class->reflFields[$name]->setValue($document, $coll); $actualData[$name] = $coll; } else { @@ -591,18 +602,18 @@ public function getDocumentActualData($document) * and any changes to its properties are detected, then a reference to the document is stored * there to mark it for an update. * - * @param ClassMetadata $class The class descriptor of the document. - * @param object $document The document for which to compute the changes. + * @param ClassMetadata $class The class descriptor of the document. + * @param object $document The document for which to compute the changes. */ public function computeChangeSet(ClassMetadata $class, $document) { - if ( ! $class->isInheritanceTypeNone()) { + if (! $class->isInheritanceTypeNone()) { $class = $this->dm->getClassMetadata(get_class($document)); } // Fire PreFlush lifecycle callbacks - if ( ! empty($class->lifecycleCallbacks[Events::preFlush])) { - $class->invokeLifecycleCallbacks(Events::preFlush, $document, array(new Event\PreFlushEventArgs($this->dm))); + if (! empty($class->lifecycleCallbacks[Events::preFlush])) { + $class->invokeLifecycleCallbacks(Events::preFlush, $document, [new Event\PreFlushEventArgs($this->dm)]); } $this->computeOrRecomputeChangeSet($class, $document); @@ -611,9 +622,8 @@ public function computeChangeSet(ClassMetadata $class, $document) /** * Used to do the common work of computeChangeSet and recomputeSingleDocumentChangeSet * - * @param \Doctrine\ODM\MongoDB\Mapping\ClassMetadata $class * @param object $document - * @param boolean $recompute + * @param bool $recompute */ private function computeOrRecomputeChangeSet(ClassMetadata $class, $document, $recompute = false) { @@ -624,7 +634,7 @@ private function computeOrRecomputeChangeSet(ClassMetadata $class, $document, $r // Document is either NEW or MANAGED but not yet fully persisted (only has an id). // These result in an INSERT. $this->originalDocumentData[$oid] = $actualData; - $changeSet = array(); + $changeSet = []; foreach ($actualData as $propName => $actualValue) { /* At this PersistentCollection shouldn't be here, probably it * was cloned and its ownership must be fixed @@ -637,7 +647,7 @@ private function computeOrRecomputeChangeSet(ClassMetadata $class, $document, $r if (isset($class->fieldMappings[$propName]['reference']) && $class->fieldMappings[$propName]['isInverseSide']) { continue; } - $changeSet[$propName] = array(null, $actualValue); + $changeSet[$propName] = [null, $actualValue]; } $this->documentChangeSets[$oid] = $changeSet; } else { @@ -651,7 +661,7 @@ private function computeOrRecomputeChangeSet(ClassMetadata $class, $document, $r if ($isChangeTrackingNotify && ! $recompute && isset($this->documentChangeSets[$oid])) { $changeSet = $this->documentChangeSets[$oid]; } else { - $changeSet = array(); + $changeSet = []; } foreach ($actualData as $propName => $actualValue) { @@ -664,7 +674,7 @@ private function computeOrRecomputeChangeSet(ClassMetadata $class, $document, $r // skip if value has not changed if ($orgValue === $actualValue) { - if (!$actualValue instanceof PersistentCollectionInterface) { + if (! $actualValue instanceof PersistentCollectionInterface) { continue; } @@ -679,7 +689,7 @@ private function computeOrRecomputeChangeSet(ClassMetadata $class, $document, $r if ($orgValue !== null) { $this->scheduleOrphanRemoval($orgValue); } - $changeSet[$propName] = array($orgValue, $actualValue); + $changeSet[$propName] = [$orgValue, $actualValue]; continue; } @@ -689,7 +699,7 @@ private function computeOrRecomputeChangeSet(ClassMetadata $class, $document, $r $this->scheduleOrphanRemoval($orgValue); } - $changeSet[$propName] = array($orgValue, $actualValue); + $changeSet[$propName] = [$orgValue, $actualValue]; continue; } @@ -711,7 +721,7 @@ private function computeOrRecomputeChangeSet(ClassMetadata $class, $document, $r // if embed-many or reference-many relationship if (isset($class->fieldMappings[$propName]['type']) && $class->fieldMappings[$propName]['type'] === 'many') { - $changeSet[$propName] = array($orgValue, $actualValue); + $changeSet[$propName] = [$orgValue, $actualValue]; /* If original collection was exchanged with a non-empty value * and $set will be issued, there is no need to $unset it first */ @@ -726,17 +736,21 @@ private function computeOrRecomputeChangeSet(ClassMetadata $class, $document, $r // skip equivalent date values if (isset($class->fieldMappings[$propName]['type']) && $class->fieldMappings[$propName]['type'] === 'date') { + /** @var DateType $dateType */ $dateType = Type::getType('date'); $dbOrgValue = $dateType->convertToDatabaseValue($orgValue); $dbActualValue = $dateType->convertToDatabaseValue($actualValue); - if ($dbOrgValue instanceof \MongoDB\BSON\UTCDateTime && $dbActualValue instanceof \MongoDB\BSON\UTCDateTime && $dbOrgValue == $dbActualValue) { + $orgTimestamp = $dbOrgValue instanceof UTCDateTime ? $dbOrgValue->toDateTime()->getTimestamp() : null; + $actualTimestamp = $dbActualValue instanceof UTCDateTime ? $dbActualValue->toDateTime()->getTimestamp() : null; + + if ($orgTimestamp === $actualTimestamp) { continue; } } // regular field - $changeSet[$propName] = array($orgValue, $actualValue); + $changeSet[$propName] = [$orgValue, $actualValue]; } if ($changeSet) { $this->documentChangeSets[$oid] = isset($this->documentChangeSets[$oid]) @@ -751,7 +765,9 @@ private function computeOrRecomputeChangeSet(ClassMetadata $class, $document, $r // Look for changes in associations of the document $associationMappings = array_filter( $class->associationMappings, - function ($assoc) { return empty($assoc['notSaved']); } + function ($assoc) { + return empty($assoc['notSaved']); + } ); foreach ($associationMappings as $mapping) { @@ -767,7 +783,7 @@ function ($assoc) { return empty($assoc['notSaved']); } continue; } - $values = $mapping['type'] === ClassMetadata::ONE ? array($value) : $value->unwrap(); + $values = $mapping['type'] === ClassMetadata::ONE ? [$value] : $value->unwrap(); foreach ($values as $obj) { $oid2 = spl_object_hash($obj); @@ -776,10 +792,10 @@ function ($assoc) { return empty($assoc['notSaved']); } if (empty($this->documentChangeSets[$oid][$mapping['fieldName']])) { // instance of $value is the same as it was previously otherwise there would be // change set already in place - $this->documentChangeSets[$oid][$mapping['fieldName']] = array($value, $value); + $this->documentChangeSets[$oid][$mapping['fieldName']] = [$value, $value]; } - if ( ! $isNewDocument) { + if (! $isNewDocument) { $this->scheduleForUpdate($document); } @@ -823,8 +839,7 @@ public function computeChangeSets() break; default: - $documentsToProcess = array(); - + $documentsToProcess = []; } foreach ($documentsToProcess as $document) { @@ -834,7 +849,7 @@ public function computeChangeSets() } // Only MANAGED documents that are NOT SCHEDULED FOR INSERTION, UPSERT OR DELETION are processed here. $oid = spl_object_hash($document); - if ( ! isset($this->documentInsertions[$oid]) + if (! isset($this->documentInsertions[$oid]) && ! isset($this->documentUpserts[$oid]) && ! isset($this->documentDeletions[$oid]) && isset($this->documentStates[$oid]) @@ -849,8 +864,8 @@ public function computeChangeSets() * Computes the changes of an association. * * @param object $parentDocument - * @param array $assoc - * @param mixed $value The value of the association. + * @param array $assoc + * @param mixed $value The value of the association. * @throws \InvalidArgumentException */ private function computeAssociationChanges($parentDocument, array $assoc, $value) @@ -869,7 +884,7 @@ private function computeAssociationChanges($parentDocument, array $assoc, $value } $topmostOwner = $this->getOwningDocument($value->getOwner()); $this->visitedCollections[spl_object_hash($topmostOwner)][] = $value; - if ( ! empty($assoc['orphanRemoval']) || isset($assoc['embedded'])) { + if (! empty($assoc['orphanRemoval']) || isset($assoc['embedded'])) { $value->initialize(); foreach ($value->getDeletedDocuments() as $orphan) { $this->scheduleOrphanRemoval($orphan); @@ -880,13 +895,13 @@ private function computeAssociationChanges($parentDocument, array $assoc, $value // Look through the documents, and in any of their associations, // for transient (new) documents, recursively. ("Persistence by reachability") // Unwrap. Uninitialized collections will simply be empty. - $unwrappedValue = ($assoc['type'] === ClassMetadata::ONE) ? array($value) : $value->unwrap(); + $unwrappedValue = ($assoc['type'] === ClassMetadata::ONE) ? [$value] : $value->unwrap(); $count = 0; foreach ($unwrappedValue as $key => $entry) { - if ( ! is_object($entry)) { + if (! is_object($entry)) { throw new \InvalidArgumentException( - sprintf('Expected object, found "%s" in %s::%s', $entry, get_class($parentDocument), $assoc['name']) + sprintf('Expected object, found "%s" in %s::%s', $entry, get_class($parentDocument), $assoc['name']) ); } @@ -902,7 +917,7 @@ private function computeAssociationChanges($parentDocument, array $assoc, $value switch ($state) { case self::STATE_NEW: - if ( ! $assoc['isCascadePersist']) { + if (! $assoc['isCascadePersist']) { throw new \InvalidArgumentException('A new document was found through a relationship that was not' . ' configured to cascade persist operations: ' . $this->objToStr($entry) . '.' . ' Explicitly persist the new document or configure cascading persist operations' @@ -954,7 +969,6 @@ private function computeAssociationChanges($parentDocument, array $assoc, $value default: // MANAGED associated documents are already taken into account // during changeset calculation anyway, since they are in the identity map. - } } } @@ -969,8 +983,8 @@ private function computeAssociationChanges($parentDocument, array $assoc, $value * whereby changes detected in this method prevail. * * @ignore - * @param ClassMetadata $class The class descriptor of the document. - * @param object $document The document for which to (re)calculate the change set. + * @param ClassMetadata $class The class descriptor of the document. + * @param object $document The document for which to (re)calculate the change set. * @throws \InvalidArgumentException If the passed document is not MANAGED. */ public function recomputeSingleDocumentChangeSet(ClassMetadata $class, $document) @@ -982,11 +996,11 @@ public function recomputeSingleDocumentChangeSet(ClassMetadata $class, $document $oid = spl_object_hash($document); - if ( ! isset($this->documentStates[$oid]) || $this->documentStates[$oid] != self::STATE_MANAGED) { + if (! isset($this->documentStates[$oid]) || $this->documentStates[$oid] !== self::STATE_MANAGED) { throw new \InvalidArgumentException('Document must be managed.'); } - if ( ! $class->isInheritanceTypeNone()) { + if (! $class->isInheritanceTypeNone()) { $class = $this->dm->getClassMetadata(get_class($document)); } @@ -994,7 +1008,6 @@ public function recomputeSingleDocumentChangeSet(ClassMetadata $class, $document } /** - * @param ClassMetadata $class * @param object $document * @throws \InvalidArgumentException If there is something wrong with document's identifier. */ @@ -1014,7 +1027,7 @@ private function persistNew(ClassMetadata $class, $document) )); } - if ($class->generatorType === ClassMetadata::GENERATOR_TYPE_AUTO && $idValue !== null && ! preg_match('#^[0-9a-f]{24}$#', $idValue)) { + if ($class->generatorType === ClassMetadata::GENERATOR_TYPE_AUTO && $idValue !== null && ! preg_match('#^[0-9a-f]{24}$#', (string) $idValue)) { throw new \InvalidArgumentException(sprintf( '%s uses AUTO identifier generation strategy but provided identifier is not a valid ObjectId.', get_class($document) @@ -1045,11 +1058,10 @@ private function persistNew(ClassMetadata $class, $document) /** * Executes all document insertions for documents of the specified type. * - * @param ClassMetadata $class * @param array $documents Array of documents to insert - * @param array $options Array of options to be used with batchInsert() + * @param array $options Array of options to be used with batchInsert() */ - private function executeInserts(ClassMetadata $class, array $documents, array $options = array()) + private function executeInserts(ClassMetadata $class, array $documents, array $options = []) { $persister = $this->getDocumentPersister($class->name); @@ -1068,15 +1080,13 @@ private function executeInserts(ClassMetadata $class, array $documents, array $o /** * Executes all document upserts for documents of the specified type. * - * @param ClassMetadata $class * @param array $documents Array of documents to upsert - * @param array $options Array of options to be used with batchInsert() + * @param array $options Array of options to be used with batchInsert() */ - private function executeUpserts(ClassMetadata $class, array $documents, array $options = array()) + private function executeUpserts(ClassMetadata $class, array $documents, array $options = []) { $persister = $this->getDocumentPersister($class->name); - foreach ($documents as $oid => $document) { $persister->addUpsert($document); unset($this->documentUpserts[$oid]); @@ -1092,11 +1102,10 @@ private function executeUpserts(ClassMetadata $class, array $documents, array $o /** * Executes all document updates for documents of the specified type. * - * @param Mapping\ClassMetadata $class * @param array $documents Array of documents to update - * @param array $options Array of options to be used with update() + * @param array $options Array of options to be used with update() */ - private function executeUpdates(ClassMetadata $class, array $documents, array $options = array()) + private function executeUpdates(ClassMetadata $class, array $documents, array $options = []) { if ($class->isReadOnly) { return; @@ -1108,7 +1117,7 @@ private function executeUpdates(ClassMetadata $class, array $documents, array $o foreach ($documents as $oid => $document) { $this->lifecycleEventManager->preUpdate($class, $document); - if ( ! empty($this->documentChangeSets[$oid]) || $this->hasScheduledCollections($document)) { + if (! empty($this->documentChangeSets[$oid]) || $this->hasScheduledCollections($document)) { $persister->update($document, $options); } @@ -1121,16 +1130,15 @@ private function executeUpdates(ClassMetadata $class, array $documents, array $o /** * Executes all document deletions for documents of the specified type. * - * @param ClassMetadata $class * @param array $documents Array of documents to delete - * @param array $options Array of options to be used with remove() + * @param array $options Array of options to be used with remove() */ - private function executeDeletions(ClassMetadata $class, array $documents, array $options = array()) + private function executeDeletions(ClassMetadata $class, array $documents, array $options = []) { $persister = $this->getDocumentPersister($class->name); foreach ($documents as $oid => $document) { - if ( ! $class->isEmbeddedDocument) { + if (! $class->isEmbeddedDocument) { $persister->delete($document, $options); } unset( @@ -1163,7 +1171,6 @@ private function executeDeletions(ClassMetadata $class, array $documents, array * If the document already has an identifier, it will be added to the * identity map. * - * @param ClassMetadata $class * @param object $document The document to schedule for insertion. * @throws \InvalidArgumentException */ @@ -1192,7 +1199,6 @@ public function scheduleForInsert(ClassMetadata $class, $document) * Schedules a document for upsert into the database and adds it to the * identity map * - * @param ClassMetadata $class * @param object $document The document to schedule for upsert. * @throws \InvalidArgumentException */ @@ -1222,7 +1228,7 @@ public function scheduleForUpsert(ClassMetadata $class, $document) * Checks whether a document is scheduled for insertion. * * @param object $document - * @return boolean + * @return bool */ public function isScheduledForInsert($document) { @@ -1233,7 +1239,7 @@ public function isScheduledForInsert($document) * Checks whether a document is scheduled for upsert. * * @param object $document - * @return boolean + * @return bool */ public function isScheduledForUpsert($document) { @@ -1249,7 +1255,7 @@ public function isScheduledForUpsert($document) public function scheduleForUpdate($document) { $oid = spl_object_hash($document); - if ( ! isset($this->documentIdentifiers[$oid])) { + if (! isset($this->documentIdentifiers[$oid])) { throw new \InvalidArgumentException('Document has no identity.'); } @@ -1257,7 +1263,7 @@ public function scheduleForUpdate($document) throw new \InvalidArgumentException('Document is removed.'); } - if ( ! isset($this->documentUpdates[$oid]) + if (! isset($this->documentUpdates[$oid]) && ! isset($this->documentInsertions[$oid]) && ! isset($this->documentUpserts[$oid])) { $this->documentUpdates[$oid] = $document; @@ -1270,7 +1276,7 @@ public function scheduleForUpdate($document) * at commit time. * * @param object $document - * @return boolean + * @return bool */ public function isScheduledForUpdate($document) { @@ -1301,7 +1307,7 @@ public function scheduleForDelete($document) return; // document has not been persisted yet, so nothing more to do. } - if ( ! $this->isInIdentityMap($document)) { + if (! $this->isInIdentityMap($document)) { return; // ignore } @@ -1311,7 +1317,7 @@ public function scheduleForDelete($document) if (isset($this->documentUpdates[$oid])) { unset($this->documentUpdates[$oid]); } - if ( ! isset($this->documentDeletions[$oid])) { + if (! isset($this->documentDeletions[$oid])) { $this->documentDeletions[$oid] = $document; } } @@ -1321,7 +1327,7 @@ public function scheduleForDelete($document) * of work. * * @param object $document - * @return boolean + * @return bool */ public function isScheduledForDelete($document) { @@ -1332,7 +1338,7 @@ public function isScheduledForDelete($document) * Checks whether a document is scheduled for insertion, update or deletion. * * @param object $document - * @return boolean + * @return bool */ public function isDocumentScheduled($document) { @@ -1352,8 +1358,8 @@ public function isDocumentScheduled($document) * keys to allow differentiation of equal, but not identical, values. * * @ignore - * @param object $document The document to register. - * @return boolean TRUE if the registration was successful, FALSE if the identity of + * @param object $document The document to register. + * @return bool TRUE if the registration was successful, FALSE if the identity of * the document in question is already managed. */ public function addToIdentityMap($document) @@ -1379,10 +1385,10 @@ public function addToIdentityMap($document) * Gets the state of a document with regard to the current unit of work. * * @param object $document - * @param int|null $assume The state to assume if the state is not yet known (not MANAGED or REMOVED). - * This parameter can be set to improve performance of document state detection - * by potentially avoiding a database lookup if the distinction between NEW and DETACHED - * is either known or does not matter for the caller of the method. + * @param int|null $assume The state to assume if the state is not yet known (not MANAGED or REMOVED). + * This parameter can be set to improve performance of document state detection + * by potentially avoiding a database lookup if the distinction between NEW and DETACHED + * is either known or does not matter for the caller of the method. * @return int The document state. */ public function getDocumentState($document, $assume = null) @@ -1444,14 +1450,14 @@ public function getDocumentState($document, $assume = null) * @ignore * @param object $document * @throws \InvalidArgumentException - * @return boolean + * @return bool */ public function removeFromIdentityMap($document) { $oid = spl_object_hash($document); // Check if id is registered first - if ( ! isset($this->documentIdentifiers[$oid])) { + if (! isset($this->documentIdentifiers[$oid])) { return false; } @@ -1479,7 +1485,7 @@ public function removeFromIdentityMap($document) */ public function getById($id, ClassMetadata $class) { - if ( ! $class->identifier) { + if (! $class->identifier) { throw new \InvalidArgumentException(sprintf('Class "%s" does not have an identifier', $class->name)); } @@ -1501,7 +1507,7 @@ public function getById($id, ClassMetadata $class) */ public function tryGetById($id, ClassMetadata $class) { - if ( ! $class->identifier) { + if (! $class->identifier) { throw new \InvalidArgumentException(sprintf('Class "%s" does not have an identifier', $class->name)); } @@ -1526,13 +1532,13 @@ public function scheduleForDirtyCheck($document) * Checks whether a document is registered in the identity map. * * @param object $document - * @return boolean + * @return bool */ public function isInIdentityMap($document) { $oid = spl_object_hash($document); - if ( ! isset($this->documentIdentifiers[$oid])) { + if (! isset($this->documentIdentifiers[$oid])) { return false; } @@ -1550,7 +1556,7 @@ private function getIdForIdentityMap($document) { $class = $this->dm->getClassMetadata(get_class($document)); - if ( ! $class->identifier) { + if (! $class->identifier) { $id = spl_object_hash($document); } else { $id = $this->documentIdentifiers[spl_object_hash($document)]; @@ -1567,7 +1573,7 @@ private function getIdForIdentityMap($document) * @ignore * @param string $id * @param string $rootClassName - * @return boolean + * @return bool */ public function containsId($id, $rootClassName) { @@ -1587,7 +1593,7 @@ public function persist($document) if ($class->isMappedSuperclass || $class->isQueryResultDocument) { throw MongoDBException::cannotPersistMappedSuperclass($class->name); } - $visited = array(); + $visited = []; $this->doPersist($document, $visited); } @@ -1600,7 +1606,7 @@ public function persist($document) * this UnitOfWork as NEW. * * @param object $document The document to persist. - * @param array $visited The already visited documents. + * @param array $visited The already visited documents. * @throws \InvalidArgumentException * @throws MongoDBException */ @@ -1636,7 +1642,8 @@ private function doPersist($document, array &$visited) case self::STATE_DETACHED: throw new \InvalidArgumentException( - 'Behavior of persist() for a detached document is not yet defined.'); + 'Behavior of persist() for a detached document is not yet defined.' + ); default: throw MongoDBException::invalidDocumentState($documentState); @@ -1652,7 +1659,7 @@ private function doPersist($document, array &$visited) */ public function remove($document) { - $visited = array(); + $visited = []; $this->doRemove($document, $visited); } @@ -1663,7 +1670,7 @@ public function remove($document) * the already visited documents to prevent infinite recursions. * * @param object $document The document to delete. - * @param array $visited The map of the already visited documents. + * @param array $visited The map of the already visited documents. * @throws MongoDBException */ private function doRemove($document, array &$visited) @@ -1707,7 +1714,7 @@ private function doRemove($document, array &$visited) */ public function merge($document) { - $visited = array(); + $visited = []; return $this->doMerge($document, $visited); } @@ -1784,7 +1791,7 @@ private function doMerge($document, array &$visited, $prevManagedCopy = null, $a $documentVersion = $class->reflFields[$class->versionField]->getValue($document); // Throw exception if versions don't match - if ($managedCopyVersion != $documentVersion) { + if ($managedCopyVersion !== $documentVersion) { throw LockException::lockFailedVersionMissmatch($document, $documentVersion, $managedCopyVersion); } } @@ -1793,8 +1800,8 @@ private function doMerge($document, array &$visited, $prevManagedCopy = null, $a foreach ($class->reflClass->getProperties() as $prop) { $name = $prop->name; $prop->setAccessible(true); - if ( ! isset($class->associationMappings[$name])) { - if ( ! $class->isIdentifier($name)) { + if (! isset($class->associationMappings[$name])) { + if (! $class->isIdentifier($name)) { $prop->setValue($managedCopy, $prop->getValue($document)); } } else { @@ -1808,7 +1815,7 @@ private function doMerge($document, array &$visited, $prevManagedCopy = null, $a } elseif ($other instanceof Proxy && ! $other->__isInitialized__) { // Do not merge fields marked lazy that have not been fetched continue; - } elseif ( ! $assoc2['isCascadeMerge']) { + } elseif (! $assoc2['isCascadeMerge']) { if ($this->getDocumentState($other) === self::STATE_DETACHED) { $targetDocument = $assoc2['targetDocument'] ?? get_class($other); /* @var $targetClass \Doctrine\ODM\MongoDB\Mapping\ClassMetadata */ @@ -1821,8 +1828,8 @@ private function doMerge($document, array &$visited, $prevManagedCopy = null, $a $other = $this ->dm ->getProxyFactory() - ->getProxy($assoc2['targetDocument'], array($targetClass->identifier => $relatedId)); - $this->registerManaged($other, $relatedId, array()); + ->getProxy($assoc2['targetDocument'], [$targetClass->identifier => $relatedId]); + $this->registerManaged($other, $relatedId, []); } } @@ -1841,7 +1848,7 @@ private function doMerge($document, array &$visited, $prevManagedCopy = null, $a $managedCol = $prop->getValue($managedCopy); - if ( ! $managedCol) { + if (! $managedCol) { $managedCol = $this->dm->getConfiguration()->getPersistentCollectionFactory()->create($this->dm, $assoc2, null); $managedCol->setOwner($managedCopy, $assoc2); $prop->setValue($managedCopy, $managedCol); @@ -1856,7 +1863,7 @@ private function doMerge($document, array &$visited, $prevManagedCopy = null, $a $managedCol->initialize(); // If $managedCol differs from the merged collection, clear and set dirty - if ( ! $managedCol->isEmpty() && $managedCol !== $mergeCol) { + if (! $managedCol->isEmpty() && $managedCol !== $mergeCol) { $managedCol->unwrap()->clear(); $managedCol->setDirty(true); @@ -1910,7 +1917,7 @@ private function doMerge($document, array &$visited, $prevManagedCopy = null, $a */ public function detach($document) { - $visited = array(); + $visited = []; $this->doDetach($document, $visited); } @@ -1918,7 +1925,7 @@ public function detach($document) * Executes a detach operation on the given document. * * @param object $document - * @param array $visited + * @param array $visited * @internal This method always considers documents with an assigned identifier as DETACHED. */ private function doDetach($document, array &$visited) @@ -1933,11 +1940,18 @@ private function doDetach($document, array &$visited) switch ($this->getDocumentState($document, self::STATE_DETACHED)) { case self::STATE_MANAGED: $this->removeFromIdentityMap($document); - unset($this->documentInsertions[$oid], $this->documentUpdates[$oid], - $this->documentDeletions[$oid], $this->documentIdentifiers[$oid], - $this->documentStates[$oid], $this->originalDocumentData[$oid], - $this->parentAssociations[$oid], $this->documentUpserts[$oid], - $this->hasScheduledCollections[$oid], $this->embeddedDocumentsRegistry[$oid]); + unset( + $this->documentInsertions[$oid], + $this->documentUpdates[$oid], + $this->documentDeletions[$oid], + $this->documentIdentifiers[$oid], + $this->documentStates[$oid], + $this->originalDocumentData[$oid], + $this->parentAssociations[$oid], + $this->documentUpserts[$oid], + $this->hasScheduledCollections[$oid], + $this->embeddedDocumentsRegistry[$oid] + ); break; case self::STATE_NEW: case self::STATE_DETACHED: @@ -1956,7 +1970,7 @@ private function doDetach($document, array &$visited) */ public function refresh($document) { - $visited = array(); + $visited = []; $this->doRefresh($document, $visited); } @@ -1964,7 +1978,7 @@ public function refresh($document) * Executes a refresh operation on a document. * * @param object $document The document to refresh. - * @param array $visited The already visited documents during cascades. + * @param array $visited The already visited documents during cascades. * @throws \InvalidArgumentException If the document is not MANAGED. */ private function doRefresh($document, array &$visited) @@ -1978,8 +1992,8 @@ private function doRefresh($document, array &$visited) $class = $this->dm->getClassMetadata(get_class($document)); - if ( ! $class->isEmbeddedDocument) { - if ($this->getDocumentState($document) == self::STATE_MANAGED) { + if (! $class->isEmbeddedDocument) { + if ($this->getDocumentState($document) === self::STATE_MANAGED) { $this->getDocumentPersister($class->name)->refresh($document); } else { throw new \InvalidArgumentException('Document is not MANAGED.'); @@ -1993,7 +2007,7 @@ private function doRefresh($document, array &$visited) * Cascades a refresh operation to associated documents. * * @param object $document - * @param array $visited + * @param array $visited */ private function cascadeRefresh($document, array &$visited) { @@ -2001,7 +2015,9 @@ private function cascadeRefresh($document, array &$visited) $associationMappings = array_filter( $class->associationMappings, - function ($assoc) { return $assoc['isCascadeRefresh']; } + function ($assoc) { + return $assoc['isCascadeRefresh']; + } ); foreach ($associationMappings as $mapping) { @@ -2024,13 +2040,13 @@ function ($assoc) { return $assoc['isCascadeRefresh']; } * Cascades a detach operation to associated documents. * * @param object $document - * @param array $visited + * @param array $visited */ private function cascadeDetach($document, array &$visited) { $class = $this->dm->getClassMetadata(get_class($document)); foreach ($class->fieldMappings as $mapping) { - if ( ! $mapping['isCascadeDetach']) { + if (! $mapping['isCascadeDetach']) { continue; } $relatedDocuments = $class->reflFields[$mapping['fieldName']]->getValue($document); @@ -2052,7 +2068,7 @@ private function cascadeDetach($document, array &$visited) * * @param object $document * @param object $managedCopy - * @param array $visited + * @param array $visited */ private function cascadeMerge($document, $managedCopy, array &$visited) { @@ -2060,7 +2076,9 @@ private function cascadeMerge($document, $managedCopy, array &$visited) $associationMappings = array_filter( $class->associationMappings, - function ($assoc) { return $assoc['isCascadeMerge']; } + function ($assoc) { + return $assoc['isCascadeMerge']; + } ); foreach ($associationMappings as $assoc) { @@ -2085,7 +2103,7 @@ function ($assoc) { return $assoc['isCascadeMerge']; } * Cascades the save operation to associated documents. * * @param object $document - * @param array $visited + * @param array $visited */ private function cascadePersist($document, array &$visited) { @@ -2093,7 +2111,9 @@ private function cascadePersist($document, array &$visited) $associationMappings = array_filter( $class->associationMappings, - function ($assoc) { return $assoc['isCascadePersist']; } + function ($assoc) { + return $assoc['isCascadePersist']; + } ); foreach ($associationMappings as $fieldName => $mapping) { @@ -2110,7 +2130,7 @@ function ($assoc) { return $assoc['isCascadePersist']; } $count = 0; foreach ($relatedDocuments as $relatedKey => $relatedDocument) { - if ( ! empty($mapping['embedded'])) { + if (! empty($mapping['embedded'])) { list(, $knownParent, ) = $this->getParentAssociation($relatedDocument); if ($knownParent && $knownParent !== $document) { $relatedDocument = clone $relatedDocument; @@ -2122,7 +2142,7 @@ function ($assoc) { return $assoc['isCascadePersist']; } $this->doPersist($relatedDocument, $visited); } } elseif ($relatedDocuments !== null) { - if ( ! empty($mapping['embedded'])) { + if (! empty($mapping['embedded'])) { list(, $knownParent, ) = $this->getParentAssociation($relatedDocuments); if ($knownParent && $knownParent !== $document) { $relatedDocuments = clone $relatedDocuments; @@ -2139,13 +2159,13 @@ function ($assoc) { return $assoc['isCascadePersist']; } * Cascades the delete operation to associated documents. * * @param object $document - * @param array $visited + * @param array $visited */ private function cascadeRemove($document, array &$visited) { $class = $this->dm->getClassMetadata(get_class($document)); foreach ($class->fieldMappings as $mapping) { - if ( ! $mapping['isCascadeRemove']) { + if (! $mapping['isCascadeRemove']) { continue; } if ($document instanceof Proxy && ! $document->__isInitialized__) { @@ -2168,32 +2188,32 @@ private function cascadeRemove($document, array &$visited) * Acquire a lock on the given document. * * @param object $document - * @param int $lockMode - * @param int $lockVersion + * @param int $lockMode + * @param int $lockVersion * @throws LockException * @throws \InvalidArgumentException */ public function lock($document, $lockMode, $lockVersion = null) { - if ($this->getDocumentState($document) != self::STATE_MANAGED) { + if ($this->getDocumentState($document) !== self::STATE_MANAGED) { throw new \InvalidArgumentException('Document is not MANAGED.'); } $documentName = get_class($document); $class = $this->dm->getClassMetadata($documentName); - if ($lockMode == LockMode::OPTIMISTIC) { - if ( ! $class->isVersioned) { + if ($lockMode === LockMode::OPTIMISTIC) { + if (! $class->isVersioned) { throw LockException::notVersioned($documentName); } - if ($lockVersion != null) { + if ($lockVersion !== null) { $documentVersion = $class->reflFields[$class->versionField]->getValue($document); - if ($documentVersion != $lockVersion) { + if ($documentVersion !== $lockVersion) { throw LockException::lockFailedVersionMissmatch($document, $lockVersion, $documentVersion); } } - } elseif (in_array($lockMode, array(LockMode::PESSIMISTIC_READ, LockMode::PESSIMISTIC_WRITE))) { + } elseif (in_array($lockMode, [LockMode::PESSIMISTIC_READ, LockMode::PESSIMISTIC_WRITE])) { $this->getDocumentPersister($class->name)->lock($document, $lockMode); } } @@ -2206,8 +2226,8 @@ public function lock($document, $lockMode, $lockVersion = null) */ public function unlock($document) { - if ($this->getDocumentState($document) != self::STATE_MANAGED) { - throw new \InvalidArgumentException("Document is not MANAGED."); + if ($this->getDocumentState($document) !== self::STATE_MANAGED) { + throw new \InvalidArgumentException('Document is not MANAGED.'); } $documentName = get_class($document); $this->getDocumentPersister($documentName)->unlock($document); @@ -2236,9 +2256,9 @@ public function clear($documentName = null) $this->parentAssociations = $this->embeddedDocumentsRegistry = $this->orphanRemovals = - $this->hasScheduledCollections = array(); + $this->hasScheduledCollections = []; } else { - $visited = array(); + $visited = []; foreach ($this->identityMap as $className => $documents) { if ($className === $documentName) { foreach ($documents as $document) { @@ -2289,9 +2309,7 @@ public function unscheduleOrphanRemoval($document) * 3) NOP if state is OK * Returned collection should be used from now on (only important with 2nd point) * - * @param PersistentCollectionInterface $coll * @param object $document - * @param ClassMetadata $class * @param string $propName * @return PersistentCollectionInterface */ @@ -2301,7 +2319,7 @@ private function fixPersistentCollectionOwnership(PersistentCollectionInterface if ($owner === null) { // cloned $coll->setOwner($document, $class->fieldMappings[$propName]); } elseif ($owner !== $document) { // no clone, we have to fix - if ( ! $coll->isInitialized()) { + if (! $coll->isInitialized()) { $coll->initialize(); // we have to do this otherwise the cols share state } $newValue = clone $coll; @@ -2320,13 +2338,12 @@ private function fixPersistentCollectionOwnership(PersistentCollectionInterface * INTERNAL: * Schedules a complete collection for removal when this UnitOfWork commits. * - * @param PersistentCollectionInterface $coll */ public function scheduleCollectionDeletion(PersistentCollectionInterface $coll) { $oid = spl_object_hash($coll); unset($this->collectionUpdates[$oid]); - if ( ! isset($this->collectionDeletions[$oid])) { + if (! isset($this->collectionDeletions[$oid])) { $this->collectionDeletions[$oid] = $coll; $this->scheduleCollectionOwner($coll); } @@ -2335,8 +2352,7 @@ public function scheduleCollectionDeletion(PersistentCollectionInterface $coll) /** * Checks whether a PersistentCollection is scheduled for deletion. * - * @param PersistentCollectionInterface $coll - * @return boolean + * @return bool */ public function isCollectionScheduledForDeletion(PersistentCollectionInterface $coll) { @@ -2347,7 +2363,6 @@ public function isCollectionScheduledForDeletion(PersistentCollectionInterface $ * INTERNAL: * Unschedules a collection from being deleted when this UnitOfWork commits. * - * @param PersistentCollectionInterface $coll */ public function unscheduleCollectionDeletion(PersistentCollectionInterface $coll) { @@ -2363,7 +2378,6 @@ public function unscheduleCollectionDeletion(PersistentCollectionInterface $coll * INTERNAL: * Schedules a collection for update when this UnitOfWork commits. * - * @param PersistentCollectionInterface $coll */ public function scheduleCollectionUpdate(PersistentCollectionInterface $coll) { @@ -2375,7 +2389,7 @@ public function scheduleCollectionUpdate(PersistentCollectionInterface $coll) $this->unscheduleCollectionDeletion($coll); } $oid = spl_object_hash($coll); - if ( ! isset($this->collectionUpdates[$oid])) { + if (! isset($this->collectionUpdates[$oid])) { $this->collectionUpdates[$oid] = $coll; $this->scheduleCollectionOwner($coll); } @@ -2385,7 +2399,6 @@ public function scheduleCollectionUpdate(PersistentCollectionInterface $coll) * INTERNAL: * Unschedules a collection from being updated when this UnitOfWork commits. * - * @param PersistentCollectionInterface $coll */ public function unscheduleCollectionUpdate(PersistentCollectionInterface $coll) { @@ -2400,8 +2413,7 @@ public function unscheduleCollectionUpdate(PersistentCollectionInterface $coll) /** * Checks whether a PersistentCollection is scheduled for update. * - * @param PersistentCollectionInterface $coll - * @return boolean + * @return bool */ public function isCollectionScheduledForUpdate(PersistentCollectionInterface $coll) { @@ -2420,7 +2432,7 @@ public function getVisitedCollections($document) { $oid = spl_object_hash($document); - return $this->visitedCollections[$oid] ?? array(); + return $this->visitedCollections[$oid] ?? []; } /** @@ -2434,7 +2446,7 @@ public function getScheduledCollections($document) { $oid = spl_object_hash($document); - return $this->hasScheduledCollections[$oid] ?? array(); + return $this->hasScheduledCollections[$oid] ?? []; } /** @@ -2442,7 +2454,7 @@ public function getScheduledCollections($document) * scheduled for update or deletion. * * @param object $document - * @return boolean + * @return bool */ public function hasScheduledCollections($document) { @@ -2460,7 +2472,6 @@ public function hasScheduledCollections($document) * unscheduled and atomic one is scheduled for update instead. This makes * calculating update data way easier. * - * @param PersistentCollectionInterface $coll */ private function scheduleCollectionOwner(PersistentCollectionInterface $coll) { @@ -2470,7 +2481,7 @@ private function scheduleCollectionOwner(PersistentCollectionInterface $coll) if ($document !== $coll->getOwner()) { $parent = $coll->getOwner(); $mapping = []; - while (null !== ($parentAssoc = $this->getParentAssociation($parent))) { + while (($parentAssoc = $this->getParentAssociation($parent)) !== null) { list($mapping, $parent, ) = $parentAssoc; } if (CollectionHelper::isAtomic($mapping['strategy'])) { @@ -2482,7 +2493,7 @@ private function scheduleCollectionOwner(PersistentCollectionInterface $coll) } } - if ( ! $this->isDocumentScheduled($document)) { + if (! $this->isDocumentScheduled($document)) { $this->scheduleForUpdate($document); } } @@ -2504,7 +2515,7 @@ public function getOwningDocument($document) while ($class->isEmbeddedDocument) { $parentAssociation = $this->getParentAssociation($document); - if ( ! $parentAssociation) { + if (! $parentAssociation) { throw new \UnexpectedValueException('Could not determine parent association for ' . get_class($document)); } @@ -2560,13 +2571,13 @@ public function getClassNameForAssociation(array $mapping, $data) * * @ignore * @param string $className The name of the document class. - * @param array $data The data for the document. - * @param array $hints Any hints to account for during reconstitution/lookup of the document. - * @param object $document The document to be hydrated into in case of creation + * @param array $data The data for the document. + * @param array $hints Any hints to account for during reconstitution/lookup of the document. + * @param object $document The document to be hydrated into in case of creation * @return object The document instance. * @internal Highly performance-sensitive method. */ - public function getOrCreateDocument($className, $data, &$hints = array(), $document = null) + public function getOrCreateDocument($className, $data, &$hints = [], $document = null) { $class = $this->dm->getClassMetadata($className); @@ -2672,12 +2683,9 @@ public function getOriginalDocumentData($document) { $oid = spl_object_hash($document); - return $this->originalDocumentData[$oid] ?? array(); + return $this->originalDocumentData[$oid] ?? []; } - /** - * @ignore - */ public function setOriginalDocumentData($document, array $data) { $oid = spl_object_hash($document); @@ -2692,7 +2700,7 @@ public function setOriginalDocumentData($document, array $data) * @ignore * @param string $oid * @param string $property - * @param mixed $value + * @param mixed $value */ public function setOriginalDocumentProperty($oid, $property, $value) { @@ -2713,7 +2721,7 @@ public function getDocumentIdentifier($document) /** * Checks whether the UnitOfWork has any pending insertions. * - * @return boolean TRUE if this UnitOfWork has pending insertions, FALSE otherwise. + * @return bool TRUE if this UnitOfWork has pending insertions, FALSE otherwise. */ public function hasPendingInsertions() { @@ -2724,7 +2732,7 @@ public function hasPendingInsertions() * Calculates the size of the UnitOfWork. The size of the UnitOfWork is the * number of documents in the identity map. * - * @return integer + * @return int */ public function size() { @@ -2747,15 +2755,15 @@ public function size() * conversion and throw an exception if it's inconsistent. * * @param object $document The document. - * @param array $id The identifier values. - * @param array $data The original document data. + * @param array $id The identifier values. + * @param array $data The original document data. */ public function registerManaged($document, $id, $data) { $oid = spl_object_hash($document); $class = $this->dm->getClassMetadata(get_class($document)); - if ( ! $class->identifier || $id === null) { + if (! $class->identifier || $id === null) { $this->documentIdentifiers[$oid] = $oid; } else { $this->documentIdentifiers[$oid] = $class->getPHPIdentifierValue($id); @@ -2774,7 +2782,7 @@ public function registerManaged($document, $id, $data) */ public function clearDocumentChangeSet($oid) { - $this->documentChangeSets[$oid] = array(); + $this->documentChangeSets[$oid] = []; } /* PropertyChangedListener implementation */ @@ -2782,23 +2790,23 @@ public function clearDocumentChangeSet($oid) /** * Notifies this UnitOfWork of a property change in a document. * - * @param object $document The document that owns the property. + * @param object $document The document that owns the property. * @param string $propertyName The name of the property that changed. - * @param mixed $oldValue The old value of the property. - * @param mixed $newValue The new value of the property. + * @param mixed $oldValue The old value of the property. + * @param mixed $newValue The new value of the property. */ public function propertyChanged($document, $propertyName, $oldValue, $newValue) { $oid = spl_object_hash($document); $class = $this->dm->getClassMetadata(get_class($document)); - if ( ! isset($class->fieldMappings[$propertyName])) { + if (! isset($class->fieldMappings[$propertyName])) { return; // ignore non-persistent fields } // Update changeset and mark document for synchronization - $this->documentChangeSets[$oid][$propertyName] = array($oldValue, $newValue); - if ( ! isset($this->scheduledForDirtyCheck[$class->name][$oid])) { + $this->documentChangeSets[$oid][$propertyName] = [$oldValue, $newValue]; + if (! isset($this->scheduledForDirtyCheck[$class->name][$oid])) { $this->scheduleForDirtyCheck($document); } } @@ -2867,7 +2875,6 @@ public function getScheduledCollectionUpdates() * Helper method to initialize a lazy loading proxy or persistent collection. * * @param object $obj - * @return void */ public function initializeObject($obj) { @@ -2880,6 +2887,6 @@ public function initializeObject($obj) private function objToStr($obj) { - return method_exists($obj, '__toString') ? (string)$obj : get_class($obj) . '@' . spl_object_hash($obj); + return method_exists($obj, '__toString') ? (string) $obj : get_class($obj) . '@' . spl_object_hash($obj); } } diff --git a/lib/Doctrine/ODM/MongoDB/Utility/CollectionHelper.php b/lib/Doctrine/ODM/MongoDB/Utility/CollectionHelper.php index fa4de7cdce..87e7fd4730 100644 --- a/lib/Doctrine/ODM/MongoDB/Utility/CollectionHelper.php +++ b/lib/Doctrine/ODM/MongoDB/Utility/CollectionHelper.php @@ -1,17 +1,20 @@ dm = $dm; @@ -48,7 +45,7 @@ public function __construct(DocumentManager $dm, UnitOfWork $uow, EventManager $ /** * @param object $proxy - * @param mixed $id + * @param mixed $id * @return bool Returns whether the exceptionDisabled flag was set */ public function documentNotFound($proxy, $id) @@ -62,7 +59,6 @@ public function documentNotFound($proxy, $id) /** * Dispatches postCollectionLoad event. * - * @param PersistentCollectionInterface $coll */ public function postCollectionLoad(PersistentCollectionInterface $coll) { @@ -73,12 +69,11 @@ public function postCollectionLoad(PersistentCollectionInterface $coll) /** * Invokes postPersist callbacks and events for given document cascading them to embedded documents as well. * - * @param ClassMetadata $class * @param object $document */ public function postPersist(ClassMetadata $class, $document) { - $class->invokeLifecycleCallbacks(Events::postPersist, $document, array(new LifecycleEventArgs($document, $this->dm))); + $class->invokeLifecycleCallbacks(Events::postPersist, $document, [new LifecycleEventArgs($document, $this->dm)]); $this->evm->dispatchEvent(Events::postPersist, new LifecycleEventArgs($document, $this->dm)); $this->cascadePostPersist($class, $document); } @@ -86,12 +81,11 @@ public function postPersist(ClassMetadata $class, $document) /** * Invokes postRemove callbacks and events for given document. * - * @param ClassMetadata $class * @param object $document */ public function postRemove(ClassMetadata $class, $document) { - $class->invokeLifecycleCallbacks(Events::postRemove, $document, array(new LifecycleEventArgs($document, $this->dm))); + $class->invokeLifecycleCallbacks(Events::postRemove, $document, [new LifecycleEventArgs($document, $this->dm)]); $this->evm->dispatchEvent(Events::postRemove, new LifecycleEventArgs($document, $this->dm)); } @@ -99,12 +93,11 @@ public function postRemove(ClassMetadata $class, $document) * Invokes postUpdate callbacks and events for given document. The same will be done for embedded documents owned * by given document unless they were new in which case postPersist callbacks and events will be dispatched. * - * @param ClassMetadata $class * @param object $document */ public function postUpdate(ClassMetadata $class, $document) { - $class->invokeLifecycleCallbacks(Events::postUpdate, $document, array(new LifecycleEventArgs($document, $this->dm))); + $class->invokeLifecycleCallbacks(Events::postUpdate, $document, [new LifecycleEventArgs($document, $this->dm)]); $this->evm->dispatchEvent(Events::postUpdate, new LifecycleEventArgs($document, $this->dm)); $this->cascadePostUpdate($class, $document); } @@ -112,39 +105,34 @@ public function postUpdate(ClassMetadata $class, $document) /** * Invokes prePersist callbacks and events for given document. * - * @param ClassMetadata $class * @param object $document */ public function prePersist(ClassMetadata $class, $document) { - $class->invokeLifecycleCallbacks(Events::prePersist, $document, array(new LifecycleEventArgs($document, $this->dm))); + $class->invokeLifecycleCallbacks(Events::prePersist, $document, [new LifecycleEventArgs($document, $this->dm)]); $this->evm->dispatchEvent(Events::prePersist, new LifecycleEventArgs($document, $this->dm)); } /** * Invokes prePersist callbacks and events for given document. * - * @param ClassMetadata $class * @param object $document */ public function preRemove(ClassMetadata $class, $document) { - $class->invokeLifecycleCallbacks(Events::preRemove, $document, array(new LifecycleEventArgs($document, $this->dm))); + $class->invokeLifecycleCallbacks(Events::preRemove, $document, [new LifecycleEventArgs($document, $this->dm)]); $this->evm->dispatchEvent(Events::preRemove, new LifecycleEventArgs($document, $this->dm)); } /** * Invokes preUpdate callbacks and events for given document cascading them to embedded documents as well. * - * @param ClassMetadata $class * @param object $document */ public function preUpdate(ClassMetadata $class, $document) { - if ( ! empty($class->lifecycleCallbacks[Events::preUpdate])) { - $class->invokeLifecycleCallbacks(Events::preUpdate, $document, array( - new PreUpdateEventArgs($document, $this->dm, $this->uow->getDocumentChangeSet($document)) - )); + if (! empty($class->lifecycleCallbacks[Events::preUpdate])) { + $class->invokeLifecycleCallbacks(Events::preUpdate, $document, [new PreUpdateEventArgs($document, $this->dm, $this->uow->getDocumentChangeSet($document))]); $this->uow->recomputeSingleDocumentChangeSet($class, $document); } $this->evm->dispatchEvent(Events::preUpdate, new PreUpdateEventArgs($document, $this->dm, $this->uow->getDocumentChangeSet($document))); @@ -154,7 +142,6 @@ public function preUpdate(ClassMetadata $class, $document) /** * Cascades the preUpdate event to embedded documents. * - * @param ClassMetadata $class * @param object $document */ private function cascadePreUpdate(ClassMetadata $class, $document) @@ -164,7 +151,7 @@ private function cascadePreUpdate(ClassMetadata $class, $document) if ($value === null) { continue; } - $values = $mapping['type'] === ClassMetadata::ONE ? array($value) : $value; + $values = $mapping['type'] === ClassMetadata::ONE ? [$value] : $value; foreach ($values as $entry) { if ($this->uow->isScheduledForInsert($entry) || empty($this->uow->getDocumentChangeSet($entry))) { @@ -178,7 +165,6 @@ private function cascadePreUpdate(ClassMetadata $class, $document) /** * Cascades the postUpdate and postPersist events to embedded documents. * - * @param ClassMetadata $class * @param object $document */ private function cascadePostUpdate(ClassMetadata $class, $document) @@ -188,7 +174,7 @@ private function cascadePostUpdate(ClassMetadata $class, $document) if ($value === null) { continue; } - $values = $mapping['type'] === ClassMetadata::ONE ? array($value) : $value; + $values = $mapping['type'] === ClassMetadata::ONE ? [$value] : $value; foreach ($values as $entry) { if (empty($this->uow->getDocumentChangeSet($entry)) && ! $this->uow->hasScheduledCollections($entry)) { @@ -196,7 +182,7 @@ private function cascadePostUpdate(ClassMetadata $class, $document) } $entryClass = $this->dm->getClassMetadata(get_class($entry)); $event = $this->uow->isScheduledForInsert($entry) ? Events::postPersist : Events::postUpdate; - $entryClass->invokeLifecycleCallbacks($event, $entry, array(new LifecycleEventArgs($entry, $this->dm))); + $entryClass->invokeLifecycleCallbacks($event, $entry, [new LifecycleEventArgs($entry, $this->dm)]); $this->evm->dispatchEvent($event, new LifecycleEventArgs($entry, $this->dm)); $this->cascadePostUpdate($entryClass, $entry); @@ -207,7 +193,6 @@ private function cascadePostUpdate(ClassMetadata $class, $document) /** * Cascades the postPersist events to embedded documents. * - * @param ClassMetadata $class * @param object $document */ private function cascadePostPersist(ClassMetadata $class, $document) @@ -217,7 +202,7 @@ private function cascadePostPersist(ClassMetadata $class, $document) if ($value === null) { continue; } - $values = $mapping['type'] === ClassMetadata::ONE ? array($value) : $value; + $values = $mapping['type'] === ClassMetadata::ONE ? [$value] : $value; foreach ($values as $embeddedDocument) { $this->postPersist($this->dm->getClassMetadata(get_class($embeddedDocument)), $embeddedDocument); } diff --git a/phpcs.xml.dist b/phpcs.xml.dist new file mode 100644 index 0000000000..3b6f7c2d61 --- /dev/null +++ b/phpcs.xml.dist @@ -0,0 +1,80 @@ + + + + + + + + + + + + lib + tests + tools + + tests/Proxies* + tests/Hydrators* + tests/PersistentCollections* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + lib/Doctrine/ODM/MongoDB/Events.php + + + + */tests/* + + diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/AggregationOperatorsProviderTrait.php b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/AggregationOperatorsProviderTrait.php index e0c56d1714..7b8f30d86f 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/AggregationOperatorsProviderTrait.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/AggregationOperatorsProviderTrait.php @@ -1,10 +1,13 @@ gte('$field', 5), '$field', - '$otherField' + '$otherField', ]; }, ], @@ -308,10 +311,10 @@ public static function provideExpressionOperators() '$let' => [ 'vars' => [ 'total' => ['$add' => ['$price', '$tax']], - 'discounted' => ['$cond' => ['if' => '$applyDiscount', 'then' => 0.9, 'else' => 1]] + 'discounted' => ['$cond' => ['if' => '$applyDiscount', 'then' => 0.9, 'else' => 1]], ], - 'in' => ['$multiply' => ['$$total', '$$discounted']] - ] + 'in' => ['$multiply' => ['$$total', '$$discounted']], + ], ], 'operator' => 'let', 'args' => function (Expr $expr) { @@ -363,7 +366,7 @@ public static function provideExpressionOperators() return [ '$quizzes', 'grade', - $expr->add('$$grade', 2) + $expr->add('$$grade', 2), ]; }, ], @@ -440,7 +443,7 @@ public static function provideExpressionOperators() ['sum' => 0, 'product' => 1], $expr ->add('$$value.sum', '$$this') - ->multiply('$$value.product', '$$this') + ->multiply('$$value.product', '$$this'), ]; }, ], diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/AggregationTestTrait.php b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/AggregationTestTrait.php index 694a6e8276..1661e16d91 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/AggregationTestTrait.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/AggregationTestTrait.php @@ -1,5 +1,7 @@ ['$exists' => true], 'username' => 'foo', ], - 'num' => 10 - ] + 'num' => 10, + ], ], - ['$match' => + [ + '$match' => [ '$or' => [ ['username' => 'admin'], - ['username' => 'administrator'] + ['username' => 'administrator'], ], - 'group' => ['$in' => ['a', 'b']] - ] + 'group' => ['$in' => ['a', 'b']], + ], ], ['$sample' => ['size' => 10]], - ['$lookup' => + [ + '$lookup' => [ 'from' => 'orders', 'localField' => '_id', 'foreignField' => 'user.$id', - 'as' => 'orders' - ] + 'as' => 'orders', + ], ], ['$unwind' => 'a'], ['$unwind' => 'b'], - ['$redact' => + [ + '$redact' => [ '$cond' => [ 'if' => ['$lte' => ['$accessLevel', 3]], 'then' => '$$KEEP', 'else' => '$$REDACT', - ] - ] + ], + ], ], - ['$project' => + [ + '$project' => [ '_id' => false, 'user' => true, @@ -63,33 +77,34 @@ public function testGetPipeline() 'if' => [ '$and' => [ ['$eq' => ['$useAlternateDeliveryAddress', true]], - ['$ne' => ['$deliveryAddress', null]] - ] + ['$ne' => ['$deliveryAddress', null]], + ], ], 'then' => '$deliveryAddress', - 'else' => '$invoiceAddress' - ] - ] - ] + 'else' => '$invoiceAddress', + ], + ], + ], ], - ['$group' => + [ + '$group' => [ '_id' => '$user', 'numOrders' => ['$sum' => 1], 'amount' => [ 'total' => ['$sum' => '$amount'], - 'avg' => ['$avg' => '$amount'] - ] - ] + 'avg' => ['$avg' => '$amount'], + ], + ], ], ['$sort' => ['totalAmount' => 0]], ['$sort' => ['numOrders' => -1, 'avgAmount' => 1]], ['$limit' => 5], ['$skip' => 2], - ['$out' => 'collectionName'] + ['$out' => 'collectionName'], ]; - $builder = $this->dm->createAggregationBuilder(\Documents\BlogPost::class); + $builder = $this->dm->createAggregationBuilder(BlogPost::class); $builder ->geoNear($point) ->distanceField('distance') @@ -153,10 +168,10 @@ public function testAggregationBuilder() { $this->insertTestData(); - $builder = $this->dm->createAggregationBuilder(\Documents\BlogPost::class); + $builder = $this->dm->createAggregationBuilder(BlogPost::class); $resultCursor = $builder - ->hydrate(\Documents\BlogTagAggregation::class) + ->hydrate(BlogTagAggregation::class) ->unwind('$tags') ->group() ->field('id') @@ -170,7 +185,7 @@ public function testAggregationBuilder() $results = $resultCursor->toArray(); $this->assertCount(2, $results); - $this->assertInstanceOf(\Documents\BlogTagAggregation::class, $results[0]); + $this->assertInstanceOf(BlogTagAggregation::class, $results[0]); $this->assertSame('baseball', $results[0]->tag->name); $this->assertSame(3, $results[0]->numPosts); @@ -178,7 +193,7 @@ public function testAggregationBuilder() public function testPipelineConvertsTypes() { - $builder = $this->dm->createAggregationBuilder(\Documents\Article::class); + $builder = $this->dm->createAggregationBuilder(Article::class); $dateTime = new \DateTimeImmutable('2000-01-01T00:00Z'); $builder ->group() @@ -202,19 +217,19 @@ public function testPipelineConvertsTypes() '$group' => [ '_id' => [ '$cond' => [ - 'if' => ['$lt' => ['$createdAt', new \MongoDB\BSON\UTCDateTime((int) $dateTime->format('Uv'))]], + 'if' => ['$lt' => ['$createdAt', new UTCDateTime((int) $dateTime->format('Uv'))]], 'then' => true, 'else' => false, - ] + ], ], 'numPosts' => ['$sum' => 1], - ] + ], ], [ '$replaceRoot' => [ - 'isToday' => ['$eq' => ['$createdAt', new \MongoDB\BSON\UTCDateTime((int) $dateTime->format('Uv'))]], - ] - ] + 'isToday' => ['$eq' => ['$createdAt', new UTCDateTime((int) $dateTime->format('Uv'))]], + ], + ], ]; $this->assertEquals($expectedPipeline, $builder->getPipeline()); @@ -222,7 +237,7 @@ public function testPipelineConvertsTypes() public function testFieldNameConversion() { - $builder = $this->dm->createAggregationBuilder(\Documents\CmsComment::class); + $builder = $this->dm->createAggregationBuilder(CmsComment::class); $builder ->match() ->field('authorIp') @@ -240,15 +255,11 @@ public function testFieldNameConversion() [ '$project' => ['ip' => true], ], - [ - '$unwind' => 'ip', - ], + ['$unwind' => 'ip'], [ '$sort' => ['ip' => 1], ], - [ - '$replaceRoot' => '$ip', - ] + ['$replaceRoot' => '$ip'], ]; $this->assertEquals($expectedPipeline, $builder->getPipeline()); @@ -258,11 +269,11 @@ public function testBuilderAppliesFilterAndDiscriminatorWithMatchStage() { $this->dm->getFilterCollection()->enable('testFilter'); $filter = $this->dm->getFilterCollection()->getFilter('testFilter'); - $filter->setParameter('class', \Documents\GuestServer::class); + $filter->setParameter('class', GuestServer::class); $filter->setParameter('field', 'filtered'); $filter->setParameter('value', true); - $builder = $this->dm->createAggregationBuilder(\Documents\GuestServer::class); + $builder = $this->dm->createAggregationBuilder(GuestServer::class); $builder ->project() ->excludeFields(['_id']); @@ -279,7 +290,7 @@ public function testBuilderAppliesFilterAndDiscriminatorWithMatchStage() ], [ '$project' => ['_id' => false], - ] + ], ]; $this->assertEquals($expectedPipeline, $builder->getPipeline()); @@ -289,11 +300,11 @@ public function testBuilderAppliesFilterAndDiscriminatorWithGeoNearStage() { $this->dm->getFilterCollection()->enable('testFilter'); $filter = $this->dm->getFilterCollection()->getFilter('testFilter'); - $filter->setParameter('class', \Documents\GuestServer::class); + $filter->setParameter('class', GuestServer::class); $filter->setParameter('field', 'filtered'); $filter->setParameter('value', true); - $builder = $this->dm->createAggregationBuilder(\Documents\GuestServer::class); + $builder = $this->dm->createAggregationBuilder(GuestServer::class); $builder ->geoNear(0, 0); @@ -320,7 +331,7 @@ public function testBuilderWithOutStageReturnsNoData() { $this->insertTestData(); - $builder = $this->dm->createAggregationBuilder(\Documents\BlogPost::class); + $builder = $this->dm->createAggregationBuilder(BlogPost::class); $builder ->out('sampleCollection'); @@ -330,25 +341,25 @@ public function testBuilderWithOutStageReturnsNoData() private function insertTestData() { - $baseballTag = new \Documents\Tag('baseball'); - $footballTag = new \Documents\Tag('football'); + $baseballTag = new Tag('baseball'); + $footballTag = new Tag('football'); - $blogPost = new \Documents\BlogPost(); + $blogPost = new BlogPost(); $blogPost->name = 'Test 1'; $blogPost->addTag($baseballTag); $this->dm->persist($blogPost); - $blogPost = new \Documents\BlogPost(); + $blogPost = new BlogPost(); $blogPost->name = 'Test 2'; $blogPost->addTag($baseballTag); $this->dm->persist($blogPost); - $blogPost = new \Documents\BlogPost(); + $blogPost = new BlogPost(); $blogPost->name = 'Test 3'; $blogPost->addTag($footballTag); $this->dm->persist($blogPost); - $blogPost = new \Documents\BlogPost(); + $blogPost = new BlogPost(); $blogPost->name = 'Test 4'; $blogPost->addTag($baseballTag); $blogPost->addTag($footballTag); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/ExprTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/ExprTest.php index 5b7fae2c9d..58116c720d 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/ExprTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/ExprTest.php @@ -1,11 +1,11 @@ [ 'dayOfMonth' => ['$dayOfMonth' => '$dateField'], - 'dayOfWeek' => ['$dayOfWeek' => '$dateField'] - ] + 'dayOfWeek' => ['$dayOfWeek' => '$dateField'], + ], ], $expr->getExpression() ); @@ -103,7 +103,7 @@ public function testSwitch() ['case' => ['$eq' => ['$numElements', 1]], 'then' => 'One element given'], ], 'default' => ['$concat' => ['$numElements', ' elements given']], - ] + ], ], $expr->getExpression() ); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/AddFieldsTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/AddFieldsTest.php index 7fbfe5e78b..18020e126c 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/AddFieldsTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/AddFieldsTest.php @@ -1,5 +1,7 @@ field('averageValue') ->avg('$value'); - $this->assertSame(['$bucketAuto' => [ + $this->assertSame([ + '$bucketAuto' => [ 'groupBy' => '$someField', 'buckets' => 3, 'granularity' => 'R10', - 'output' => ['averageValue' => ['$avg' => '$value']] - ]], $bucketStage->getExpression()); + 'output' => ['averageValue' => ['$avg' => '$value']], + ], + ], $bucketStage->getExpression()); } public function testBucketAutoFromBuilder() @@ -42,12 +47,15 @@ public function testBucketAutoFromBuilder() ->field('averageValue') ->avg('$value'); - $this->assertSame([['$bucketAuto' => [ + $this->assertSame([[ + '$bucketAuto' => [ 'groupBy' => '$someField', 'buckets' => 3, 'granularity' => 'R10', - 'output' => ['averageValue' => ['$avg' => '$value']] - ]]], $builder->getPipeline()); + 'output' => ['averageValue' => ['$avg' => '$value']], + ], + ], + ], $builder->getPipeline()); } public function testBucketAutoSkipsUndefinedProperties() @@ -57,10 +65,12 @@ public function testBucketAutoSkipsUndefinedProperties() ->groupBy('$someField') ->buckets(3); - $this->assertSame(['$bucketAuto' => [ + $this->assertSame([ + '$bucketAuto' => [ 'groupBy' => '$someField', 'buckets' => 3, - ]], $bucketStage->getExpression()); + ], + ], $bucketStage->getExpression()); } public function testFieldNameConversion() @@ -76,12 +86,15 @@ public function testFieldNameConversion() ->avg('$value'); $this->assertEquals( - [['$bucketAuto' => [ + [[ + '$bucketAuto' => [ 'groupBy' => '$ip', 'buckets' => 3, 'granularity' => 'R10', - 'output' => ['averageValue' => ['$avg' => '$value']] - ]]], + 'output' => ['averageValue' => ['$avg' => '$value']], + ], + ], + ], $builder->getPipeline() ); } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/BucketTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/BucketTest.php index 735e72f326..5ad9f43871 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/BucketTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/BucketTest.php @@ -1,14 +1,17 @@ field('averageValue') ->avg('$value'); - $this->assertSame(['$bucket' => [ + $this->assertSame([ + '$bucket' => [ 'groupBy' => '$someField', 'boundaries' => [1, 2, 3], 'default' => 0, - 'output' => ['averageValue' => ['$avg' => '$value']] - ]], $bucketStage->getExpression()); + 'output' => ['averageValue' => ['$avg' => '$value']], + ], + ], $bucketStage->getExpression()); } public function testBucketFromBuilder() @@ -42,12 +47,15 @@ public function testBucketFromBuilder() ->field('averageValue') ->avg('$value'); - $this->assertSame([['$bucket' => [ + $this->assertSame([[ + '$bucket' => [ 'groupBy' => '$someField', 'boundaries' => [1, 2, 3], 'default' => 0, - 'output' => ['averageValue' => ['$avg' => '$value']] - ]]], $builder->getPipeline()); + 'output' => ['averageValue' => ['$avg' => '$value']], + ], + ], + ], $builder->getPipeline()); } public function testBucketSkipsUndefinedProperties() @@ -57,10 +65,12 @@ public function testBucketSkipsUndefinedProperties() ->groupBy('$someField') ->boundaries(1, 2, 3); - $this->assertSame(['$bucket' => [ + $this->assertSame([ + '$bucket' => [ 'groupBy' => '$someField', 'boundaries' => [1, 2, 3], - ]], $bucketStage->getExpression()); + ], + ], $bucketStage->getExpression()); } public function testFieldNameConversion() @@ -76,12 +86,15 @@ public function testFieldNameConversion() ->avg('$value'); $this->assertEquals( - [['$bucket' => [ + [[ + '$bucket' => [ 'groupBy' => '$ip', 'boundaries' => [1, 2, 3], 'default' => 0, - 'output' => ['averageValue' => ['$avg' => '$value']] - ]]], + 'output' => ['averageValue' => ['$avg' => '$value']], + ], + ], + ], $builder->getPipeline() ); } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/CollStatsTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/CollStatsTest.php index e16ea30d92..8f93b8c096 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/CollStatsTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/CollStatsTest.php @@ -1,5 +1,7 @@ assertSame([[ '$collStats' => [ 'latencyStats' => ['histograms' => true], - 'storageStats' => [] - ] - ]], $builder->getPipeline()); + 'storageStats' => [], + ], + ], + ], $builder->getPipeline()); } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/CountTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/CountTest.php index 246a88134f..175628f2fb 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/CountTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/CountTest.php @@ -1,5 +1,7 @@ [ 'someField' => [['$sortByCount' => '$tags']], 'otherField' => [['$sortByCount' => '$comments']], - ] + ], ], $facetStage->getExpression()); } @@ -46,8 +48,9 @@ public function testFacetFromBuilder() '$facet' => [ 'someField' => [['$sortByCount' => '$tags']], 'otherField' => [['$sortByCount' => '$comments']], - ] - ]], $builder->getPipeline()); + ], + ], + ], $builder->getPipeline()); } public function testFacetThrowsExceptionWithoutFieldName() diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/GeoNearTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/GeoNearTest.php index 716a80380b..bfc634d75a 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/GeoNearTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/GeoNearTest.php @@ -1,5 +1,7 @@ alias('reportingHierarchy'); $this->assertEquals( - ['$graphLookup' => [ + [ + '$graphLookup' => [ 'from' => 'employees', 'startWith' => '$reportsTo', 'connectFromField' => 'reportsTo', 'connectToField' => 'name', 'as' => 'reportingHierarchy', 'restrictSearchWithMatch' => (object) [], - ]], + ], + ], $graphLookupStage->getExpression() ); } @@ -56,14 +63,17 @@ public function testGraphLookupFromBuilder() ->alias('reportingHierarchy'); $this->assertEquals( - [['$graphLookup' => [ + [[ + '$graphLookup' => [ 'from' => 'employees', 'startWith' => '$reportsTo', 'connectFromField' => 'reportsTo', 'connectToField' => 'name', 'as' => 'reportingHierarchy', 'restrictSearchWithMatch' => (object) [], - ]]], + ], + ], + ], $builder->getPipeline() ); } @@ -83,7 +93,8 @@ public function testGraphLookupWithMatch() ->depthField('depth'); $this->assertSame( - [['$graphLookup' => [ + [[ + '$graphLookup' => [ 'from' => 'employees', 'startWith' => '$reportsTo', 'connectFromField' => 'reportsTo', @@ -92,7 +103,9 @@ public function testGraphLookupWithMatch() 'restrictSearchWithMatch' => ['hobbies' => 'golf'], 'maxDepth' => 1, 'depthField' => 'depth', - ]]], + ], + ], + ], $builder->getPipeline() ); } @@ -109,7 +122,7 @@ public function provideEmployeeAggregations() 'startWith' => '$reportsTo.id', 'connectFromField' => 'reportsTo.id', 'connectToField' => '_id', - ] + ], ], 'owningSideId' => [ 'addGraphLookupStage' => function (Builder $builder) { @@ -120,7 +133,7 @@ public function provideEmployeeAggregations() 'startWith' => '$reportsToId', 'connectFromField' => 'reportsToId', 'connectToField' => '_id', - ] + ], ], 'inverseSide' => [ 'addGraphLookupStage' => function (Builder $builder) { @@ -131,7 +144,7 @@ public function provideEmployeeAggregations() 'startWith' => '$reportsTo.id', 'connectFromField' => 'reportsTo.id', 'connectToField' => '_id', - ] + ], ], ]; } @@ -153,8 +166,8 @@ public function testGraphLookupWithEmployees(\Closure $addGraphLookupStage, arra 'from' => 'Employee', 'as' => 'reportingHierarchy', 'restrictSearchWithMatch' => (object) [], - ], $expectedFields) - ] + ], $expectedFields), + ], ]; $this->assertEquals($expectedPipeline, $builder->getPipeline()); @@ -187,7 +200,7 @@ public function provideTravellerAggregations() 'startWith' => '$nearestAirport.id', 'connectFromField' => 'connections.id', 'connectToField' => '_id', - ] + ], ], 'owningSideId' => [ 'addGraphLookupStage' => function (Builder $builder) { @@ -201,7 +214,7 @@ public function provideTravellerAggregations() 'startWith' => '$nearestAirportId', 'connectFromField' => 'connectionIds', 'connectToField' => '_id', - ] + ], ], ]; } @@ -224,8 +237,8 @@ public function testGraphLookupWithTraveller(\Closure $addGraphLookupStage, arra 'maxDepth' => 2, 'depthField' => 'numConnections', 'restrictSearchWithMatch' => (object) [], - ], $expectedFields) - ] + ], $expectedFields), + ], ]; $this->assertEquals($expectedPipeline, $builder->getPipeline()); @@ -265,8 +278,8 @@ public function testGraphLookupWithUnmappedFields() 'connectToField' => 'target', 'as' => 'targets', 'restrictSearchWithMatch' => (object) [], - ] - ] + ], + ], ]; $this->assertEquals($expectedPipeline, $builder->getPipeline()); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/GroupTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/GroupTest.php index 9c91936921..894d6798c1 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/GroupTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/GroupTest.php @@ -1,5 +1,7 @@ ['addToSet', ['$field']], 'avg()' => ['avg', ['$field']], - 'expression()' => ['expression', function (Expr $expr) { + 'expression()' => [ + 'expression', + function (Expr $expr) { $expr ->field('dayOfMonth') ->dayOfMonth('$dateField') @@ -49,7 +53,8 @@ public function provideProxiedExprMethods() ->dayOfWeek('$dateField'); return [$expr]; - }], + }, + ], 'first()' => ['first', ['$field']], 'last()' => ['last', ['$field']], 'max()' => ['max', ['$field']], diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/IndexStatsTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/IndexStatsTest.php index 1a6d0fafad..4b1857c69d 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/IndexStatsTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/IndexStatsTest.php @@ -1,5 +1,7 @@ dm->createAggregationBuilder(\Documents\SimpleReferenceUser::class); + $builder = $this->dm->createAggregationBuilder(SimpleReferenceUser::class); $builder ->lookup('user') ->alias('user'); @@ -29,8 +35,8 @@ public function testLookupStage() 'localField' => 'userId', 'foreignField' => '_id', 'as' => 'user', - ] - ] + ], + ], ]; $this->assertEquals($expectedPipeline, $builder->getPipeline()); @@ -44,7 +50,7 @@ public function testLookupStage() public function testLookupStageWithFieldNameTranslation() { - $builder = $this->dm->createAggregationBuilder(\Documents\SimpleReferenceUser::class); + $builder = $this->dm->createAggregationBuilder(SimpleReferenceUser::class); $builder ->lookup(CmsComment::class) ->localField('id') @@ -58,8 +64,8 @@ public function testLookupStageWithFieldNameTranslation() 'localField' => '_id', 'foreignField' => 'ip', 'as' => 'user', - ] - ] + ], + ], ]; $this->assertEquals($expectedPipeline, $builder->getPipeline()); @@ -67,9 +73,9 @@ public function testLookupStageWithFieldNameTranslation() public function testLookupStageWithClassName() { - $builder = $this->dm->createAggregationBuilder(\Documents\SimpleReferenceUser::class); + $builder = $this->dm->createAggregationBuilder(SimpleReferenceUser::class); $builder - ->lookup(\Documents\User::class) + ->lookup(User::class) ->localField('userId') ->foreignField('_id') ->alias('user'); @@ -81,8 +87,8 @@ public function testLookupStageWithClassName() 'localField' => 'userId', 'foreignField' => '_id', 'as' => 'user', - ] - ] + ], + ], ]; $this->assertEquals($expectedPipeline, $builder->getPipeline()); @@ -96,7 +102,7 @@ public function testLookupStageWithClassName() public function testLookupStageWithCollectionName() { - $builder = $this->dm->createAggregationBuilder(\Documents\SimpleReferenceUser::class); + $builder = $this->dm->createAggregationBuilder(SimpleReferenceUser::class); $builder ->lookup('randomCollectionName') ->localField('userId') @@ -110,8 +116,8 @@ public function testLookupStageWithCollectionName() 'localField' => 'userId', 'foreignField' => '_id', 'as' => 'user', - ] - ] + ], + ], ]; $this->assertEquals($expectedPipeline, $builder->getPipeline()); @@ -124,24 +130,22 @@ public function testLookupStageWithCollectionName() public function testLookupStageReferenceMany() { - $builder = $this->dm->createAggregationBuilder(\Documents\SimpleReferenceUser::class); + $builder = $this->dm->createAggregationBuilder(SimpleReferenceUser::class); $builder ->unwind('$users') ->lookup('users') ->alias('users'); $expectedPipeline = [ - [ - '$unwind' => '$users', - ], + ['$unwind' => '$users'], [ '$lookup' => [ 'from' => 'users', 'localField' => 'users', 'foreignField' => '_id', 'as' => 'users', - ] - ] + ], + ], ]; $this->assertEquals($expectedPipeline, $builder->getPipeline()); @@ -157,24 +161,22 @@ public function testLookupStageReferenceMany() public function testLookupStageReferenceManyStoreAsRef() { - $builder = $this->dm->createAggregationBuilder(\Documents\ReferenceUser::class); + $builder = $this->dm->createAggregationBuilder(ReferenceUser::class); $builder ->unwind('$referencedUsers') ->lookup('referencedUsers') ->alias('users'); $expectedPipeline = [ - [ - '$unwind' => '$referencedUsers', - ], + ['$unwind' => '$referencedUsers'], [ '$lookup' => [ 'from' => 'users', 'localField' => 'referencedUsers.id', 'foreignField' => '_id', 'as' => 'users', - ] - ] + ], + ], ]; $this->assertEquals($expectedPipeline, $builder->getPipeline()); @@ -192,7 +194,7 @@ public function testLookupStageReferenceManyWithoutUnwindMongoDB32() { $this->skipOnMongoDB34('$lookup tests without unwind will not work on MongoDB 3.4.0'); - $builder = $this->dm->createAggregationBuilder(\Documents\SimpleReferenceUser::class); + $builder = $this->dm->createAggregationBuilder(SimpleReferenceUser::class); $builder ->lookup('users') ->alias('users'); @@ -204,8 +206,8 @@ public function testLookupStageReferenceManyWithoutUnwindMongoDB32() 'localField' => 'users', 'foreignField' => '_id', 'as' => 'users', - ] - ] + ], + ], ]; $this->assertEquals($expectedPipeline, $builder->getPipeline()); @@ -220,7 +222,7 @@ public function testLookupStageReferenceManyWithoutUnwindMongoDB34() { $this->requireMongoDB34('$lookup tests with unwind require at least MongoDB 3.4.0'); - $builder = $this->dm->createAggregationBuilder(\Documents\SimpleReferenceUser::class); + $builder = $this->dm->createAggregationBuilder(SimpleReferenceUser::class); $builder ->lookup('users') ->alias('users'); @@ -232,8 +234,8 @@ public function testLookupStageReferenceManyWithoutUnwindMongoDB34() 'localField' => 'users', 'foreignField' => '_id', 'as' => 'users', - ] - ] + ], + ], ]; $this->assertEquals($expectedPipeline, $builder->getPipeline()); @@ -248,7 +250,7 @@ public function testLookupStageReferenceManyWithoutUnwindMongoDB34() public function testLookupStageReferenceOneInverse() { - $builder = $this->dm->createAggregationBuilder(\Documents\User::class); + $builder = $this->dm->createAggregationBuilder(User::class); $builder ->match() ->field('username') @@ -258,7 +260,7 @@ public function testLookupStageReferenceOneInverse() $expectedPipeline = [ [ - '$match' => ['username' => 'alcaeus'] + '$match' => ['username' => 'alcaeus'], ], [ '$lookup' => [ @@ -266,8 +268,8 @@ public function testLookupStageReferenceOneInverse() 'localField' => '_id', 'foreignField' => 'userId', 'as' => 'simpleReferenceOneInverse', - ] - ] + ], + ], ]; $this->assertEquals($expectedPipeline, $builder->getPipeline()); @@ -280,7 +282,7 @@ public function testLookupStageReferenceOneInverse() public function testLookupStageReferenceManyInverse() { - $builder = $this->dm->createAggregationBuilder(\Documents\User::class); + $builder = $this->dm->createAggregationBuilder(User::class); $builder ->match() ->field('username') @@ -290,7 +292,7 @@ public function testLookupStageReferenceManyInverse() $expectedPipeline = [ [ - '$match' => ['username' => 'alcaeus'] + '$match' => ['username' => 'alcaeus'], ], [ '$lookup' => [ @@ -298,8 +300,8 @@ public function testLookupStageReferenceManyInverse() 'localField' => '_id', 'foreignField' => 'users', 'as' => 'simpleReferenceManyInverse', - ] - ] + ], + ], ]; $this->assertEquals($expectedPipeline, $builder->getPipeline()); @@ -312,7 +314,7 @@ public function testLookupStageReferenceManyInverse() public function testLookupStageReferenceOneInverseStoreAsRef() { - $builder = $this->dm->createAggregationBuilder(\Documents\User::class); + $builder = $this->dm->createAggregationBuilder(User::class); $builder ->match() ->field('username') @@ -322,7 +324,7 @@ public function testLookupStageReferenceOneInverseStoreAsRef() $expectedPipeline = [ [ - '$match' => ['username' => 'alcaeus'] + '$match' => ['username' => 'alcaeus'], ], [ '$lookup' => [ @@ -330,8 +332,8 @@ public function testLookupStageReferenceOneInverseStoreAsRef() 'localField' => '_id', 'foreignField' => 'referencedUser.id', 'as' => 'embeddedReferenceOneInverse', - ] - ] + ], + ], ]; $this->assertEquals($expectedPipeline, $builder->getPipeline()); @@ -344,7 +346,7 @@ public function testLookupStageReferenceOneInverseStoreAsRef() public function testLookupStageReferenceManyInverseStoreAsRef() { - $builder = $this->dm->createAggregationBuilder(\Documents\User::class); + $builder = $this->dm->createAggregationBuilder(User::class); $builder ->match() ->field('username') @@ -354,7 +356,7 @@ public function testLookupStageReferenceManyInverseStoreAsRef() $expectedPipeline = [ [ - '$match' => ['username' => 'alcaeus'] + '$match' => ['username' => 'alcaeus'], ], [ '$lookup' => [ @@ -362,8 +364,8 @@ public function testLookupStageReferenceManyInverseStoreAsRef() 'localField' => '_id', 'foreignField' => 'referencedUsers.id', 'as' => 'embeddedReferenceManyInverse', - ] - ] + ], + ], ]; $this->assertEquals($expectedPipeline, $builder->getPipeline()); @@ -376,7 +378,7 @@ public function testLookupStageReferenceManyInverseStoreAsRef() public function testLookupToShardedCollectionThrowsException() { - $builder = $this->dm->createAggregationBuilder(\Documents\User::class); + $builder = $this->dm->createAggregationBuilder(User::class); $this->expectException(MappingException::class); $builder @@ -396,22 +398,22 @@ public function testLookupToShardedReferenceThrowsException() private function insertTestData() { - $user1 = new \Documents\User(); + $user1 = new User(); $user1->setUsername('alcaeus'); - $user2 = new \Documents\User(); + $user2 = new User(); $user2->setUsername('malarzm'); - $user3 = new \Documents\User(); + $user3 = new User(); $user3->setUsername('jmikola'); $this->dm->persist($user1); $this->dm->persist($user2); - $simpleReferenceUser = new \Documents\SimpleReferenceUser(); + $simpleReferenceUser = new SimpleReferenceUser(); $simpleReferenceUser->user = $user1; $simpleReferenceUser->addUser($user1); $simpleReferenceUser->addUser($user2); - $referenceUser = new \Documents\ReferenceUser(); + $referenceUser = new ReferenceUser(); $referenceUser->setReferencedUser($user1); $referenceUser->addReferencedUser($user1); $referenceUser->addReferencedUser($user2); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/MatchTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/MatchTest.php index 78ec5e058c..83085bdd50 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/MatchTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/MatchTest.php @@ -1,11 +1,14 @@ dm->createAggregationBuilder('Documents\User'); $date = new \DateTime(); - $mongoDate = new \MongoDB\BSON\UTCDateTime((int) $date->format('Uv')); + $mongoDate = new UTCDateTime((int) $date->format('Uv')); $stage = $builder ->match() ->field('createdAt') ->lte($date); $this->assertEquals( - ['$match' => [ - 'createdAt' => ['$lte' => $mongoDate] - ]], + [ + '$match' => [ + 'createdAt' => ['$lte' => $mongoDate], + ], + ], $stage->getExpression() ); } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/OperatorTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/OperatorTest.php index 8160ca99b5..2d457fb4c8 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/OperatorTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/OperatorTest.php @@ -1,5 +1,7 @@ [ 'dayOfMonth' => ['$dayOfMonth' => '$dateField'], - 'dayOfWeek' => ['$dayOfWeek' => '$dateField'] - ] + 'dayOfWeek' => ['$dayOfWeek' => '$dateField'], + ], ], $stage->getExpression() ); @@ -65,7 +67,7 @@ public function testSwitch() ['case' => ['$eq' => ['$numElements', 1]], 'then' => 'One element given'], ], 'default' => ['$concat' => ['$numElements', ' elements given']], - ] + ], ], $stage->getExpression() ); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/OutTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/OutTest.php index eabb01bd36..d254cbe09a 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/OutTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/OutTest.php @@ -1,19 +1,24 @@ dm->createAggregationBuilder(\Documents\SimpleReferenceUser::class); + $builder = $this->dm->createAggregationBuilder(SimpleReferenceUser::class); $builder - ->out(\Documents\User::class); + ->out(User::class); $expectedPipeline = [ - [ - '$out' => 'users' - ] + ['$out' => 'users'], ]; $this->assertEquals($expectedPipeline, $builder->getPipeline()); @@ -21,14 +26,12 @@ public function testOutStageWithClassName() public function testOutStageWithCollectionName() { - $builder = $this->dm->createAggregationBuilder(\Documents\SimpleReferenceUser::class); + $builder = $this->dm->createAggregationBuilder(SimpleReferenceUser::class); $builder ->out('someRandomCollectionName'); $expectedPipeline = [ - [ - '$out' => 'someRandomCollectionName' - ] + ['$out' => 'someRandomCollectionName'], ]; $this->assertEquals($expectedPipeline, $builder->getPipeline()); @@ -40,16 +43,16 @@ public function testOutStageWithCollectionName() */ public function testOutStageWithShardedClassName() { - $builder = $this->dm->createAggregationBuilder(\Documents\SimpleReferenceUser::class); + $builder = $this->dm->createAggregationBuilder(SimpleReferenceUser::class); $builder - ->out(\Documents\Sharded\ShardedUser::class); + ->out(ShardedUser::class); $builder->getPipeline(); } public function testSubsequentOutStagesAreOverwritten() { - $builder = $this->dm->createAggregationBuilder(\Documents\SimpleReferenceUser::class); + $builder = $this->dm->createAggregationBuilder(SimpleReferenceUser::class); $builder ->out('someCollection') ->out('otherCollection'); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/ProjectTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/ProjectTest.php index 4397480a58..7e8c303c20 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/ProjectTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/ProjectTest.php @@ -1,12 +1,15 @@ dm->createAggregationBuilder(User::class); $dateTime = new \DateTimeImmutable('2000-01-01T00:00Z'); - $mongoDate = new \MongoDB\BSON\UTCDateTime((int) $dateTime->format('Uv')); + $mongoDate = new UTCDateTime((int) $dateTime->format('Uv')); $stage = $builder ->replaceRoot() ->field('isToday') ->eq('$createdAt', $dateTime); $this->assertEquals( - ['$replaceRoot' => [ + [ + '$replaceRoot' => [ 'isToday' => ['$eq' => ['$createdAt', $mongoDate]], - ]], + ], + ], $stage->getExpression() ); } @@ -31,7 +37,7 @@ public function testTypeConversionWithDirectExpression() $builder = $this->dm->createAggregationBuilder(User::class); $dateTime = new \DateTimeImmutable('2000-01-01T00:00Z'); - $mongoDate = new \MongoDB\BSON\UTCDateTime((int) $dateTime->format('Uv')); + $mongoDate = new UTCDateTime((int) $dateTime->format('Uv')); $stage = $builder ->replaceRoot( $builder->expr() @@ -40,9 +46,11 @@ public function testTypeConversionWithDirectExpression() ); $this->assertEquals( - ['$replaceRoot' => [ + [ + '$replaceRoot' => [ 'isToday' => ['$eq' => ['$createdAt', $mongoDate]], - ]], + ], + ], $stage->getExpression() ); } @@ -57,9 +65,11 @@ public function testFieldNameConversion() ->concat('$authorIp', 'foo'); $this->assertEquals( - ['$replaceRoot' => [ + [ + '$replaceRoot' => [ 'someField' => ['$concat' => ['$ip', 'foo']], - ]], + ], + ], $stage->getExpression() ); } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/SampleTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/SampleTest.php index 2ebcfa0bb9..f51c2b8bd6 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/SampleTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/SampleTest.php @@ -1,5 +1,7 @@ [ ['field' => -1], 'field', - 'desc' + 'desc', ], 'singleFieldCombined' => [ ['field' => -1], - ['field' => 'desc'] + ['field' => 'desc'], ], 'multipleFields' => [ ['field' => -1, 'otherField' => 1], - ['field' => 'desc', 'otherField' => 'asc'] + ['field' => 'desc', 'otherField' => 'asc'], ], 'sortMeta' => [ ['field' => ['$meta' => 'textScore'], 'invalidField' => -1], - ['field' => 'textScore', 'invalidField' => 'nonExistingMetaField'] - ] + ['field' => 'textScore', 'invalidField' => 'nonExistingMetaField'], + ], ]; } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/UnwindTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/UnwindTest.php index 1e1748a835..68fd4d3ee1 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/UnwindTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/UnwindTest.php @@ -1,5 +1,7 @@ dm) { + if (! $this->dm) { return; } @@ -75,14 +85,14 @@ protected function createMetadataDriverImpl() protected function createTestDocumentManager() { $config = $this->getConfiguration(); - $client = new Client(getenv("DOCTRINE_MONGODB_SERVER") ?: DOCTRINE_MONGODB_SERVER, [], ['typeMap' => ['root' => 'array', 'document' => 'array']]); + $client = new Client(getenv('DOCTRINE_MONGODB_SERVER') ?: DOCTRINE_MONGODB_SERVER, [], ['typeMap' => ['root' => 'array', 'document' => 'array']]); return DocumentManager::create($client, $config); } protected function getServerVersion() { - $result = $this->dm->getClient()->selectDatabase(DOCTRINE_MONGODB_DATABASE)->command(array('buildInfo' => 1))->toArray()[0]; + $result = $this->dm->getClient()->selectDatabase(DOCTRINE_MONGODB_DATABASE)->command(['buildInfo' => 1])->toArray()[0]; return $result['version']; } @@ -90,11 +100,11 @@ protected function getServerVersion() protected function skipTestIfNotSharded($className) { $result = $this->dm->getDocumentDatabase($className)->command(['listCommands' => true])->toArray()[0]; - if (!$result['ok']) { + if (! $result['ok']) { $this->markTestSkipped('Could not check whether server supports sharding'); } - if (!array_key_exists('shardCollection', $result['commands'])) { + if (! array_key_exists('shardCollection', $result['commands'])) { $this->markTestSkipped('Test skipped because server does not support sharding'); } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/ConfigurationTest.php b/tests/Doctrine/ODM/MongoDB/Tests/ConfigurationTest.php index 1ede172e93..ea4e03dd75 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/ConfigurationTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/ConfigurationTest.php @@ -1,5 +1,7 @@ dm->getPartialReference('Documents\CmsUser', $id); $this->assertTrue($this->dm->contains($user)); $this->assertEquals($id, $user->id); @@ -93,13 +99,13 @@ public function testDocumentManagerIsClosedAccessor() public function dataMethodsAffectedByNoObjectArguments() { - return array( - array('persist'), - array('remove'), - array('merge'), - array('refresh'), - array('detach') - ); + return [ + ['persist'], + ['remove'], + ['merge'], + ['refresh'], + ['detach'], + ]; } /** @@ -114,13 +120,13 @@ public function testThrowsExceptionOnNonObjectValues($methodName) public function dataAffectedByErrorIfClosedException() { - return array( - array('flush'), - array('persist'), - array('remove'), - array('merge'), - array('refresh'), - ); + return [ + ['flush'], + ['persist'], + ['remove'], + ['merge'], + ['refresh'], + ]; } /** @@ -129,7 +135,7 @@ public function dataAffectedByErrorIfClosedException() */ public function testAffectedByErrorIfClosedException($methodName) { - $this->expectException(\Doctrine\ODM\MongoDB\MongoDBException::class); + $this->expectException(MongoDBException::class); $this->expectExceptionMessage('closed'); $this->dm->close(); @@ -146,7 +152,7 @@ public function testAffectedByErrorIfClosedException($methodName) */ public function testCannotCreateDbRefWithoutId() { - $d = new \Documents\User(); + $d = new User(); $this->dm->createReference($d, ['storeAs' => ClassMetadata::REFERENCE_STORE_AS_DB_REF]); } @@ -158,7 +164,7 @@ public function testCreateDbRefWithNonNullEmptyId() $dbRef = $this->dm->createReference($phonenumber, ['storeAs' => ClassMetadata::REFERENCE_STORE_AS_DB_REF, 'targetDocument' => CmsPhonenumber::class]); - $this->assertSame(array('$ref' => 'CmsPhonenumber', '$id' => 0), $dbRef); + $this->assertSame(['$ref' => 'CmsPhonenumber', '$id' => 0], $dbRef); } /** @@ -168,7 +174,7 @@ public function testCreateDbRefWithNonNullEmptyId() public function testDisriminatedSimpleReferenceFails() { $d = new WrongSimpleRefDocument(); - $r = new \Documents\Tournament\ParticipantSolo('Maciej'); + $r = new ParticipantSolo('Maciej'); $this->dm->persist($r); $class = $this->dm->getClassMetadata(get_class($d)); $this->dm->createReference($r, $class->associationMappings['ref']); @@ -176,13 +182,13 @@ public function testDisriminatedSimpleReferenceFails() public function testDifferentStoreAsDbReferences() { - $r = new \Documents\User(); + $r = new User(); $this->dm->persist($r); $d = new ReferenceStoreAsDocument(); $class = $this->dm->getClassMetadata(get_class($d)); $dbRef = $this->dm->createReference($r, $class->associationMappings['ref1']); - $this->assertInstanceOf(\MongoDB\BSON\ObjectId::class, $dbRef); + $this->assertInstanceOf(ObjectId::class, $dbRef); $dbRef = $this->dm->createReference($r, $class->associationMappings['ref2']); $this->assertCount(2, $dbRef); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/DocumentRepositoryTest.php b/tests/Doctrine/ODM/MongoDB/Tests/DocumentRepositoryTest.php index 69a37a888b..2543b1aeb1 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/DocumentRepositoryTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/DocumentRepositoryTest.php @@ -1,10 +1,11 @@ getUnitOfWork() ->getDocumentPersister(User::class) ->prepareQueryOrNewObj(['account' => $account]); - $expectedQuery = ['account.$id' => new \MongoDB\BSON\ObjectId($account->getId())]; + $expectedQuery = ['account.$id' => new ObjectId($account->getId())]; $this->assertEquals($expectedQuery, $query); $this->assertSame($user, $this->dm->getRepository(User::class)->findOneBy(['account' => $account])); @@ -59,8 +61,8 @@ public function testFindByRefOneWithoutTargetDocumentFull() ->prepareQueryOrNewObj(['user' => $user]); $expectedQuery = [ 'user.$ref' => 'users', - 'user.$id' => new \MongoDB\BSON\ObjectId($user->getId()), - 'user.$db' => DOCTRINE_MONGODB_DATABASE + 'user.$id' => new ObjectId($user->getId()), + 'user.$db' => DOCTRINE_MONGODB_DATABASE, ]; $this->assertEquals($expectedQuery, $query); @@ -82,7 +84,7 @@ public function testFindByRefOneWithoutTargetDocumentStoredAsDbRef() ->prepareQueryOrNewObj(['userDbRef' => $user]); $expectedQuery = [ 'userDbRef.$ref' => 'users', - 'userDbRef.$id' => new ObjectId($user->getId()) + 'userDbRef.$id' => new ObjectId($user->getId()), ]; $this->assertEquals($expectedQuery, $query); @@ -101,7 +103,7 @@ public function testFindDiscriminatedByRefManyFull() ->getUnitOfWork() ->getDocumentPersister(Developer::class) ->prepareQueryOrNewObj(['projects' => $project]); - $expectedQuery = ['projects' => ['$elemMatch' => ['$id' => new \MongoDB\BSON\ObjectId($project->getId())]]]; + $expectedQuery = ['projects' => ['$elemMatch' => ['$id' => new ObjectId($project->getId())]]]; $this->assertEquals($expectedQuery, $query); $this->assertSame($developer, $this->dm->getRepository(Developer::class)->findOneBy(['projects' => $project])); @@ -146,7 +148,7 @@ public function testFindByRefManyFull() $expectedQuery = [ 'groups' => [ '$elemMatch' => [ - '$id' => new \MongoDB\BSON\ObjectId($group->getId()), + '$id' => new ObjectId($group->getId()), ], ], ]; diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Events/LifecycleCallbacksTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Events/LifecycleCallbacksTest.php index 0d56379b5a..a42632a880 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Events/LifecycleCallbacksTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Events/LifecycleCallbacksTest.php @@ -1,12 +1,15 @@ createUser(); $this->dm->clear(); - $user = $this->dm->find(__NAMESPACE__.'\User', $user->id); + $user = $this->dm->find(__NAMESPACE__ . '\User', $user->id); $this->assertInstanceOf('DateTime', $user->createdAt); $this->assertInstanceOf('DateTime', $user->profile->createdAt); @@ -33,7 +36,7 @@ public function testPreUpdateChangingValue() $this->dm->flush(); $this->dm->clear(); - $user = $this->dm->find(__NAMESPACE__.'\User', $user->id); + $user = $this->dm->find(__NAMESPACE__ . '\User', $user->id); $this->assertInstanceOf('DateTime', $user->updatedAt); $this->assertInstanceOf('DateTime', $user->profile->updatedAt); } @@ -61,7 +64,7 @@ public function testPreUpdate() $this->assertTrue($user->postUpdate); $this->assertTrue($user->profile->postUpdate); } - + public function testPreFlush() { $user = $this->createUser(); @@ -78,7 +81,7 @@ public function testPreLoadAndPostLoad() $user = $this->createUser(); $this->dm->clear(); - $user = $this->dm->find(__NAMESPACE__.'\User', $user->id); + $user = $this->dm->find(__NAMESPACE__ . '\User', $user->id); $this->assertTrue($user->preLoad); $this->assertTrue($user->profile->preLoad); @@ -126,7 +129,7 @@ public function testEmbedManyEvent() $this->assertTrue($profile->postUpdate); $this->dm->clear(); - $user = $this->dm->find(__NAMESPACE__.'\User', $user->id); + $user = $this->dm->find(__NAMESPACE__ . '\User', $user->id); $profile = $user->profiles[0]; $this->assertTrue($profile->preLoad); @@ -172,10 +175,10 @@ public function testMultipleLevelsOfEmbedded() $this->assertTrue($profile->postUpdate); $this->dm->clear(); - $user = $this->dm->find(__NAMESPACE__.'\User', $user->id); + $user = $this->dm->find(__NAMESPACE__ . '\User', $user->id); $profile = $user->profile->profile; $profile->name = '2nd level changed again'; - + $profile2 = new Profile(); $profile2->name = 'test'; $user->profiles[] = $profile2; @@ -206,12 +209,12 @@ public function testMultipleLevelsOfEmbedded() $this->assertTrue($user->profiles[0]->preRemove); $this->assertTrue($user->profiles[0]->postRemove); } - + public function testReferences() { $user = $this->createUser(); $user2 = $this->createUser('maciej', 'Maciej Malarz'); - + $user->friends[] = $user2; $this->dm->flush(); @@ -250,10 +253,10 @@ class User extends BaseDocument public $profile; /** @ODM\EmbedMany(targetDocument="Profile") */ - public $profiles = array(); - + public $profiles = []; + /** @ODM\ReferenceMany(targetDocument="User") */ - public $friends = array(); + public $friends = []; } /** @ODM\Document */ @@ -358,7 +361,7 @@ public function postLoad(Event\LifecycleEventArgs $e) { $this->postLoad = true; } - + /** @ODM\PreFlush */ public function preFlush(Event\PreFlushEventArgs $e) { diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Events/LifecycleListenersTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Events/LifecycleListenersTest.php index 5838255eef..f019c2b48d 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Events/LifecycleListenersTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Events/LifecycleListenersTest.php @@ -1,18 +1,22 @@ listener = new MyEventListener(); $evm = $this->dm->getEventManager(); - $events = array( + $events = [ Events::prePersist, Events::postPersist, Events::preUpdate, @@ -21,7 +25,7 @@ private function getDocumentManager() Events::postLoad, Events::preRemove, Events::postRemove, - ); + ]; $evm->addEventListener($events, $this->listener); return $this->dm; } @@ -35,55 +39,55 @@ public function testLifecycleListeners() $dm->persist($test); $dm->flush(); - $called = array( - Events::prePersist => array('Doctrine\ODM\MongoDB\Tests\Events\TestDocument'), - Events::postPersist => array('Doctrine\ODM\MongoDB\Tests\Events\TestDocument') - ); + $called = [ + Events::prePersist => ['Doctrine\ODM\MongoDB\Tests\Events\TestDocument'], + Events::postPersist => ['Doctrine\ODM\MongoDB\Tests\Events\TestDocument'], + ]; $this->assertEquals($called, $this->listener->called); - $this->listener->called = array(); + $this->listener->called = []; $test->embedded[0] = new TestEmbeddedDocument(); $test->embedded[0]->name = 'cool'; $dm->flush(); $dm->clear(); - $called = array( - Events::prePersist => array('Doctrine\ODM\MongoDB\Tests\Events\TestEmbeddedDocument'), - Events::preUpdate => array('Doctrine\ODM\MongoDB\Tests\Events\TestDocument'), - Events::postUpdate => array('Doctrine\ODM\MongoDB\Tests\Events\TestDocument'), - Events::postPersist => array('Doctrine\ODM\MongoDB\Tests\Events\TestEmbeddedDocument') - ); + $called = [ + Events::prePersist => ['Doctrine\ODM\MongoDB\Tests\Events\TestEmbeddedDocument'], + Events::preUpdate => ['Doctrine\ODM\MongoDB\Tests\Events\TestDocument'], + Events::postUpdate => ['Doctrine\ODM\MongoDB\Tests\Events\TestDocument'], + Events::postPersist => ['Doctrine\ODM\MongoDB\Tests\Events\TestEmbeddedDocument'], + ]; $this->assertEquals($called, $this->listener->called); - $this->listener->called = array(); + $this->listener->called = []; - $document = $dm->find(__NAMESPACE__.'\TestDocument', $test->id); + $document = $dm->find(__NAMESPACE__ . '\TestDocument', $test->id); $document->embedded->initialize(); - $called = array( - Events::preLoad => array('Doctrine\ODM\MongoDB\Tests\Events\TestDocument', 'Doctrine\ODM\MongoDB\Tests\Events\TestEmbeddedDocument'), - Events::postLoad => array('Doctrine\ODM\MongoDB\Tests\Events\TestDocument', 'Doctrine\ODM\MongoDB\Tests\Events\TestEmbeddedDocument') - ); + $called = [ + Events::preLoad => ['Doctrine\ODM\MongoDB\Tests\Events\TestDocument', 'Doctrine\ODM\MongoDB\Tests\Events\TestEmbeddedDocument'], + Events::postLoad => ['Doctrine\ODM\MongoDB\Tests\Events\TestDocument', 'Doctrine\ODM\MongoDB\Tests\Events\TestEmbeddedDocument'], + ]; $this->assertEquals($called, $this->listener->called); - $this->listener->called = array(); + $this->listener->called = []; $document->embedded[0]->name = 'changed'; $dm->flush(); - $called = array( - Events::preUpdate => array('Doctrine\ODM\MongoDB\Tests\Events\TestDocument', 'Doctrine\ODM\MongoDB\Tests\Events\TestEmbeddedDocument'), - Events::postUpdate => array('Doctrine\ODM\MongoDB\Tests\Events\TestDocument', 'Doctrine\ODM\MongoDB\Tests\Events\TestEmbeddedDocument') - ); + $called = [ + Events::preUpdate => ['Doctrine\ODM\MongoDB\Tests\Events\TestDocument', 'Doctrine\ODM\MongoDB\Tests\Events\TestEmbeddedDocument'], + Events::postUpdate => ['Doctrine\ODM\MongoDB\Tests\Events\TestDocument', 'Doctrine\ODM\MongoDB\Tests\Events\TestEmbeddedDocument'], + ]; $this->assertEquals($called, $this->listener->called); - $this->listener->called = array(); + $this->listener->called = []; $dm->remove($document); $dm->flush(); - $called = array( - Events::preRemove => array('Doctrine\ODM\MongoDB\Tests\Events\TestEmbeddedDocument', 'Doctrine\ODM\MongoDB\Tests\Events\TestDocument'), - Events::postRemove => array('Doctrine\ODM\MongoDB\Tests\Events\TestEmbeddedDocument', 'Doctrine\ODM\MongoDB\Tests\Events\TestDocument') - ); + $called = [ + Events::preRemove => ['Doctrine\ODM\MongoDB\Tests\Events\TestEmbeddedDocument', 'Doctrine\ODM\MongoDB\Tests\Events\TestDocument'], + Events::postRemove => ['Doctrine\ODM\MongoDB\Tests\Events\TestEmbeddedDocument', 'Doctrine\ODM\MongoDB\Tests\Events\TestDocument'], + ]; $this->assertEquals($called, $this->listener->called); - $this->listener->called = array(); + $this->listener->called = []; $test = new TestDocument(); $test->name = 'test'; @@ -91,19 +95,19 @@ public function testLifecycleListeners() $test->embedded[0]->name = 'cool'; $dm->persist($test); $dm->flush(); - $this->listener->called = array(); + $this->listener->called = []; $test->name = 'cool'; $dm->flush(); $dm->clear(); - $called = array( - Events::preUpdate => array('Doctrine\ODM\MongoDB\Tests\Events\TestDocument'), - Events::postUpdate => array('Doctrine\ODM\MongoDB\Tests\Events\TestDocument') - ); + $called = [ + Events::preUpdate => ['Doctrine\ODM\MongoDB\Tests\Events\TestDocument'], + Events::postUpdate => ['Doctrine\ODM\MongoDB\Tests\Events\TestDocument'], + ]; $this->assertEquals($called, $this->listener->called); - $this->listener->called = array(); + $this->listener->called = []; } public function testMultipleLevelsOfEmbeddedDocsPrePersist() @@ -117,29 +121,29 @@ public function testMultipleLevelsOfEmbeddedDocsPrePersist() $dm->flush(); $dm->clear(); - $test = $dm->find(__NAMESPACE__.'\TestProfile', $test->id); - $this->listener->called = array(); + $test = $dm->find(__NAMESPACE__ . '\TestProfile', $test->id); + $this->listener->called = []; $test->image->thumbnails[] = new Thumbnail('Thumbnail #1'); $dm->flush(); - $called = array( - Events::prePersist => array('Doctrine\ODM\MongoDB\Tests\Events\Thumbnail'), - Events::preUpdate => array('Doctrine\ODM\MongoDB\Tests\Events\TestProfile', 'Doctrine\ODM\MongoDB\Tests\Events\Image'), - Events::postUpdate => array('Doctrine\ODM\MongoDB\Tests\Events\TestProfile', 'Doctrine\ODM\MongoDB\Tests\Events\Image'), - Events::postPersist => array('Doctrine\ODM\MongoDB\Tests\Events\Thumbnail') - ); + $called = [ + Events::prePersist => ['Doctrine\ODM\MongoDB\Tests\Events\Thumbnail'], + Events::preUpdate => ['Doctrine\ODM\MongoDB\Tests\Events\TestProfile', 'Doctrine\ODM\MongoDB\Tests\Events\Image'], + Events::postUpdate => ['Doctrine\ODM\MongoDB\Tests\Events\TestProfile', 'Doctrine\ODM\MongoDB\Tests\Events\Image'], + Events::postPersist => ['Doctrine\ODM\MongoDB\Tests\Events\Thumbnail'], + ]; $this->assertEquals($called, $this->listener->called); - $this->listener->called = array(); + $this->listener->called = []; $test->image->thumbnails[0]->name = 'ok'; $dm->flush(); - $called = array( - Events::preUpdate => array('Doctrine\ODM\MongoDB\Tests\Events\TestProfile', 'Doctrine\ODM\MongoDB\Tests\Events\Image', 'Doctrine\ODM\MongoDB\Tests\Events\Thumbnail'), - Events::postUpdate => array('Doctrine\ODM\MongoDB\Tests\Events\TestProfile', 'Doctrine\ODM\MongoDB\Tests\Events\Image', 'Doctrine\ODM\MongoDB\Tests\Events\Thumbnail'), - ); + $called = [ + Events::preUpdate => ['Doctrine\ODM\MongoDB\Tests\Events\TestProfile', 'Doctrine\ODM\MongoDB\Tests\Events\Image', 'Doctrine\ODM\MongoDB\Tests\Events\Thumbnail'], + Events::postUpdate => ['Doctrine\ODM\MongoDB\Tests\Events\TestProfile', 'Doctrine\ODM\MongoDB\Tests\Events\Image', 'Doctrine\ODM\MongoDB\Tests\Events\Thumbnail'], + ]; $this->assertEquals($called, $this->listener->called); - $this->listener->called = array(); + $this->listener->called = []; } public function testChangeToReferenceFieldTriggersEvents() @@ -153,29 +157,29 @@ public function testChangeToReferenceFieldTriggersEvents() $dm->persist($profile); $dm->flush(); $dm->clear(); - $this->listener->called = array(); + $this->listener->called = []; - $called = array( - Events::preUpdate => array('Doctrine\ODM\MongoDB\Tests\Events\TestDocument'), - Events::postUpdate => array('Doctrine\ODM\MongoDB\Tests\Events\TestDocument'), - ); + $called = [ + Events::preUpdate => ['Doctrine\ODM\MongoDB\Tests\Events\TestDocument'], + Events::postUpdate => ['Doctrine\ODM\MongoDB\Tests\Events\TestDocument'], + ]; $document = $dm->getRepository(get_class($document))->find($document->id); $profile = $dm->getRepository(get_class($profile))->find($profile->id); - $this->listener->called = array(); + $this->listener->called = []; $document->profile = $profile; $dm->flush(); $dm->clear(); $this->assertEquals($called, $this->listener->called, 'Changing ReferenceOne field did not dispatched proper events.'); - $this->listener->called = array(); + $this->listener->called = []; $document = $dm->getRepository(get_class($document))->find($document->id); $profile = $dm->getRepository(get_class($profile))->find($profile->id); - $this->listener->called = array(); + $this->listener->called = []; $document->profiles[] = $profile; $dm->flush(); $this->assertEquals($called, $this->listener->called, 'Changing ReferenceMany field did not dispatched proper events.'); - $this->listener->called = array(); + $this->listener->called = []; } public function testPostCollectionLoad() @@ -205,7 +209,7 @@ public function testPostCollectionLoad() class MyEventListener { - public $called = array(); + public $called = []; public function __call($method, $args) { @@ -302,7 +306,7 @@ class Image public $name; /** @ODM\EmbedMany(targetDocument="Thumbnail") */ - public $thumbnails = array(); + public $thumbnails = []; public function __construct($name) { diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Events/PreLoadEventArgsTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Events/PreLoadEventArgsTest.php index e86b909233..2824411042 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Events/PreLoadEventArgsTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Events/PreLoadEventArgsTest.php @@ -1,17 +1,20 @@ dm; - $data = array('id' => '1234', 'name' => 'test'); + $data = ['id' => '1234', 'name' => 'test']; $eventArgs = new PreLoadEventArgs($document, $dm, $data); $eventArgsData =& $eventArgs->getData(); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Events/PreUpdateEventArgsTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Events/PreUpdateEventArgsTest.php index 5991eac539..93ac8d549b 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Events/PreUpdateEventArgsTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Events/PreUpdateEventArgsTest.php @@ -1,15 +1,20 @@ 'foo', 'bar' => 'bar', 'baz' => null, 'zip' => 'zip', - ); + ]; $this->dm->getDocumentCollection(__NAMESPACE__ . '\AlsoLoadDocument')->insertOne($document); - $document = $this->dm->getRepository(__NAMESPACE__ . '\AlsoLoadDocument')->findOneBy(array()); + $document = $this->dm->getRepository(__NAMESPACE__ . '\AlsoLoadDocument')->findOneBy([]); $this->assertEquals('foo', $document->foo, '"foo" gets its own value and ignores "bar" and "zip"'); $this->assertEquals('bar', $document->bar, '"bar" is hydrated normally'); @@ -27,11 +30,11 @@ public function testPropertyAlsoLoadDoesNotInterfereWithBasicHydration() public function testPropertyAlsoLoadMayOverwriteDefaultPropertyValue() { - $document = array('zip' => 'zip'); + $document = ['zip' => 'zip']; $this->dm->getDocumentCollection(__NAMESPACE__ . '\AlsoLoadDocument')->insertOne($document); - $document = $this->dm->getRepository(__NAMESPACE__ . '\AlsoLoadDocument')->findOneBy(array()); + $document = $this->dm->getRepository(__NAMESPACE__ . '\AlsoLoadDocument')->findOneBy([]); $this->assertEquals('zip', $document->zap, '"zap" gets value from "zip", overwriting its default value'); $this->assertEquals('zip', $document->zip, '"zip" is hydrated normally'); @@ -39,14 +42,14 @@ public function testPropertyAlsoLoadMayOverwriteDefaultPropertyValue() public function testPropertyAlsoLoadShortCircuitsAfterFirstFieldIsFound() { - $document = array( + $document = [ 'bar' => null, 'zip' => 'zip', - ); + ]; $this->dm->getDocumentCollection(__NAMESPACE__ . '\AlsoLoadDocument')->insertOne($document); - $document = $this->dm->getRepository(__NAMESPACE__ . '\AlsoLoadDocument')->findOneBy(array()); + $document = $this->dm->getRepository(__NAMESPACE__ . '\AlsoLoadDocument')->findOneBy([]); $this->assertEquals(null, $document->foo, '"foo" gets null value from "bar" and ignores "zip"'); $this->assertEquals('zip', $document->baz, '"baz" gets value from "zip" and ignores "bar"'); @@ -56,11 +59,11 @@ public function testPropertyAlsoLoadShortCircuitsAfterFirstFieldIsFound() public function testPropertyAlsoLoadChecksMultipleFields() { - $document = array('zip' => 'zip'); + $document = ['zip' => 'zip']; $this->dm->getDocumentCollection(__NAMESPACE__ . '\AlsoLoadDocument')->insertOne($document); - $document = $this->dm->getRepository(__NAMESPACE__ . '\AlsoLoadDocument')->findOneBy(array()); + $document = $this->dm->getRepository(__NAMESPACE__ . '\AlsoLoadDocument')->findOneBy([]); $this->assertEquals('zip', $document->foo, '"foo" gets value from "zip" since "bar" was missing'); $this->assertNull($document->bar, '"bar" is not hydrated'); @@ -69,14 +72,14 @@ public function testPropertyAlsoLoadChecksMultipleFields() public function testPropertyAlsoLoadBeatsMethodAlsoLoad() { - $document = array( + $document = [ 'testNew' => 'testNew', 'testOld' => 'testOld', - ); + ]; $this->dm->getDocumentCollection(__NAMESPACE__ . '\AlsoLoadDocument')->insertOne($document); - $document = $this->dm->getRepository(__NAMESPACE__ . '\AlsoLoadDocument')->findOneBy(array()); + $document = $this->dm->getRepository(__NAMESPACE__ . '\AlsoLoadDocument')->findOneBy([]); $this->assertEquals('testNew', $document->test, '"test" gets value from "testNew"'); $this->assertEquals('testNew', $document->testNew, '"testNew" is hydrated normally'); @@ -85,14 +88,14 @@ public function testPropertyAlsoLoadBeatsMethodAlsoLoad() public function testMethodAlsoLoadDoesNotInterfereWithBasicHydration() { - $document = array( + $document = [ 'firstName' => 'Jonathan', 'name' => 'Kris Wallsmith', - ); + ]; $this->dm->getDocumentCollection(__NAMESPACE__ . '\AlsoLoadDocument')->insertOne($document); - $document = $this->dm->getRepository(__NAMESPACE__ . '\AlsoLoadDocument')->findOneBy(array()); + $document = $this->dm->getRepository(__NAMESPACE__ . '\AlsoLoadDocument')->findOneBy([]); $this->assertEquals('Jonathan', $document->firstName, '"firstName" gets value from exploded "name" but is overwritten with normal hydration'); $this->assertEquals('Wallsmith', $document->lastName, '"lastName" gets value from exploded "name"'); @@ -101,11 +104,11 @@ public function testMethodAlsoLoadDoesNotInterfereWithBasicHydration() public function testMethodAlsoLoadMayOverwriteDefaultPropertyValue() { - $document = array('testOld' => null); + $document = ['testOld' => null]; $this->dm->getDocumentCollection(__NAMESPACE__ . '\AlsoLoadDocument')->insertOne($document); - $document = $this->dm->getRepository(__NAMESPACE__ . '\AlsoLoadDocument')->findOneBy(array()); + $document = $this->dm->getRepository(__NAMESPACE__ . '\AlsoLoadDocument')->findOneBy([]); $this->assertNull($document->test, '"test" gets value from "testOld", overwriting its default value'); $this->assertNull($document->testOld, '"testOld" is hydrated normally"'); @@ -113,16 +116,16 @@ public function testMethodAlsoLoadMayOverwriteDefaultPropertyValue() public function testMethodAlsoLoadShortCircuitsAfterFirstFieldIsFound() { - $document = array( + $document = [ 'name' => 'Jonathan Wage', 'fullName' => 'Kris Wallsmith', 'testOld' => 'testOld', 'testOlder' => 'testOlder', - ); + ]; $this->dm->getDocumentCollection(__NAMESPACE__ . '\AlsoLoadDocument')->insertOne($document); - $document = $this->dm->getRepository(__NAMESPACE__ . '\AlsoLoadDocument')->findOneBy(array()); + $document = $this->dm->getRepository(__NAMESPACE__ . '\AlsoLoadDocument')->findOneBy([]); $this->assertEquals('Jonathan Wage', $document->name, '"name" is hydrated normally'); $this->assertEquals('Kris Wallsmith', $document->fullName, '"fullName" is hydrated normally'); @@ -136,14 +139,14 @@ public function testMethodAlsoLoadShortCircuitsAfterFirstFieldIsFound() public function testMethodAlsoLoadChecksMultipleFields() { - $document = array( + $document = [ 'fullName' => 'Kris Wallsmith', 'testOlder' => 'testOlder', - ); + ]; $this->dm->getDocumentCollection(__NAMESPACE__ . '\AlsoLoadDocument')->insertOne($document); - $document = $this->dm->getRepository(__NAMESPACE__ . '\AlsoLoadDocument')->findOneBy(array()); + $document = $this->dm->getRepository(__NAMESPACE__ . '\AlsoLoadDocument')->findOneBy([]); $this->assertNull($document->name, '"name" is not hydrated'); $this->assertEquals('Kris Wallsmith', $document->fullName, '"fullName" is hydrated normally'); @@ -176,16 +179,16 @@ public function testNotSaved() public function testMethodAlsoLoadParentInheritance() { - $document = array( + $document = [ 'buzz' => 'buzz', 'test' => 'test', 'testOld' => 'testOld', 'testOlder' => 'testOlder', - ); + ]; $this->dm->getDocumentCollection(__NAMESPACE__ . '\AlsoLoadChild')->insertOne($document); - $document = $this->dm->getRepository(__NAMESPACE__ . '\AlsoLoadChild')->findOneBy(array()); + $document = $this->dm->getRepository(__NAMESPACE__ . '\AlsoLoadChild')->findOneBy([]); $this->assertEquals('buzz', $document->fizz, '"fizz" gets value from "buzz"'); $this->assertEquals('test', $document->test, '"test" is hydrated normally, since "testOldest" was missing and parent method was overridden'); @@ -193,14 +196,14 @@ public function testMethodAlsoLoadParentInheritance() public function testMethodAlsoLoadGrandparentInheritance() { - $document = array( + $document = [ 'buzz' => 'buzz', 'testReallyOldest' => 'testReallyOldest', - ); + ]; $this->dm->getDocumentCollection(__NAMESPACE__ . '\AlsoLoadGrandchild')->insertOne($document); - $document = $this->dm->getRepository(__NAMESPACE__ . '\AlsoLoadGrandchild')->findOneBy(array()); + $document = $this->dm->getRepository(__NAMESPACE__ . '\AlsoLoadGrandchild')->findOneBy([]); $this->assertEquals('buzz', $document->fizz, '"fizz" gets value from "buzz"'); $this->assertEquals('testReallyOldest', $document->test, '"test" gets value from "testReallyOldest"'); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/AtomicSetTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/AtomicSetTest.php index ffe2535440..704d481b3a 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/AtomicSetTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/AtomicSetTest.php @@ -1,9 +1,12 @@ markTestSkipped('mongodb-driver: query logging does not exist'); - if ( ! isset($this->ql)) { + if (! isset($this->ql)) { $this->ql = new QueryLogger(); } @@ -51,7 +56,7 @@ public function testAtomicInsertAndUpdate() $this->assertCount(1, $user->phonenumbers); $this->assertEquals('12345678', $user->phonenumbers[0]->getPhonenumber()); - $user->surname = "Malarz"; + $user->surname = 'Malarz'; $user->phonenumbers[] = new Phonenumber('87654321'); $this->ql->clear(); $this->dm->flush(); @@ -69,7 +74,7 @@ public function testAtomicInsertAndUpdate() public function testAtomicUpsert() { $user = new AtomicSetUser('Maciej'); - $user->id = new \MongoDB\BSON\ObjectId(); + $user->id = new ObjectId(); $user->phonenumbers[] = new Phonenumber('12345678'); $this->dm->persist($user); $this->dm->flush(); @@ -99,7 +104,7 @@ public function testAtomicCollectionUnset($clearWith) $this->assertCount(1, $user->phonenumbers); $this->assertEquals('12345678', $user->phonenumbers[0]->getPhonenumber()); - $user->surname = "Malarz"; + $user->surname = 'Malarz'; $user->phonenumbers = $clearWith; $this->ql->clear(); $this->dm->flush(); @@ -114,11 +119,11 @@ public function testAtomicCollectionUnset($clearWith) public function provideAtomicCollectionUnset() { - return array( - array(null), - array(array()), - array(new ArrayCollection()), - ); + return [ + [null], + [[]], + [new ArrayCollection()], + ]; } public function testAtomicCollectionClearAndUpdate() @@ -250,7 +255,7 @@ public function testAtomicCollectionWithAnotherNested() $this->assertCount(1, $publicBook->getPhonenumbers()); $this->assertEquals('10203040', $publicBook->getPhonenumbers()->get(0)->getPhonenumber()); } - + public function testWeNeedToGoDeeper() { $user = new AtomicSetUser('Maciej'); @@ -413,7 +418,7 @@ public function testAtomicSetUpdatesAllNestedCollectionsInOneQuery() // Simulate another PHP request which loads this record and tries to add an embedded document two levels deep... $this->dm->clear(); - $book = $this->dm->getRepository(Book::CLASSNAME)->findOneBy(array('_id' => $book->id)); + $book = $this->dm->getRepository(Book::CLASSNAME)->findOneBy(['_id' => $book->id]); // Now we add a new "page" to the only chapter in this book. $firstChapter = $book->chapters->first(); @@ -425,8 +430,8 @@ public function testAtomicSetUpdatesAllNestedCollectionsInOneQuery() $this->assertCount(1, $this->ql, 'Adding a page to the first chapter of the book requires one query'); // this is failing if lifecycle callback postUpdate is recomputing change set - $book = $this->dm->getRepository(Book::CLASSNAME)->findOneBy(array('_id' => $book->id)); - $this->assertEquals(2, $book->chapters->first()->pages->count(), "Two page objects are expected in the first chapter of the book."); + $book = $this->dm->getRepository(Book::CLASSNAME)->findOneBy(['_id' => $book->id]); + $this->assertEquals(2, $book->chapters->first()->pages->count(), 'Two page objects are expected in the first chapter of the book.'); } public function testReplacementOfEmbedManyElements() @@ -441,10 +446,10 @@ public function testReplacementOfEmbedManyElements() // Simulate another PHP request which loads this record. $this->dm->clear(); - $book = $this->dm->getRepository(Book::CLASSNAME)->findOneBy(array('_id' => $book->id)); + $book = $this->dm->getRepository(Book::CLASSNAME)->findOneBy(['_id' => $book->id]); $firstChapter = $book->chapters->first(); - $firstChapter->name = "First chapter A"; + $firstChapter->name = 'First chapter A'; // Developers commonly attempt to replace the contents of an EmbedMany with a new ArrayCollection like this: $replacementChapters = new ArrayCollection(); @@ -456,7 +461,7 @@ public function testReplacementOfEmbedManyElements() // Simulate another PHP request. $this->dm->clear(); - $book = $this->dm->getRepository(Book::CLASSNAME)->findOneBy(array('_id' => $book->id)); + $book = $this->dm->getRepository(Book::CLASSNAME)->findOneBy(['_id' => $book->id]); // Verify we see chapters A and B. $this->assertEquals('First chapter A', $book->chapters[0]->name); @@ -472,9 +477,9 @@ public function testReplacementOfIdentifiedEmbedManyElements() $this->dm->flush(); $this->dm->clear(); - $book = $this->dm->getRepository(Book::CLASSNAME)->findOneBy(array('_id' => $book->id)); + $book = $this->dm->getRepository(Book::CLASSNAME)->findOneBy(['_id' => $book->id]); $firstChapter = $book->identifiedChapters->first(); - $firstChapter->name = "First chapter A"; + $firstChapter->name = 'First chapter A'; $replacementChapters = new ArrayCollection(); $replacementChapters->add($firstChapter); $replacementChapters->add(new IdentifiedChapter('Second chapter B')); @@ -483,7 +488,7 @@ public function testReplacementOfIdentifiedEmbedManyElements() $this->dm->flush(); $this->dm->clear(); - $book = $this->dm->getRepository(Book::CLASSNAME)->findOneBy(array('_id' => $book->id)); + $book = $this->dm->getRepository(Book::CLASSNAME)->findOneBy(['_id' => $book->id]); $this->assertEquals('First chapter A', $book->identifiedChapters[0]->name); $this->assertEquals('Second chapter B', $book->identifiedChapters[1]->name); } @@ -500,18 +505,18 @@ public function testOnlyEmbeddedDocumentUpdated() // Simulate another PHP request which loads this record. $this->dm->clear(); - $book = $this->dm->getRepository(Book::CLASSNAME)->findOneBy(array('_id' => $book->id)); + $book = $this->dm->getRepository(Book::CLASSNAME)->findOneBy(['_id' => $book->id]); // Modify the chapter's name. - $book->chapters->first()->name = "First chapter A"; + $book->chapters->first()->name = 'First chapter A'; $this->dm->flush(); // Simulate another PHP request & verify the change was saved. $this->dm->clear(); - $book = $this->dm->getRepository(Book::CLASSNAME)->findOneBy(array('_id' => $book->id)); + $book = $this->dm->getRepository(Book::CLASSNAME)->findOneBy(['_id' => $book->id]); - $this->assertEquals('First chapter A', $book->chapters[0]->name, "The chapter title failed to update."); + $this->assertEquals('First chapter A', $book->chapters[0]->name, 'The chapter title failed to update.'); } public function testUpdatedEmbeddedDocumentAndDirtyCollectionInside() @@ -523,9 +528,9 @@ public function testUpdatedEmbeddedDocumentAndDirtyCollectionInside() $this->dm->flush(); $this->dm->clear(); - $book = $this->dm->getRepository(Book::CLASSNAME)->findOneBy(array('_id' => $book->id)); + $book = $this->dm->getRepository(Book::CLASSNAME)->findOneBy(['_id' => $book->id]); $firstChapter = $book->chapters->first(); - $firstChapter->name = "Apple"; + $firstChapter->name = 'Apple'; // Add some pages. $firstChapter->pages->add(new Page(1)); @@ -534,7 +539,7 @@ public function testUpdatedEmbeddedDocumentAndDirtyCollectionInside() $this->dm->flush(); $this->dm->clear(); - $book = $this->dm->getRepository(Book::CLASSNAME)->findOneBy(array('_id' => $book->id)); + $book = $this->dm->getRepository(Book::CLASSNAME)->findOneBy(['_id' => $book->id]); $this->assertEquals(2, $book->chapters->first()->pages->count()); } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/BidirectionalInheritanceTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/BidirectionalInheritanceTest.php index 9733054f58..20149af9c0 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/BidirectionalInheritanceTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/BidirectionalInheritanceTest.php @@ -1,5 +1,7 @@ dm->persist($test); $this->dm->flush(); - $check = $this->dm->getDocumentCollection(get_class($test))->findOne(array()); - $this->assertInstanceOf(\MongoDB\BSON\Binary::class, $check[$field]); + $check = $this->dm->getDocumentCollection(get_class($test))->findOne([]); + $this->assertInstanceOf(Binary::class, $check[$field]); $this->assertEquals($type, $check[$field]->getType()); $this->assertEquals($data, $check[$field]->getData()); } public function provideData() { - return array( - array('bin', 'test', \MongoDB\BSON\Binary::TYPE_GENERIC), - array('binFunc', 'test', \MongoDB\BSON\Binary::TYPE_FUNCTION), - array('binByteArray', 'test', \MongoDB\BSON\Binary::TYPE_OLD_BINARY), - array('binUUID', 'testtesttesttest', \MongoDB\BSON\Binary::TYPE_OLD_UUID), - array('binUUIDRFC4122', '1234567890ABCDEF', \MongoDB\BSON\Binary::TYPE_UUID), - array('binMD5', 'test', \MongoDB\BSON\Binary::TYPE_MD5), - array('binCustom', 'test', \MongoDB\BSON\Binary::TYPE_USER_DEFINED), - ); + return [ + ['bin', 'test', Binary::TYPE_GENERIC], + ['binFunc', 'test', Binary::TYPE_FUNCTION], + ['binByteArray', 'test', Binary::TYPE_OLD_BINARY], + ['binUUID', 'testtesttesttest', Binary::TYPE_OLD_UUID], + ['binUUIDRFC4122', '1234567890ABCDEF', Binary::TYPE_UUID], + ['binMD5', 'test', Binary::TYPE_MD5], + ['binCustom', 'test', Binary::TYPE_USER_DEFINED], + ]; } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/CollectionPersisterTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/CollectionPersisterTest.php index 49158759ad..550cff8cba 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/CollectionPersisterTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/CollectionPersisterTest.php @@ -1,11 +1,15 @@ getCollectionPersister(); $user = $this->getTestUser('jwage'); - $persister->delete($user->phonenumbers, array()); + $persister->delete($user->phonenumbers, []); - $user = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterUser')->findOne(array('username' => 'jwage')); + $user = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterUser')->findOne(['username' => 'jwage']); $this->assertArrayNotHasKey('phonenumbers', $user, 'Test that the phonenumbers field was deleted'); } @@ -23,9 +27,9 @@ public function testDeleteEmbedMany() { $persister = $this->getCollectionPersister(); $user = $this->getTestUser('jwage'); - $persister->delete($user->categories, array()); + $persister->delete($user->categories, []); - $user = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterUser')->findOne(array('username' => 'jwage')); + $user = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterUser')->findOne(['username' => 'jwage']); $this->assertArrayNotHasKey('categories', $user, 'Test that the categories field was deleted'); } @@ -34,18 +38,18 @@ public function testDeleteNestedEmbedMany() $persister = $this->getCollectionPersister(); $user = $this->getTestUser('jwage'); - $persister->delete($user->categories[0]->children[0]->children, array()); - $persister->delete($user->categories[0]->children[1]->children, array()); + $persister->delete($user->categories[0]->children[0]->children, []); + $persister->delete($user->categories[0]->children[1]->children, []); - $check = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterUser')->findOne(array('username' => 'jwage')); + $check = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterUser')->findOne(['username' => 'jwage']); $this->assertFalse(isset($check['categories']['0']['children'][0]['children'])); $this->assertFalse(isset($check['categories']['0']['children'][1]['children'])); - $persister->delete($user->categories[0]->children, array()); - $persister->delete($user->categories[1]->children, array()); + $persister->delete($user->categories[0]->children, []); + $persister->delete($user->categories[1]->children, []); - $check = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterUser')->findOne(array('username' => 'jwage')); + $check = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterUser')->findOne(['username' => 'jwage']); $this->assertFalse(isset($check['categories'][0]['children']), 'Test that the nested children categories field was deleted'); $this->assertTrue(isset($check['categories'][0]), 'Test that the category with the children still exists'); @@ -70,7 +74,7 @@ public function testDeleteRows() $this->dm->flush(); - $check = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterUser')->findOne(array('username' => 'jwage')); + $check = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterUser')->findOne(['username' => 'jwage']); $this->assertFalse(isset($check['phonenumbers'][0])); $this->assertFalse(isset($check['phonenumbers'][1])); @@ -85,7 +89,7 @@ public function testDeleteRows() unset($user->categories[1]); $this->dm->flush(); - $check = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterUser')->findOne(array('username' => 'jwage')); + $check = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterUser')->findOne(['username' => 'jwage']); $this->assertFalse(isset($check['categories'][0])); $this->assertFalse(isset($check['categories'][1])); } @@ -97,7 +101,7 @@ public function testInsertRows() $user->phonenumbers[] = new CollectionPersisterPhonenumber('6155139185'); $this->dm->flush(); - $check = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterUser')->findOne(array('username' => 'jwage')); + $check = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterUser')->findOne(['username' => 'jwage']); $this->assertCount(4, $check['phonenumbers']); $this->assertEquals((string) $check['phonenumbers'][2]['$id'], $user->phonenumbers[2]->id); $this->assertEquals((string) $check['phonenumbers'][3]['$id'], $user->phonenumbers[3]->id); @@ -106,7 +110,7 @@ public function testInsertRows() $user->categories[] = new CollectionPersisterCategory('Test'); $this->dm->flush(); - $check = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterUser')->findOne(array('username' => 'jwage')); + $check = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterUser')->findOne(['username' => 'jwage']); $this->assertCount(4, $check['categories']); $user->categories[3]->children[0] = new CollectionPersisterCategory('Test'); @@ -115,7 +119,7 @@ public function testInsertRows() $user->categories[3]->children[1]->children[1] = new CollectionPersisterCategory('Test'); $this->dm->flush(); - $check = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterUser')->findOne(array('username' => 'jwage')); + $check = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterUser')->findOne(['username' => 'jwage']); $this->assertCount(2, $check['categories'][3]['children']); $this->assertCount(2, $check['categories'][3]['children']['1']['children']); } @@ -168,7 +172,7 @@ public function testNestedEmbedManySetStrategy() $this->dm->persist($post); $this->dm->flush(); - $doc = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterPost')->findOne(array('post' => 'postA')); + $doc = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterPost')->findOne(['post' => 'postA']); $this->assertCount(1, $doc['comments']); $this->assertEquals($commentA->comment, $doc['comments']['a']['comment']); @@ -189,7 +193,7 @@ public function testNestedEmbedManySetStrategy() $this->dm->persist($post); $this->dm->flush(); - $doc = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterPost')->findOne(array('post' => 'postA')); + $doc = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterPost')->findOne(['post' => 'postA']); $this->assertCount(2, $doc['comments']); $this->assertEquals($commentA->comment, $doc['comments']['a']['comment']); @@ -209,7 +213,7 @@ public function testNestedEmbedManySetStrategy() $this->dm->persist($post); $this->dm->flush(); - $doc = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterPost')->findOne(array('post' => 'postA')); + $doc = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterPost')->findOne(['post' => 'postA']); $this->assertCount(2, $doc['comments']); $this->assertEquals($commentA->comment, $doc['comments']['a']['comment']); @@ -226,7 +230,7 @@ public function testNestedEmbedManySetStrategy() $this->dm->persist($post); $this->dm->flush(); - $doc = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterPost')->findOne(array('post' => 'postA')); + $doc = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CollectionPersisterPost')->findOne(['post' => 'postA']); $this->assertCount(1, $doc['comments']); $this->assertEquals($commentA->comment, $doc['comments']['a']['comment']); @@ -248,8 +252,8 @@ public function testFindBySetStrategyKey() $this->dm->persist($post); $this->dm->flush(); - $this->assertSame($post, $this->dm->getRepository(get_class($post))->findOneBy(array('comments.a.by' => 'userA'))); - $this->assertSame($post, $this->dm->getRepository(get_class($post))->findOneBy(array('comments.a.comments.b.by' => 'userB'))); + $this->assertSame($post, $this->dm->getRepository(get_class($post))->findOneBy(['comments.a.by' => 'userA'])); + $this->assertSame($post, $this->dm->getRepository(get_class($post))->findOneBy(['comments.a.comments.b.by' => 'userB'])); } } @@ -263,10 +267,10 @@ class CollectionPersisterUser public $username; /** @ODM\EmbedMany(targetDocument="CollectionPersisterCategory") */ - public $categories = array(); + public $categories = []; /** @ODM\ReferenceMany(targetDocument="CollectionPersisterPhonenumber", cascade={"persist"}) */ - public $phonenumbers = array(); + public $phonenumbers = []; } /** @ODM\EmbeddedDocument */ @@ -276,7 +280,7 @@ class CollectionPersisterCategory public $name; /** @ODM\EmbedMany(targetDocument="CollectionPersisterCategory") */ - public $children = array(); + public $children = []; public function __construct($name) { @@ -303,42 +307,40 @@ public function __construct($phonenumber) class CollectionPersisterPost { /** @ODM\Id */ - public $id; + public $id; /** @ODM\Field(type="string") */ - public $post; + public $post; /** @ODM\EmbedMany(targetDocument="CollectionPersisterComment", strategy="set") */ - public $comments = array(); - - function __construct($post) - { - $this->comments = new \Doctrine\Common\Collections\ArrayCollection(); - $this->post = $post; - } - + public $comments = []; + function __construct($post) + { + $this->comments = new ArrayCollection(); + $this->post = $post; + } } /** @ODM\EmbeddedDocument */ class CollectionPersisterComment { /** @ODM\Id */ - public $id; + public $id; /** @ODM\Field(type="string") */ - public $comment; + public $comment; /** @ODM\Field(type="string") */ - public $by; + public $by; /** @ODM\EmbedMany(targetDocument="CollectionPersisterComment", strategy="set") */ - public $comments = array(); - - function __construct($comment, $by) - { - $this->comments = new \Doctrine\Common\Collections\ArrayCollection(); - $this->comment = $comment; - $this->by = $by; - } + public $comments = []; + + function __construct($comment, $by) + { + $this->comments = new ArrayCollection(); + $this->comment = $comment; + $this->by = $by; + } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/CollectionsTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/CollectionsTest.php index 9760945d20..c027e0f5dd 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/CollectionsTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/CollectionsTest.php @@ -1,13 +1,16 @@ markTestSkipped('mongodb-driver: query logging does not exist'); - if ( ! isset($this->ql)) { + if (! isset($this->ql)) { $this->ql = new QueryLogger(); } @@ -68,8 +73,7 @@ public function testCollectionsAreUpdatedJustAfterOwningDocument() $troll->setVersion(3); try { $this->dm->flush(); - } catch (\Doctrine\ODM\MongoDB\LockException $ex) { - + } catch (LockException $ex) { } $this->dm->clear(); @@ -137,22 +141,22 @@ public function testSchedulingCollectionDeletionAfterSchedulingForUpdate() class PhonenumberMachine implements EventSubscriber { - private $numbers = array('12345678', '87654321'); + private $numbers = ['12345678', '87654321']; private $numberId = 0; public function getSubscribedEvents() { - return array( + return [ Events::postPersist, Events::postUpdate, - ); + ]; } public function __call($eventName, $args) { $document = $args[0]->getDocument(); - if ( ! ($document instanceof User)) { + if (! ($document instanceof User)) { return; } // hey I just met you, and this is crazy! @@ -165,8 +169,8 @@ public function __call($eventName, $args) // prove that even this won't break our flow $dm = $args[0]->getDocumentManager(); $dm->getUnitOfWork()->recomputeSingleDocumentChangeSet( - $dm->getClassMetadata(get_class($document)), - $document + $dm->getClassMetadata(get_class($document)), + $document ); } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/CustomCollectionsTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/CustomCollectionsTest.php index af5452a53f..a8817aaea4 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/CustomCollectionsTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/CustomCollectionsTest.php @@ -1,17 +1,20 @@ mapField(array( + $cm->mapField([ 'fieldName' => 'assoc', 'reference' => true, 'type' => 'many', 'collectionClass' => 'stdClass', - )); + ]); } public function testGeneratedClassExtendsBaseCollection() @@ -234,14 +237,14 @@ class MyEmbedsCollection extends ArrayCollection { public function getByName($name) { - return $this->filter(function($item) use ($name) { + return $this->filter(function ($item) use ($name) { return $item->name === $name; }); } public function getEnabled() { - return $this->filter(function($item) { + return $this->filter(function ($item) { return $item->enabled; }); } @@ -258,7 +261,7 @@ class MyDocumentsCollection extends ArrayCollection { public function havingEmbeds() { - return $this->filter(function($item) { + return $this->filter(function ($item) { return $item->coll->count(); }); } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/CustomFieldNameTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/CustomFieldNameTest.php index 724cb9bbc1..3cde001660 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/CustomFieldNameTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/CustomFieldNameTest.php @@ -1,10 +1,13 @@ dm->persist($test); $this->dm->flush(); - $test = $this->dm->getDocumentCollection(__NAMESPACE__.'\CustomFieldName')->findOne(); + $test = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CustomFieldName')->findOne(); $this->assertArrayHasKey('login', $test); $this->assertEquals('test', $test['login']); } @@ -28,7 +31,7 @@ public function testHydration() $this->dm->flush(); $this->dm->clear(); - $test = $this->dm->find(__NAMESPACE__.'\CustomFieldName', $test->id); + $test = $this->dm->find(__NAMESPACE__ . '\CustomFieldName', $test->id); $this->assertNotNull($test); $this->assertEquals('test', $test->username); } @@ -42,12 +45,12 @@ public function testUpdateSetsLoginInsteadOfUsername() $this->dm->flush(); $this->dm->clear(); - $test = $this->dm->find(__NAMESPACE__.'\CustomFieldName', $test->id); + $test = $this->dm->find(__NAMESPACE__ . '\CustomFieldName', $test->id); $test->username = 'ok'; $this->dm->flush(); - $test = $this->dm->getDocumentCollection(__NAMESPACE__.'\CustomFieldName')->findOne(); + $test = $this->dm->getDocumentCollection(__NAMESPACE__ . '\CustomFieldName')->findOne(); $this->assertArrayHasKey('login', $test); $this->assertEquals('ok', $test['login']); } @@ -61,7 +64,7 @@ public function testFindOneQueryIsPrepared() $this->dm->flush(); $this->dm->clear(); - $test = $this->dm->getRepository(__NAMESPACE__.'\CustomFieldName')->findOneBy(array('username' => 'test')); + $test = $this->dm->getRepository(__NAMESPACE__ . '\CustomFieldName')->findOneBy(['username' => 'test']); $this->assertNotNull($test); $this->assertEquals('test', $test->username); } @@ -75,7 +78,7 @@ public function testFindQueryIsPrepared() $this->dm->flush(); $this->dm->clear(); - $test = $this->dm->getRepository(__NAMESPACE__.'\CustomFieldName')->findOneBy(array('username' => 'test')); + $test = $this->dm->getRepository(__NAMESPACE__ . '\CustomFieldName')->findOneBy(['username' => 'test']); $this->assertNotNull($test); $this->assertEquals('test', $test->username); } @@ -89,7 +92,7 @@ public function testQueryBuilderAndDqlArePrepared() $this->dm->flush(); $this->dm->clear(); - $qb = $this->dm->createQueryBuilder(__NAMESPACE__.'\CustomFieldName')->field('username')->equals('test'); + $qb = $this->dm->createQueryBuilder(__NAMESPACE__ . '\CustomFieldName')->field('username')->equals('test'); $query = $qb->getQuery(); $test = $query->getSingleResult(); $this->assertNotNull($test); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/CustomIdTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/CustomIdTest.php index 84965a972f..2303452bda 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/CustomIdTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/CustomIdTest.php @@ -1,12 +1,16 @@ dm->getRepository("Documents\User")->findAll(); + $users = $this->dm->getRepository('Documents\User')->findAll(); $this->assertCount(2, $users); - $results = array(); + $results = []; foreach ($users as $user) { if ($user->getId() === 'userId') { $results['userId'] = true; @@ -87,7 +91,7 @@ public function testBatchInsertCustomId() $results['ids'][] = $user->getId(); } - $users = $this->dm->getRepository("Documents\CustomUser")->findAll(); + $users = $this->dm->getRepository('Documents\CustomUser')->findAll(); $this->assertCount(1, $users); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/CustomTypeTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/CustomTypeTest.php index 0ae8ce35c8..753339ac24 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/CustomTypeTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/CustomTypeTest.php @@ -1,12 +1,18 @@ nationalHolidays = array(new \DateTime(), new \DateTime()); + $country->nationalHolidays = [new \DateTime(), new \DateTime()]; $this->dm->persist($country); $this->dm->flush(); @@ -52,13 +58,13 @@ public function convertToDatabaseValue($value) return null; } - if (!is_array($value)) { + if (! is_array($value)) { throw new CustomTypeException('Array expected.'); } $converter = Type::getType('date'); - $value = array_map(function($date) use ($converter) { + $value = array_map(function ($date) use ($converter) { return $converter->convertToDatabaseValue($date); }, array_values($value)); @@ -71,13 +77,13 @@ public function convertToPHPValue($value) return null; } - if (!is_array($value)) { + if (! is_array($value)) { throw new CustomTypeException('Array expected.'); } $converter = Type::getType('date'); - $value = array_map(function($date) use ($converter) { + $value = array_map(function ($date) use ($converter) { return $converter->convertToPHPValue($date); }, array_values($value)); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/DatabasesTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/DatabasesTest.php index 88e27c0f51..2ed1efc757 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/DatabasesTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/DatabasesTest.php @@ -1,10 +1,13 @@ dm->flush(); $this->dm->clear(); - $user = $this->dm->getRepository(get_class($user))->findOneBy(array()); + $user = $this->dm->getRepository(get_class($user))->findOneBy([]); $user->setCreatedAt($newValue); $this->dm->getUnitOfWork()->computeChangeSets(); $changeset = $this->dm->getUnitOfWork()->getDocumentChangeset($user); @@ -49,14 +53,14 @@ public function testDateInstanceChangeDoesNotCauseUpdateIfValueIsTheSame($oldVal public function provideEquivalentDates() { - return array( - array(new \DateTime('1985-09-01 00:00:00'), new \DateTime('1985-09-01 00:00:00')), - array(new \DateTime('2012-07-11T14:55:14-04:00'), new \DateTime('2012-07-11T19:55:14+01:00')), - array(new \DateTime('@1342033881'), new \MongoDB\BSON\UTCDateTime(1342033881000)), - array(\DateTime::createFromFormat('U.u', '100000000.123'), new \MongoDB\BSON\UTCDateTime(100000000123)), - array(\DateTime::createFromFormat('U.u', '100000000.123000'), new \MongoDB\BSON\UTCDateTime(100000000123)), - array(new \MongoDB\BSON\UTCDateTime(100000000123), \DateTime::createFromFormat('U.u', '100000000.123')), - ); + return [ + [new \DateTime('1985-09-01 00:00:00'), new \DateTime('1985-09-01 00:00:00')], + [new \DateTime('2012-07-11T14:55:14-04:00'), new \DateTime('2012-07-11T19:55:14+01:00')], + [new \DateTime('@1342033881'), new UTCDateTime(1342033881000)], + [\DateTime::createFromFormat('U.u', '100000000.123'), new UTCDateTime(100000000123)], + [\DateTime::createFromFormat('U.u', '100000000.123000'), new UTCDateTime(100000000123)], + [new UTCDateTime(100000000123), \DateTime::createFromFormat('U.u', '100000000.123')], + ]; } public function testDateInstanceValueChangeDoesCauseUpdateIfValueIsTheSame() @@ -67,7 +71,7 @@ public function testDateInstanceValueChangeDoesCauseUpdateIfValueIsTheSame() $this->dm->flush(); $this->dm->clear(); - $user = $this->dm->getRepository(get_class($user))->findOneBy(array()); + $user = $this->dm->getRepository(get_class($user))->findOneBy([]); $user->getCreatedAt()->setTimestamp(time() - 3600); $this->dm->getUnitOfWork()->computeChangeSets(); @@ -92,10 +96,10 @@ public function testOldDate() $this->dm->clear(); - $test = $this->dm->getDocumentCollection('Documents\User')->findOne(array('username' => 'datetest2')); + $test = $this->dm->getDocumentCollection('Documents\User')->findOne(['username' => 'datetest2']); $this->assertArrayHasKey('createdAt', $test); - $user = $this->dm->getRepository('Documents\User')->findOneBy(array('username' => 'datetest2')); + $user = $this->dm->getRepository('Documents\User')->findOneBy(['username' => 'datetest2']); $this->assertInstanceOf(\DateTime::class, $user->getCreatedAt()); $this->assertEquals('1900-01-01', $user->getCreatedAt()->format('Y-m-d')); } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/DetachedDocumentTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/DetachedDocumentTest.php index 271bb5dea5..84273dbc54 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/DetachedDocumentTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/DetachedDocumentTest.php @@ -1,17 +1,23 @@ name = 'Roman'; $user->username = 'romanb'; $user->status = 'dev'; @@ -36,12 +42,12 @@ public function testSimpleDetachMerge() public function testSerializeUnserializeModifyMerge() { - $user = new CmsUser; + $user = new CmsUser(); $user->name = 'Guilherme'; $user->username = 'gblanco'; $user->status = 'developer'; - $ph1 = new CmsPhonenumber; + $ph1 = new CmsPhonenumber(); $ph1->phonenumber = '1234'; $user->addPhonenumber($ph1); @@ -58,7 +64,7 @@ public function testSerializeUnserializeModifyMerge() $user = unserialize($serialized); - $ph2 = new CmsPhonenumber; + $ph2 = new CmsPhonenumber(); $ph2->phonenumber = '56789'; $user->addPhonenumber($ph2); $this->assertCount(2, $user->getPhonenumbers()); @@ -84,31 +90,14 @@ public function testSerializeUnserializeModifyMerge() $this->assertTrue($this->dm->contains($phonenumbers[1])); } - /** - * @group DDC-203 - */ - public function testDetachedEntityThrowsExceptionOnFlush() - { - $ph = new CmsPhonenumber(); - $ph->phonenumber = '12345'; - $this->dm->persist($ph); - $this->dm->flush(); - $this->dm->clear(); - $this->dm->persist($ph); - try { - $this->dm->flush(); - $this->fail(); - } catch (\Exception $expected) {} - } - public function testUninitializedLazyAssociationsAreIgnoredOnMerge() { - $user = new CmsUser; + $user = new CmsUser(); $user->name = 'Guilherme'; $user->username = 'gblanco'; $user->status = 'developer'; - $address = new CmsAddress; + $address = new CmsAddress(); $address->city = 'Berlin'; $address->country = 'Germany'; $address->street = 'Sesamestreet'; diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/DiscriminatorsDefaultValueTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/DiscriminatorsDefaultValueTest.php index fda5dfb3c0..d261ac66f9 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/DiscriminatorsDefaultValueTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/DiscriminatorsDefaultValueTest.php @@ -1,10 +1,13 @@ dm->persist($firstChildWithoutDiscriminator = new ChildDocumentWithoutDiscriminator('firstWithoutDiscriminator')); $this->dm->persist($secondChildWithoutDiscriminator = new ChildDocumentWithoutDiscriminator('firstWithoutDiscriminator')); - $children = array($firstChildWithoutDiscriminator, $secondChildWithoutDiscriminator); + $children = [$firstChildWithoutDiscriminator, $secondChildWithoutDiscriminator]; $this->dm->persist($parentWithoutDiscriminator = new ParentDocumentWithoutDiscriminator($children)); $this->dm->flush(); @@ -52,7 +55,7 @@ public function testLoadDocumentWithDifferentChild() $this->dm->persist($firstChildWithDiscriminator = new ChildDocumentWithDiscriminatorComplex('firstWithDiscriminator', 'veryComplex')); $this->dm->persist($secondChildWithDiscriminator = new ChildDocumentWithDiscriminatorSimple('secondWithDiscriminator')); - $children = array($firstChildWithDiscriminator, $secondChildWithDiscriminator); + $children = [$firstChildWithDiscriminator, $secondChildWithDiscriminator]; $this->dm->persist($parentWithDiscriminator = new ParentDocumentWithDiscriminator($children)); $this->dm->flush(); @@ -203,7 +206,6 @@ class ParentDocumentWithDiscriminator extends ParentDocument */ class ChildDocumentWithDiscriminator extends ChildDocument { - } /** @ODM\Document(collection="discriminator_child") */ diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/DocumentPersisterTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/DocumentPersisterTest.php index 5b2c96586b..8030b8fd34 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/DocumentPersisterTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/DocumentPersisterTest.php @@ -1,12 +1,17 @@ dm->getDocumentCollection($this->class); $collection->drop(); - foreach (array('a', 'b', 'c', 'd') as $name) { - $document = array('dbName' => $name); + foreach (['a', 'b', 'c', 'd'] as $name) { + $document = ['dbName' => $name]; $collection->insertOne($document); } @@ -42,15 +47,15 @@ public function testExecuteUpsertShouldNeverReplaceDocuments() $this->dm->persist($document); $this->dm->flush(); - $updatedData = $this->dm->getDocumentCollection($this->class)->findOne(array('_id' => $originalData['_id'])); + $updatedData = $this->dm->getDocumentCollection($this->class)->findOne(['_id' => $originalData['_id']]); $this->assertEquals($originalData, $updatedData); } public function testExistsReturnsTrueForExistentDocuments() { - foreach (array('a', 'b', 'c', 'd') as $name) { - $document = $this->documentPersister->load(array('name' => $name)); + foreach (['a', 'b', 'c', 'd'] as $name) { + $document = $this->documentPersister->load(['name' => $name]); $this->assertTrue($this->documentPersister->exists($document)); } } @@ -58,17 +63,17 @@ public function testExistsReturnsTrueForExistentDocuments() public function testExistsReturnsFalseForNonexistentDocuments() { $document = new DocumentPersisterTestDocument(); - $document->id = new \MongoDB\BSON\ObjectId(); + $document->id = new ObjectId(); $this->assertFalse($this->documentPersister->exists($document)); } public function testLoadPreparesCriteriaAndSort() { - $criteria = array('name' => array('$in' => array('a', 'b'))); - $sort = array('name' => -1); + $criteria = ['name' => ['$in' => ['a', 'b']]]; + $sort = ['name' => -1]; - $document = $this->documentPersister->load($criteria, null, array(), 0, $sort); + $document = $this->documentPersister->load($criteria, null, [], 0, $sort); $this->assertInstanceOf($this->class, $document); $this->assertEquals('b', $document->name); @@ -76,8 +81,8 @@ public function testLoadPreparesCriteriaAndSort() public function testLoadAllPreparesCriteriaAndSort() { - $criteria = array('name' => array('$in' => array('a', 'b'))); - $sort = array('name' => -1); + $criteria = ['name' => ['$in' => ['a', 'b']]]; + $sort = ['name' => -1]; $cursor = $this->documentPersister->loadAll($criteria, $sort); $documents = $cursor->toArray(); @@ -90,9 +95,9 @@ public function testLoadAllPreparesCriteriaAndSort() public function testLoadAllWithSortLimitAndSkip() { - $sort = array('name' => -1); + $sort = ['name' => -1]; - $cursor = $this->documentPersister->loadAll(array(), $sort, 1, 2); + $cursor = $this->documentPersister->loadAll([], $sort, 1, 2); $documents = $cursor->toArray(); $this->assertInstanceOf($this->class, $documents[0]); @@ -110,18 +115,18 @@ public function testPrepareFieldName($fieldName, $expected) public function getTestPrepareFieldNameData() { - return array( - array('name', 'dbName'), - array('association', 'associationName'), - array('association.id', 'associationName._id'), - array('association.nested', 'associationName.nestedName'), - array('association.nested.$id', 'associationName.nestedName.$id'), - array('association.nested._id', 'associationName.nestedName._id'), - array('association.nested.id', 'associationName.nestedName._id'), - array('association.nested.association.nested.$id', 'associationName.nestedName.associationName.nestedName.$id'), - array('association.nested.association.nested.id', 'associationName.nestedName.associationName.nestedName._id'), - array('association.nested.association.nested.firstName', 'associationName.nestedName.associationName.nestedName.firstName'), - ); + return [ + ['name', 'dbName'], + ['association', 'associationName'], + ['association.id', 'associationName._id'], + ['association.nested', 'associationName.nestedName'], + ['association.nested.$id', 'associationName.nestedName.$id'], + ['association.nested._id', 'associationName.nestedName._id'], + ['association.nested.id', 'associationName.nestedName._id'], + ['association.nested.association.nested.$id', 'associationName.nestedName.associationName.nestedName.$id'], + ['association.nested.association.nested.id', 'associationName.nestedName.associationName.nestedName._id'], + ['association.nested.association.nested.firstName', 'associationName.nestedName.associationName.nestedName.firstName'], + ]; } /** @@ -132,8 +137,8 @@ public function testPrepareQueryOrNewObjWithHashId($hashId) $class = DocumentPersisterTestHashIdDocument::class; $documentPersister = $this->uow->getDocumentPersister($class); - $value = array('_id' => $hashId); - $expected = array('_id' => (object) $hashId); + $value = ['_id' => $hashId]; + $expected = ['_id' => (object) $hashId]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); } @@ -146,39 +151,39 @@ public function testPrepareQueryOrNewObjWithHashIdAndInOperators($hashId) $class = DocumentPersisterTestHashIdDocument::class; $documentPersister = $this->uow->getDocumentPersister($class); - $value = array('_id' => array('$exists' => true)); - $expected = array('_id' => array('$exists' => true)); + $value = ['_id' => ['$exists' => true]]; + $expected = ['_id' => ['$exists' => true]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('_id' => array('$elemMatch' => $hashId)); - $expected = array('_id' => array('$elemMatch' => (object) $hashId)); + $value = ['_id' => ['$elemMatch' => $hashId]]; + $expected = ['_id' => ['$elemMatch' => (object) $hashId]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('_id' => array('$in' => array($hashId))); - $expected = array('_id' => array('$in' => array((object) $hashId))); + $value = ['_id' => ['$in' => [$hashId]]]; + $expected = ['_id' => ['$in' => [(object) $hashId]]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('_id' => array('$not' => array('$elemMatch' => $hashId))); - $expected = array('_id' => array('$not' => array('$elemMatch' => (object) $hashId))); + $value = ['_id' => ['$not' => ['$elemMatch' => $hashId]]]; + $expected = ['_id' => ['$not' => ['$elemMatch' => (object) $hashId]]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('_id' => array('$not' => array('$in' => array($hashId)))); - $expected = array('_id' => array('$not' => array('$in' => array((object) $hashId)))); + $value = ['_id' => ['$not' => ['$in' => [$hashId]]]]; + $expected = ['_id' => ['$not' => ['$in' => [(object) $hashId]]]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); } public function provideHashIdentifiers() { - return array( - array(array('key' => 'value')), - array(array(0 => 'first', 1 => 'second')), - array(array('$ref' => 'ref', '$id' => 'id')), - ); + return [ + [['key' => 'value']], + [[0 => 'first', 1 => 'second']], + [['$ref' => 'ref', '$id' => 'id']], + ]; } public function testPrepareQueryOrNewObjWithSimpleReferenceToTargetDocumentWithNormalIdType() @@ -186,35 +191,35 @@ public function testPrepareQueryOrNewObjWithSimpleReferenceToTargetDocumentWithN $class = DocumentPersisterTestHashIdDocument::class; $documentPersister = $this->uow->getDocumentPersister($class); - $id = new \MongoDB\BSON\ObjectId(); + $id = new ObjectId(); - $value = array('simpleRef' => (string) $id); - $expected = array('simpleRef' => $id); + $value = ['simpleRef' => (string) $id]; + $expected = ['simpleRef' => $id]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('simpleRef' => array('$exists' => true)); - $expected = array('simpleRef' => array('$exists' => true)); + $value = ['simpleRef' => ['$exists' => true]]; + $expected = ['simpleRef' => ['$exists' => true]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('simpleRef' => array('$elemMatch' => (string) $id)); - $expected = array('simpleRef' => array('$elemMatch' => $id)); + $value = ['simpleRef' => ['$elemMatch' => (string) $id]]; + $expected = ['simpleRef' => ['$elemMatch' => $id]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('simpleRef' => array('$in' => array((string) $id))); - $expected = array('simpleRef' => array('$in' => array($id))); + $value = ['simpleRef' => ['$in' => [(string) $id]]]; + $expected = ['simpleRef' => ['$in' => [$id]]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('simpleRef' => array('$not' => array('$elemMatch' => (string) $id))); - $expected = array('simpleRef' => array('$not' => array('$elemMatch' => $id))); + $value = ['simpleRef' => ['$not' => ['$elemMatch' => (string) $id]]]; + $expected = ['simpleRef' => ['$not' => ['$elemMatch' => $id]]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('simpleRef' => array('$not' => array('$in' => array((string) $id)))); - $expected = array('simpleRef' => array('$not' => array('$in' => array($id)))); + $value = ['simpleRef' => ['$not' => ['$in' => [(string) $id]]]]; + $expected = ['simpleRef' => ['$not' => ['$in' => [$id]]]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); } @@ -227,33 +232,33 @@ public function testPrepareQueryOrNewObjWithSimpleReferenceToTargetDocumentWithH $class = DocumentPersisterTestDocument::class; $documentPersister = $this->uow->getDocumentPersister($class); - $value = array('simpleRef' => $hashId); - $expected = array('simpleRef' => (object) $hashId); + $value = ['simpleRef' => $hashId]; + $expected = ['simpleRef' => (object) $hashId]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('simpleRef' => array('$exists' => true)); - $expected = array('simpleRef' => array('$exists' => true)); + $value = ['simpleRef' => ['$exists' => true]]; + $expected = ['simpleRef' => ['$exists' => true]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('simpleRef' => array('$elemMatch' => $hashId)); - $expected = array('simpleRef' => array('$elemMatch' => (object) $hashId)); + $value = ['simpleRef' => ['$elemMatch' => $hashId]]; + $expected = ['simpleRef' => ['$elemMatch' => (object) $hashId]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('simpleRef' => array('$in' => array($hashId))); - $expected = array('simpleRef' => array('$in' => array((object) $hashId))); + $value = ['simpleRef' => ['$in' => [$hashId]]]; + $expected = ['simpleRef' => ['$in' => [(object) $hashId]]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('simpleRef' => array('$not' => array('$elemMatch' => $hashId))); - $expected = array('simpleRef' => array('$not' => array('$elemMatch' => (object) $hashId))); + $value = ['simpleRef' => ['$not' => ['$elemMatch' => $hashId]]]; + $expected = ['simpleRef' => ['$not' => ['$elemMatch' => (object) $hashId]]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('simpleRef' => array('$not' => array('$in' => array($hashId)))); - $expected = array('simpleRef' => array('$not' => array('$in' => array((object) $hashId)))); + $value = ['simpleRef' => ['$not' => ['$in' => [$hashId]]]]; + $expected = ['simpleRef' => ['$not' => ['$in' => [(object) $hashId]]]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); } @@ -263,35 +268,35 @@ public function testPrepareQueryOrNewObjWithDBRefReferenceToTargetDocumentWithNo $class = DocumentPersisterTestHashIdDocument::class; $documentPersister = $this->uow->getDocumentPersister($class); - $id = new \MongoDB\BSON\ObjectId(); + $id = new ObjectId(); - $value = array('complexRef.id' => (string) $id); - $expected = array('complexRef.$id' => $id); + $value = ['complexRef.id' => (string) $id]; + $expected = ['complexRef.$id' => $id]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('complexRef.id' => array('$exists' => true)); - $expected = array('complexRef.$id' => array('$exists' => true)); + $value = ['complexRef.id' => ['$exists' => true]]; + $expected = ['complexRef.$id' => ['$exists' => true]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('complexRef.id' => array('$elemMatch' => (string) $id)); - $expected = array('complexRef.$id' => array('$elemMatch' => $id)); + $value = ['complexRef.id' => ['$elemMatch' => (string) $id]]; + $expected = ['complexRef.$id' => ['$elemMatch' => $id]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('complexRef.id' => array('$in' => array((string) $id))); - $expected = array('complexRef.$id' => array('$in' => array($id))); + $value = ['complexRef.id' => ['$in' => [(string) $id]]]; + $expected = ['complexRef.$id' => ['$in' => [$id]]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('complexRef.id' => array('$not' => array('$elemMatch' => (string) $id))); - $expected = array('complexRef.$id' => array('$not' => array('$elemMatch' => $id))); + $value = ['complexRef.id' => ['$not' => ['$elemMatch' => (string) $id]]]; + $expected = ['complexRef.$id' => ['$not' => ['$elemMatch' => $id]]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('complexRef.id' => array('$not' => array('$in' => array((string) $id)))); - $expected = array('complexRef.$id' => array('$not' => array('$in' => array($id)))); + $value = ['complexRef.id' => ['$not' => ['$in' => [(string) $id]]]]; + $expected = ['complexRef.$id' => ['$not' => ['$in' => [$id]]]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); } @@ -304,33 +309,33 @@ public function testPrepareQueryOrNewObjWithDBRefReferenceToTargetDocumentWithHa $class = DocumentPersisterTestDocument::class; $documentPersister = $this->uow->getDocumentPersister($class); - $value = array('complexRef.id' => $hashId); - $expected = array('complexRef.$id' => (object) $hashId); + $value = ['complexRef.id' => $hashId]; + $expected = ['complexRef.$id' => (object) $hashId]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('complexRef.id' => array('$exists' => true)); - $expected = array('complexRef.$id' => array('$exists' => true)); + $value = ['complexRef.id' => ['$exists' => true]]; + $expected = ['complexRef.$id' => ['$exists' => true]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('complexRef.id' => array('$elemMatch' => $hashId)); - $expected = array('complexRef.$id' => array('$elemMatch' => (object) $hashId)); + $value = ['complexRef.id' => ['$elemMatch' => $hashId]]; + $expected = ['complexRef.$id' => ['$elemMatch' => (object) $hashId]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('complexRef.id' => array('$in' => array($hashId))); - $expected = array('complexRef.$id' => array('$in' => array((object) $hashId))); + $value = ['complexRef.id' => ['$in' => [$hashId]]]; + $expected = ['complexRef.$id' => ['$in' => [(object) $hashId]]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('complexRef.id' => array('$not' => array('$elemMatch' => $hashId))); - $expected = array('complexRef.$id' => array('$not' => array('$elemMatch' => (object) $hashId))); + $value = ['complexRef.id' => ['$not' => ['$elemMatch' => $hashId]]]; + $expected = ['complexRef.$id' => ['$not' => ['$elemMatch' => (object) $hashId]]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('complexRef.id' => array('$not' => array('$in' => array($hashId)))); - $expected = array('complexRef.$id' => array('$not' => array('$in' => array((object) $hashId)))); + $value = ['complexRef.id' => ['$not' => ['$in' => [$hashId]]]]; + $expected = ['complexRef.$id' => ['$not' => ['$in' => [(object) $hashId]]]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); } @@ -340,35 +345,35 @@ public function testPrepareQueryOrNewObjWithEmbeddedReferenceToTargetDocumentWit $class = DocumentPersisterTestHashIdDocument::class; $documentPersister = $this->uow->getDocumentPersister($class); - $id = new \MongoDB\BSON\ObjectId(); + $id = new ObjectId(); - $value = array('embeddedRef.id' => (string) $id); - $expected = array('embeddedRef.id' => $id); + $value = ['embeddedRef.id' => (string) $id]; + $expected = ['embeddedRef.id' => $id]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('embeddedRef.id' => array('$exists' => true)); - $expected = array('embeddedRef.id' => array('$exists' => true)); + $value = ['embeddedRef.id' => ['$exists' => true]]; + $expected = ['embeddedRef.id' => ['$exists' => true]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('embeddedRef.id' => array('$elemMatch' => (string) $id)); - $expected = array('embeddedRef.id' => array('$elemMatch' => $id)); + $value = ['embeddedRef.id' => ['$elemMatch' => (string) $id]]; + $expected = ['embeddedRef.id' => ['$elemMatch' => $id]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('embeddedRef.id' => array('$in' => array((string) $id))); - $expected = array('embeddedRef.id' => array('$in' => array($id))); + $value = ['embeddedRef.id' => ['$in' => [(string) $id]]]; + $expected = ['embeddedRef.id' => ['$in' => [$id]]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('embeddedRef.id' => array('$not' => array('$elemMatch' => (string) $id))); - $expected = array('embeddedRef.id' => array('$not' => array('$elemMatch' => $id))); + $value = ['embeddedRef.id' => ['$not' => ['$elemMatch' => (string) $id]]]; + $expected = ['embeddedRef.id' => ['$not' => ['$elemMatch' => $id]]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('embeddedRef.id' => array('$not' => array('$in' => array((string) $id)))); - $expected = array('embeddedRef.id' => array('$not' => array('$in' => array($id)))); + $value = ['embeddedRef.id' => ['$not' => ['$in' => [(string) $id]]]]; + $expected = ['embeddedRef.id' => ['$not' => ['$in' => [$id]]]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); } @@ -381,33 +386,33 @@ public function testPrepareQueryOrNewObjWithEmbeddedReferenceToTargetDocumentWit $class = DocumentPersisterTestDocument::class; $documentPersister = $this->uow->getDocumentPersister($class); - $value = array('embeddedRef.id' => $hashId); - $expected = array('embeddedRef.id' => (object) $hashId); + $value = ['embeddedRef.id' => $hashId]; + $expected = ['embeddedRef.id' => (object) $hashId]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('embeddedRef.id' => array('$exists' => true)); - $expected = array('embeddedRef.id' => array('$exists' => true)); + $value = ['embeddedRef.id' => ['$exists' => true]]; + $expected = ['embeddedRef.id' => ['$exists' => true]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('embeddedRef.id' => array('$elemMatch' => $hashId)); - $expected = array('embeddedRef.id' => array('$elemMatch' => (object) $hashId)); + $value = ['embeddedRef.id' => ['$elemMatch' => $hashId]]; + $expected = ['embeddedRef.id' => ['$elemMatch' => (object) $hashId]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('embeddedRef.id' => array('$in' => array($hashId))); - $expected = array('embeddedRef.id' => array('$in' => array((object) $hashId))); + $value = ['embeddedRef.id' => ['$in' => [$hashId]]]; + $expected = ['embeddedRef.id' => ['$in' => [(object) $hashId]]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('embeddedRef.id' => array('$not' => array('$elemMatch' => $hashId))); - $expected = array('embeddedRef.id' => array('$not' => array('$elemMatch' => (object) $hashId))); + $value = ['embeddedRef.id' => ['$not' => ['$elemMatch' => $hashId]]]; + $expected = ['embeddedRef.id' => ['$not' => ['$elemMatch' => (object) $hashId]]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); - $value = array('embeddedRef.id' => array('$not' => array('$in' => array($hashId)))); - $expected = array('embeddedRef.id' => array('$not' => array('$in' => array((object) $hashId)))); + $value = ['embeddedRef.id' => ['$not' => ['$in' => [$hashId]]]]; + $expected = ['embeddedRef.id' => ['$not' => ['$in' => [(object) $hashId]]]]; $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); } @@ -417,24 +422,24 @@ public function testPrepareQueryOrNewObjWithEmbeddedReferenceToTargetDocumentWit */ public static function dataProviderTestWriteConcern() { - return array( - 'default' => array( + return [ + 'default' => [ 'className' => DocumentPersisterTestDocument::class, 'writeConcern' => 1, - ), - 'acknowledged' => array( + ], + 'acknowledged' => [ 'className' => DocumentPersisterWriteConcernAcknowledged::class, 'writeConcern' => 1, - ), - 'unacknowledged' => array( + ], + 'unacknowledged' => [ 'className' => DocumentPersisterWriteConcernUnacknowledged::class, 'writeConcern' => 0, - ), - 'majority' => array( + ], + 'majority' => [ 'className' => DocumentPersisterWriteConcernMajority::class, 'writeConcern' => 'majority', - ), - ); + ], + ]; } /** @@ -481,7 +486,7 @@ public function testExecuteUpsertsRespectsWriteConcern($class, $writeConcern) $reflectionProperty->setValue($documentPersister, $collection); $testDocument = new $class(); - $testDocument->id = new \MongoDB\BSON\ObjectId(); + $testDocument->id = new ObjectId(); $this->dm->persist($testDocument); $this->dm->flush(); } @@ -521,13 +526,13 @@ public function testDefaultWriteConcernIsRespected() $collection = $this->createMock(Collection::class); $collection->expects($this->once()) ->method('insertMany') - ->with($this->isType('array'), $this->equalTo(array('w' => 0))); + ->with($this->isType('array'), $this->equalTo(['w' => 0])); $reflectionProperty = new \ReflectionProperty($documentPersister, 'collection'); $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($documentPersister, $collection); - $this->dm->getConfiguration()->setDefaultCommitOptions(array('w' => 0)); + $this->dm->getConfiguration()->setDefaultCommitOptions(['w' => 0]); $testDocument = new $class(); $this->dm->persist($testDocument); @@ -544,7 +549,7 @@ public function testVersionIncrementOnUpdateSuccess() $collection = $this->createMock(Collection::class); $collection->expects($this->any()) ->method('updateOne') - ->will($this->returnValue(array('n' => 1))); + ->will($this->returnValue(['n' => 1])); $reflectionProperty = new \ReflectionProperty($documentPersister, 'collection'); $reflectionProperty->setAccessible(true); @@ -552,7 +557,7 @@ public function testVersionIncrementOnUpdateSuccess() $testDocument = new $class(); $testDocument->id = 12345; - $this->uow->registerManaged($testDocument, 12345, array('id' => 12345)); + $this->uow->registerManaged($testDocument, 12345, ['id' => 12345]); $testDocument->name = 'test'; $this->dm->persist($testDocument); $this->dm->flush(); @@ -570,7 +575,7 @@ public function testNoVersionIncrementOnUpdateFailure() $collection = $this->createMock(Collection::class); $collection->expects($this->any()) ->method('updateOne') - ->will($this->returnValue(array('n' => 0))); + ->will($this->returnValue(['n' => 0])); $reflectionProperty = new \ReflectionProperty($documentPersister, 'collection'); $reflectionProperty->setAccessible(true); @@ -578,8 +583,8 @@ public function testNoVersionIncrementOnUpdateFailure() $testDocument = new $class(); $testDocument->id = 12345; - $this->uow->registerManaged($testDocument, 12345, array('id' => 12345)); - $this->expectException(\Doctrine\ODM\MongoDB\LockException::class); + $this->uow->registerManaged($testDocument, 12345, ['id' => 12345]); + $this->expectException(LockException::class); $testDocument->name = 'test'; $this->dm->persist($testDocument); $this->dm->flush(); @@ -634,7 +639,6 @@ class DocumentPersisterTestDocumentWithVersion /** @ODM\Version @ODM\Field(type="int") */ public $revision = 1; - } /** diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/EcommerceTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/EcommerceTest.php index 0460170e15..6557700255 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/EcommerceTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/EcommerceTest.php @@ -1,20 +1,23 @@ 1, 'EURO' => 1.7, 'JPN' => 0.0125); + $currencies = ['USD' => 1, 'EURO' => 1.7, 'JPN' => 0.0125]; foreach ($currencies as $name => &$multiplier) { $multiplier = new Currency($name, $multiplier); @@ -45,11 +48,11 @@ public function testEmbedding() $this->assertCount(3, $product->getOptions()); $this->assertEquals(12.99, $product->getOption('small')->getPrice()); - $usdCurrency = $this->dm->getRepository('Documents\Ecommerce\Currency')->findOneBy(array('name' => 'USD')); + $usdCurrency = $this->dm->getRepository('Documents\Ecommerce\Currency')->findOneBy(['name' => 'USD']); $this->assertNotNull($usdCurrency); $usdCurrency->setMultiplier('2'); - $this->assertInstanceOf(\Documents\Ecommerce\StockItem::class, $product->getOption('small')->getStockItem()); + $this->assertInstanceOf(StockItem::class, $product->getOption('small')->getStockItem()); $this->assertNotNull($product->getOption('small')->getStockItem()->getId()); $this->assertEquals(12.99 * 2, $product->getOption('small')->getPrice()); } @@ -61,7 +64,7 @@ public function testMoneyDocumentsAvailableForReference() $currency = $price->getCurrency(); $this->assertInstanceOf(Currency::class, $currency); $this->assertNotNull($currency->getId()); - $this->assertEquals($currency, $this->dm->getRepository('Documents\Ecommerce\Currency')->findOneBy(array('name' => Currency::USD))); + $this->assertEquals($currency, $this->dm->getRepository('Documents\Ecommerce\Currency')->findOneBy(['name' => Currency::USD])); } public function testRemoveOption() diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/EmbeddedIdTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/EmbeddedIdTest.php index 826541d775..7b9ef0b5fa 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/EmbeddedIdTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/EmbeddedIdTest.php @@ -1,10 +1,14 @@ id = $id; @@ -61,7 +65,7 @@ class EmbeddedIdTestUser public $embedOne; /** @ODM\EmbedMany(targetDocument="DefaultIdEmbeddedDocument") */ - public $embedMany = array(); + public $embedMany = []; } /** @ODM\Document */ @@ -74,7 +78,7 @@ class EmbeddedStrategyNoneIdTestUser public $embedOne; /** @ODM\EmbedMany(targetDocument="DefaultIdStrategyNoneEmbeddedDocument") */ - public $embedMany = array(); + public $embedMany = []; } /** @ODM\EmbeddedDocument */ diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/EmbeddedReferenceTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/EmbeddedReferenceTest.php index 8030298430..2fbdc0754b 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/EmbeddedReferenceTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/EmbeddedReferenceTest.php @@ -1,12 +1,14 @@ setId((string) new \MongoDB\BSON\ObjectId()); + $user->setId((string) new ObjectId()); $user->setUsername('jwage'); $user->setAddress(null); @@ -45,7 +49,7 @@ public function testFlushEmbedded() $this->dm->flush(); $this->dm->clear(); - $test = $this->dm->getRepository('Documents\Functional\EmbeddedTestLevel0')->findOneBy(array('name' => 'test')); + $test = $this->dm->getRepository('Documents\Functional\EmbeddedTestLevel0')->findOneBy(['name' => 'test']); $this->assertInstanceOf('Documents\Functional\EmbeddedTestLevel0', $test); // Adding this flush here makes level1 not to be inserted. @@ -148,7 +152,7 @@ public function testRemoveOneEmbedded() public function testManyEmbedded() { - $user = new \Documents\User(); + $user = new User(); $user->addPhonenumber(new Phonenumber('6155139185')); $user->addPhonenumber(new Phonenumber('6153303769')); @@ -423,11 +427,11 @@ public function testRemoveAddDeepEmbedded() $vhost->getVHostDirective()->addDirective($directive1); $directive2 = new VirtualHostDirective('Directory', '/var/www/html'); - $directive2->addDirective(new VirtualHostDirective('AllowOverride','All')); + $directive2->addDirective(new VirtualHostDirective('AllowOverride', 'All')); $vhost->getVHostDirective()->addDirective($directive2); $directive3 = new VirtualHostDirective('Directory', '/var/www/html'); - $directive3->addDirective(new VirtualHostDirective('RewriteEngine','on')); + $directive3->addDirective(new VirtualHostDirective('RewriteEngine', 'on')); $vhost->getVHostDirective()->addDirective($directive3); $this->dm->persist($vhost); @@ -436,17 +440,15 @@ public function testRemoveAddDeepEmbedded() $vhost->getVHostDirective()->removeDirective($directive2); $directive4 = new VirtualHostDirective('Directory', '/var/www/html'); - $directive4->addDirective(new VirtualHostDirective('RewriteEngine','on')); + $directive4->addDirective(new VirtualHostDirective('RewriteEngine', 'on')); $vhost->getVHostDirective()->addDirective($directive4); - $this->dm->flush(); $this->dm->clear(); $vhost = $this->dm->find('Documents\Functional\VirtualHost', $vhost->getId()); - foreach($vhost->getVHostDirective()->getDirectives() as $directive) - { + foreach ($vhost->getVHostDirective()->getDirectives() as $directive) { $this->assertNotEmpty($directive->getName()); } } @@ -470,7 +472,7 @@ public function testEmbeddedDocumentNotSavedFields() public function testChangeEmbedOneDocumentId() { - $originalId = (string) new \MongoDB\BSON\ObjectId(); + $originalId = (string) new ObjectId(); $test = new ChangeEmbeddedIdTest(); $test->embed = new EmbeddedDocumentWithId(); @@ -479,7 +481,7 @@ public function testChangeEmbedOneDocumentId() $this->dm->flush(); - $newId = (string) new \MongoDB\BSON\ObjectId(); + $newId = (string) new ObjectId(); $test->embed->id = $newId; @@ -493,7 +495,7 @@ public function testChangeEmbedOneDocumentId() public function testChangeEmbedManyDocumentId() { - $originalId = (string) new \MongoDB\BSON\ObjectId(); + $originalId = (string) new ObjectId(); $test = new ChangeEmbeddedIdTest(); $test->embedMany[] = new EmbeddedDocumentWithId(); @@ -502,7 +504,7 @@ public function testChangeEmbedManyDocumentId() $this->dm->flush(); - $newId = (string) new \MongoDB\BSON\ObjectId(); + $newId = (string) new ObjectId(); $test->embedMany[0]->id = $newId; @@ -516,7 +518,7 @@ public function testChangeEmbedManyDocumentId() public function testEmbeddedDocumentsWithSameIdAreNotSameInstance() { - $originalId = (string) new \MongoDB\BSON\ObjectId(); + $originalId = (string) new ObjectId(); $test = new ChangeEmbeddedIdTest(); $test->embed = new EmbeddedDocumentWithId(); @@ -538,8 +540,8 @@ public function testWhenCopyingManyEmbedSubDocumentsFromOneDocumentToAnotherWill $test1 = new ChangeEmbeddedIdTest(); $embedded = new EmbeddedDocumentWithId(); - $embedded->id = (string) new \MongoDB\BSON\ObjectId(); - $test1->embedMany = array($embedded); + $embedded->id = (string) new ObjectId(); + $test1->embedMany = [$embedded]; $this->dm->persist($test1); $this->dm->flush(); @@ -552,7 +554,6 @@ public function testWhenCopyingManyEmbedSubDocumentsFromOneDocumentToAnotherWill $this->dm->flush(); - //do some operations on test1 $this->dm->persist($test1); $this->dm->flush(); @@ -569,7 +570,7 @@ public function testReusedEmbeddedDocumentsAreClonedInFact() $test2 = new ChangeEmbeddedIdTest(); $embedded = new EmbeddedDocumentWithId(); - $embedded->id = (string) new \MongoDB\BSON\ObjectId(); + $embedded->id = (string) new ObjectId(); $test1->embed = $embedded; $test2->embed = $embedded; @@ -592,7 +593,7 @@ public function testEmbeddedDocumentWithDifferentFieldNameAnnotation() $test1 = new ChangeEmbeddedWithNameAnnotationTest(); $embedded = new EmbeddedDocumentWithId(); - $embedded->id = (string) new \MongoDB\BSON\ObjectId(); + $embedded->id = (string) new ObjectId(); $firstEmbedded = new EmbedDocumentWithAnotherEmbed(); $firstEmbedded->embed = $embedded; diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/EnsureShardingTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/EnsureShardingTest.php index 60905414fa..71ca8db8e4 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/EnsureShardingTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/EnsureShardingTest.php @@ -1,9 +1,13 @@ skipTestIfNotSharded(\Documents\Sharded\ShardedOne::class); + $this->skipTestIfNotSharded(ShardedOne::class); } public function testEnsureShardingForNewCollection() { - $class = \Documents\Sharded\ShardedOne::class; + $class = ShardedOne::class; $this->dm->getSchemaManager()->ensureDocumentSharding($class); $collection = $this->dm->getDocumentCollection($class); $indexes = iterator_to_array($collection->listIndexes()); - $stats = $this->dm->getDocumentDatabase($class)->command(array('collstats' => $collection->getCollectionName()))->toArray()[0]; + $stats = $this->dm->getDocumentDatabase($class)->command(['collstats' => $collection->getCollectionName()])->toArray()[0]; $this->assertCount(2, $indexes); - $this->assertSame(array('k' => 1), $indexes[1]['key']); + $this->assertSame(['k' => 1], $indexes[1]['key']); $this->assertTrue($stats['sharded']); } public function testEnsureShardingForCollectionWithDocuments() { $this->markTestSkipped('Test does not pass due to https://github.com/mongodb/mongo-php-driver/issues/296'); - $class = \Documents\Sharded\ShardedOne::class; + $class = ShardedOne::class; $collection = $this->dm->getDocumentCollection($class); - $doc = array('title' => 'hey', 'k' => 'hi'); + $doc = ['title' => 'hey', 'k' => 'hi']; $collection->insertOne($doc); $this->dm->getSchemaManager()->ensureDocumentSharding($class); $indexes = iterator_to_array($collection->listIndexes()); - $stats = $this->dm->getDocumentDatabase($class)->command(array('collstats' => $collection->getCollectionName()))->toArray()[0]; + $stats = $this->dm->getDocumentDatabase($class)->command(['collstats' => $collection->getCollectionName()])->toArray()[0]; $this->assertCount(2, $indexes); - $this->assertSame(array('k' => 1), $indexes[1]['key']); + $this->assertSame(['k' => 1], $indexes[1]['key']); $this->assertTrue($stats['sharded']); } public function testEnsureShardingForCollectionWithShardingEnabled() { - $class = \Documents\Sharded\ShardedOneWithDifferentKey::class; + $class = ShardedOneWithDifferentKey::class; $this->dm->getSchemaManager()->ensureDocumentSharding($class); - $this->dm->getSchemaManager()->ensureDocumentSharding(\Documents\Sharded\ShardedOne::class); + $this->dm->getSchemaManager()->ensureDocumentSharding(ShardedOne::class); $collection = $this->dm->getDocumentCollection($class); $indexes = iterator_to_array($collection->listIndexes()); - $stats = $this->dm->getDocumentDatabase($class)->command(array('collstats' => $collection->getCollectionName()))->toArray()[0]; + $stats = $this->dm->getDocumentDatabase($class)->command(['collstats' => $collection->getCollectionName()])->toArray()[0]; $this->assertCount(2, $indexes); - $this->assertSame(array('v' => 1), $indexes[1]['key']); + $this->assertSame(['v' => 1], $indexes[1]['key']); $this->assertTrue($stats['sharded']); } public function testEnsureShardingForCollectionWithData() { $this->markTestSkipped('Test does not pass due to https://github.com/mongodb/mongo-php-driver/issues/296'); - $document = new \Documents\Sharded\ShardedOne(); + $document = new ShardedOne(); $this->dm->persist($document); $this->dm->flush(); - $class = \Documents\Sharded\ShardedOne::class; + $class = ShardedOne::class; $this->dm->getSchemaManager()->ensureDocumentSharding($class); $collection = $this->dm->getDocumentCollection($class); $indexes = iterator_to_array($collection->listIndexes()); - $stats = $this->dm->getDocumentDatabase($class)->command(array('collstats' => $collection->getCollectionName()))->toArray()[0]; + $stats = $this->dm->getDocumentDatabase($class)->command(['collstats' => $collection->getCollectionName()])->toArray()[0]; $this->assertCount(2, $indexes); - $this->assertSame(array('k' => 1), $indexes[1]['key']); + $this->assertSame(['k' => 1], $indexes[1]['key']); $this->assertTrue($stats['sharded']); } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/FilterTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/FilterTest.php index c371923125..568ed60a98 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/FilterTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/FilterTest.php @@ -1,18 +1,23 @@ ids = array(); + $this->ids = []; $groupA = new Group('groupA'); $groupB = new Group('groupB'); @@ -71,15 +76,15 @@ protected function enableProfileFilter() public function testRepositoryFind() { - $this->assertEquals(array('John', 'Tim'), $this->getUsernamesWithFind()); + $this->assertEquals(['John', 'Tim'], $this->getUsernamesWithFind()); $this->enableUserFilter(); $this->dm->clear(); - $this->assertEquals(array('Tim'), $this->getUsernamesWithFind()); + $this->assertEquals(['Tim'], $this->getUsernamesWithFind()); $this->fc->disable('testFilter'); $this->dm->clear(); - $this->assertEquals(array('John', 'Tim'), $this->getUsernamesWithFind()); + $this->assertEquals(['John', 'Tim'], $this->getUsernamesWithFind()); } protected function getUsernamesWithFind() @@ -89,12 +94,12 @@ protected function getUsernamesWithFind() $tim = $repository->find($this->ids['tim']); $john = $repository->find($this->ids['john']); - $usernames = array(); + $usernames = []; - if(isset($tim)) { + if (isset($tim)) { $usernames[] = $tim->getUsername(); } - if(isset($john)) { + if (isset($john)) { $usernames[] = $john->getUsername(); } @@ -104,22 +109,22 @@ protected function getUsernamesWithFind() public function testRepositoryFindBy() { - $this->assertEquals(array('John', 'Tim'), $this->getUsernamesWithFindBy()); + $this->assertEquals(['John', 'Tim'], $this->getUsernamesWithFindBy()); $this->enableUserFilter(); $this->dm->clear(); - $this->assertEquals(array('Tim'), $this->getUsernamesWithFindBy()); + $this->assertEquals(['Tim'], $this->getUsernamesWithFindBy()); $this->fc->disable('testFilter'); $this->dm->clear(); - $this->assertEquals(array('John', 'Tim'), $this->getUsernamesWithFindBy()); + $this->assertEquals(['John', 'Tim'], $this->getUsernamesWithFindBy()); } protected function getUsernamesWithFindBy() { - $all = $this->dm->getRepository('Documents\User')->findBy(array('hits' => 10)); + $all = $this->dm->getRepository('Documents\User')->findBy(['hits' => 10]); - $usernames = array(); + $usernames = []; foreach ($all as $user) { $usernames[] = $user->getUsername(); } @@ -142,29 +147,29 @@ public function testRepositoryFindOneBy() protected function getJohnsUsernameWithFindOneBy() { - $john = $this->dm->getRepository('Documents\User')->findOneBy(array('id' => $this->ids['john'])); + $john = $this->dm->getRepository('Documents\User')->findOneBy(['id' => $this->ids['john']]); return isset($john) ? $john->getUsername() : null; } public function testRepositoryFindAll() { - $this->assertEquals(array('John', 'Tim'), $this->getUsernamesWithFindAll()); + $this->assertEquals(['John', 'Tim'], $this->getUsernamesWithFindAll()); $this->enableUserFilter(); $this->dm->clear(); - $this->assertEquals(array('Tim'), $this->getUsernamesWithFindAll()); + $this->assertEquals(['Tim'], $this->getUsernamesWithFindAll()); $this->fc->disable('testFilter'); $this->dm->clear(); - $this->assertEquals(array('John', 'Tim'), $this->getUsernamesWithFindAll()); + $this->assertEquals(['John', 'Tim'], $this->getUsernamesWithFindAll()); } protected function getUsernamesWithFindAll() { $all = $this->dm->getRepository('Documents\User')->findAll(); - $usernames = array(); + $usernames = []; foreach ($all as $user) { $usernames[] = $user->getUsername(); } @@ -174,26 +179,26 @@ protected function getUsernamesWithFindAll() public function testReferenceMany() { - $this->assertEquals(array('groupA', 'groupB'), $this->getGroupsByReference()); + $this->assertEquals(['groupA', 'groupB'], $this->getGroupsByReference()); $this->enableGroupFilter(); $this->dm->clear(); - $this->assertEquals(array('groupA'), $this->getGroupsByReference()); + $this->assertEquals(['groupA'], $this->getGroupsByReference()); $this->fc->disable('testFilter'); $this->dm->clear(); - $this->assertEquals(array('groupA', 'groupB'), $this->getGroupsByReference()); + $this->assertEquals(['groupA', 'groupB'], $this->getGroupsByReference()); } protected function getGroupsByReference() { $tim = $this->dm->getRepository('Documents\User')->find($this->ids['tim']); - $groupnames = array(); + $groupnames = []; foreach ($tim->getGroups() as $group) { try { $groupnames[] = $group->getName(); - } catch (\Doctrine\ODM\MongoDB\DocumentNotFoundException $e) { + } catch (DocumentNotFoundException $e) { //Proxy object filtered } } @@ -221,7 +226,7 @@ protected function getProfileByReference() $profile = $tim->getProfile(); try { return $profile->getFirstname(); - } catch (\Doctrine\ODM\MongoDB\DocumentNotFoundException $e) { + } catch (DocumentNotFoundException $e) { //Proxy object filtered return null; } @@ -229,15 +234,15 @@ protected function getProfileByReference() public function testDocumentManagerRef() { - $this->assertEquals(array('John', 'Tim'), $this->getUsernamesWithDocumentManager()); + $this->assertEquals(['John', 'Tim'], $this->getUsernamesWithDocumentManager()); $this->enableUserFilter(); $this->dm->clear(); - $this->assertEquals(array('Tim'), $this->getUsernamesWithDocumentManager()); + $this->assertEquals(['Tim'], $this->getUsernamesWithDocumentManager()); $this->fc->disable('testFilter'); $this->dm->clear(); - $this->assertEquals(array('John', 'Tim'), $this->getUsernamesWithDocumentManager()); + $this->assertEquals(['John', 'Tim'], $this->getUsernamesWithDocumentManager()); } protected function getUsernamesWithDocumentManager() @@ -245,17 +250,17 @@ protected function getUsernamesWithDocumentManager() $tim = $this->dm->getReference('Documents\User', $this->ids['tim']); $john = $this->dm->getReference('Documents\User', $this->ids['john']); - $usernames = array(); + $usernames = []; try { $usernames[] = $tim->getUsername(); - } catch (\Doctrine\ODM\MongoDB\DocumentNotFoundException $e) { + } catch (DocumentNotFoundException $e) { //Proxy object filtered } try { $usernames[] = $john->getUsername(); - } catch (\Doctrine\ODM\MongoDB\DocumentNotFoundException $e) { + } catch (DocumentNotFoundException $e) { //Proxy object filtered } @@ -265,15 +270,15 @@ protected function getUsernamesWithDocumentManager() public function testQuery() { - $this->assertEquals(array('John', 'Tim'), $this->getUsernamesWithQuery()); + $this->assertEquals(['John', 'Tim'], $this->getUsernamesWithQuery()); $this->enableUserFilter(); $this->dm->clear(); - $this->assertEquals(array('Tim'), $this->getUsernamesWithQuery()); + $this->assertEquals(['Tim'], $this->getUsernamesWithQuery()); $this->fc->disable('testFilter'); $this->dm->clear(); - $this->assertEquals(array('John', 'Tim'), $this->getUsernamesWithQuery()); + $this->assertEquals(['John', 'Tim'], $this->getUsernamesWithQuery()); } protected function getUsernamesWithQuery() @@ -282,7 +287,7 @@ protected function getUsernamesWithQuery() $query = $qb->getQuery(); $all = $query->execute(); - $usernames = array(); + $usernames = []; foreach ($all as $user) { $usernames[] = $user->getUsername(); } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/FindAndModifyTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/FindAndModifyTest.php index a8aa7388b2..cfa99daa89 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/FindAndModifyTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/FindAndModifyTest.php @@ -1,15 +1,18 @@ dm->getDocumentCollection('Documents\User'); - $docs = array(array('count' => 0), array('count' => 0)); + $docs = [['count' => 0], ['count' => 0]]; $coll->insertMany($docs); // test update findAndModify diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/FlushTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/FlushTest.php index f6be0a1e70..ff86e4dcca 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/FlushTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/FlushTest.php @@ -1,12 +1,14 @@ addFriend($userC); // persist all users, flush and clear - foreach (array($userA, $userB, $userC) as $user) $this->dm->persist($user); + foreach ([$userA, $userB, $userC] as $user) { + $this->dm->persist($user); + } $this->dm->flush(); $this->dm->clear(); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/FunctionalTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/FunctionalTest.php index 0fb20513fb..c1835ed461 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/FunctionalTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/FunctionalTest.php @@ -1,18 +1,20 @@ id = (string) $id; $user->username = 'test'; $user->count = 1; - $group = new \Documents\Group('Group'); - $user->groups = array($group); + $group = new Group('Group'); + $user->groups = [$group]; $this->dm->persist($user); $this->dm->flush(); $this->dm->clear(); - $check = $this->dm->getDocumentCollection($className)->findOne(array('_id' => $id)); + $check = $this->dm->getDocumentCollection($className)->findOne(['_id' => $id]); $this->assertNotNull($check); $this->assertEquals((string) $id, (string) $check['_id']); $this->assertEquals($group->getId(), (string) $check['groups'][0]['$id']); $this->assertEquals($discriminator, $check['discriminator']); - $group2 = new \Documents\Group('Group'); + $group2 = new Group('Group'); $user = new $className(); $user->id = $id; $user->hits = 5; $user->count = 2; - $user->groups = array($group2); + $user->groups = [$group2]; $this->dm->persist($user); $this->dm->flush(); $this->dm->clear(); - $check = $this->dm->getDocumentCollection($className)->findOne(array('_id' => $id)); + $check = $this->dm->getDocumentCollection($className)->findOne(['_id' => $id]); $this->assertEquals($discriminator, $check['discriminator']); $this->assertEquals(3, $check['count']); $this->assertEquals(5, $check['hits']); @@ -91,7 +98,7 @@ public function testUpsertObject($className, $id, $discriminator) $this->dm->persist($user); $this->dm->flush(); - $check = $this->dm->getDocumentCollection($className)->findOne(array('_id' => $id)); + $check = $this->dm->getDocumentCollection($className)->findOne(['_id' => $id]); $this->assertEquals($discriminator, $check['discriminator']); $this->assertEquals(3, $check['count']); $this->assertEquals(100, $check['hits']); @@ -110,9 +117,9 @@ public function testInheritedAssociationMappings() public function testNestedCategories() { - $root = new \Documents\Category('Root'); - $child1 = new \Documents\SubCategory('Child 1'); - $child2 = new \Documents\SubCategory('Child 2'); + $root = new Category('Root'); + $child1 = new SubCategory('Child 1'); + $child2 = new SubCategory('Child 2'); $child1->addChild($child2); $root->addChild($child1); @@ -144,7 +151,7 @@ public function testManyEmbedded() $songs->add(new Song('Song #3')); $this->dm->flush(); - $test = $this->dm->getDocumentCollection('Documents\Album')->findOne(array('name' => 'Jon')); + $test = $this->dm->getDocumentCollection('Documents\Album')->findOne(['name' => 'Jon']); $this->assertEquals('Song #1 Changed', $test['songs'][0]['name']); $album->setName('jwage'); @@ -154,7 +161,7 @@ public function testManyEmbedded() unset($songs[0]); $this->dm->flush(); - $test = $this->dm->getDocumentCollection('Documents\Album')->findOne(array('name' => 'jwage')); + $test = $this->dm->getDocumentCollection('Documents\Album')->findOne(['name' => 'jwage']); $this->assertEquals('jwage', $test['name']); $this->assertEquals('ok', $test['songs'][0]['name']); @@ -167,7 +174,7 @@ public function testManyEmbedded() $this->dm->flush(); $this->dm->clear(); - $test = $this->dm->getDocumentCollection('Documents\Album')->findOne(array('name' => 'jwage')); + $test = $this->dm->getDocumentCollection('Documents\Album')->findOne(['name' => 'jwage']); $this->assertFalse(isset($test['songs'])); } @@ -189,7 +196,7 @@ public function testNewEmbedded() $subAddress->setCity('New Sub-City'); $this->dm->flush(); - $test = $this->dm->getDocumentCollection('Documents\Project')->findOne(array('name' => 'Project')); + $test = $this->dm->getDocumentCollection('Documents\Project')->findOne(['name' => 'Project']); $this->assertEquals('New Sub-City', $test['address']['subAddress']['city']); $this->assertEquals('New City', $test['address']['city']); @@ -197,7 +204,7 @@ public function testNewEmbedded() public function testPersistingNewDocumentWithOnlyOneReference() { - $server = new \Documents\GuestServer(); + $server = new GuestServer(); $server->name = 'test'; $this->dm->persist($server); $this->dm->flush(); @@ -207,7 +214,7 @@ public function testPersistingNewDocumentWithOnlyOneReference() $server = $this->dm->getReference('Documents\GuestServer', $id); - $agent = new \Documents\Agent(); + $agent = new Agent(); $agent->server = $server; $this->dm->persist($agent); $this->dm->flush(); @@ -222,32 +229,32 @@ public function testPersistingNewDocumentWithOnlyOneReference() public function testCollection() { - $user = new \Documents\User(); + $user = new User(); $user->setUsername('joncolltest'); - $user->log(array('test')); - $user->log(array('test')); + $user->log(['test']); + $user->log(['test']); $this->dm->persist($user); $this->dm->flush(); $this->dm->clear(); $coll = $this->dm->getDocumentCollection('Documents\User'); - $document = $coll->findOne(array('username' => 'joncolltest')); + $document = $coll->findOne(['username' => 'joncolltest']); $this->assertCount(2, $document['logs']); - $document = $this->dm->getRepository('Documents\User')->findOneBy(array('username' => 'joncolltest')); + $document = $this->dm->getRepository('Documents\User')->findOneBy(['username' => 'joncolltest']); $this->assertCount(2, $document->getLogs()); - $document->log(array('test')); + $document->log(['test']); $this->dm->flush(); $this->dm->clear(); - $document = $this->dm->getRepository('Documents\User')->findOneBy(array('username' => 'joncolltest')); + $document = $this->dm->getRepository('Documents\User')->findOneBy(['username' => 'joncolltest']); $this->assertCount(3, $document->getLogs()); - $document->setLogs(array('ok', 'test')); + $document->setLogs(['ok', 'test']); $this->dm->flush(); $this->dm->clear(); - $document = $this->dm->getRepository('Documents\User')->findOneBy(array('username' => 'joncolltest')); - $this->assertEquals(array('ok', 'test'), $document->getLogs()); + $document = $this->dm->getRepository('Documents\User')->findOneBy(['username' => 'joncolltest']); + $this->assertEquals(['ok', 'test'], $document->getLogs()); } public function testSameObjectValuesInCollection() @@ -260,7 +267,7 @@ public function testSameObjectValuesInCollection() $this->dm->flush(); $this->dm->clear(); - $user = $this->dm->getRepository('Documents\User')->findOneBy(array('username' => 'testing')); + $user = $this->dm->getRepository('Documents\User')->findOneBy(['username' => 'testing']); $this->assertCount(2, $user->getPhonenumbers()); } @@ -275,14 +282,14 @@ public function testIncrement() $this->dm->flush(); $this->dm->clear(); - $user = $this->dm->getRepository('Documents\User')->findOneBy(array('username' => 'jon')); + $user = $this->dm->getRepository('Documents\User')->findOneBy(['username' => 'jon']); $user->incrementCount(5); $user->incrementFloatCount(5); $this->dm->flush(); $this->dm->clear(); - $user = $this->dm->getRepository('Documents\User')->findOneBy(array('username' => 'jon')); + $user = $this->dm->getRepository('Documents\User')->findOneBy(['username' => 'jon']); $this->assertSame(105, $user->getCount()); $this->assertSame(105.0, $user->getFloatCount()); @@ -291,7 +298,7 @@ public function testIncrement() $this->dm->flush(); $this->dm->clear(); - $user = $this->dm->getRepository('Documents\User')->findOneBy(array('username' => 'jon')); + $user = $this->dm->getRepository('Documents\User')->findOneBy(['username' => 'jon']); $this->assertSame(50, $user->getCount()); $this->assertSame(50.0, $user->getFloatCount()); } @@ -307,14 +314,14 @@ public function testIncrementWithFloat() $this->dm->flush(); $this->dm->clear(); - $user = $this->dm->getRepository('Documents\User')->findOneBy(array('username' => 'jon')); + $user = $this->dm->getRepository('Documents\User')->findOneBy(['username' => 'jon']); $user->incrementCount(1.337); $user->incrementFloatCount(1.337); $this->dm->flush(); $this->dm->clear(); - $user = $this->dm->getRepository('Documents\User')->findOneBy(array('username' => 'jon')); + $user = $this->dm->getRepository('Documents\User')->findOneBy(['username' => 'jon']); $this->assertSame(101, $user->getCount()); $this->assertSame(101.337, $user->getFloatCount()); @@ -323,7 +330,7 @@ public function testIncrementWithFloat() $this->dm->flush(); $this->dm->clear(); - $user = $this->dm->getRepository('Documents\User')->findOneBy(array('username' => 'jon')); + $user = $this->dm->getRepository('Documents\User')->findOneBy(['username' => 'jon']); $this->assertSame(110, $user->getCount()); $this->assertSame(110.5, $user->getFloatCount()); } @@ -339,7 +346,7 @@ public function testIncrementSetsNull() $this->dm->flush(); $this->dm->clear(); - $user = $this->dm->getRepository('Documents\User')->findOneBy(array('username' => 'jon')); + $user = $this->dm->getRepository('Documents\User')->findOneBy(['username' => 'jon']); $this->assertSame(10, $user->getCount()); $this->assertSame(10.0, $user->getFloatCount()); @@ -348,7 +355,7 @@ public function testIncrementSetsNull() $this->dm->flush(); $this->dm->clear(); - $user = $this->dm->getRepository('Documents\User')->findOneBy(array('username' => 'jon')); + $user = $this->dm->getRepository('Documents\User')->findOneBy(['username' => 'jon']); $this->assertSame(11, $user->getCount()); $this->assertSame(11.0, $user->getFloatCount()); @@ -357,7 +364,7 @@ public function testIncrementSetsNull() $this->dm->flush(); $this->dm->clear(); - $user = $this->dm->getRepository('Documents\User')->findOneBy(array('username' => 'jon')); + $user = $this->dm->getRepository('Documents\User')->findOneBy(['username' => 'jon']); $this->assertNull($user->getCount()); $this->assertNull($user->getFloatCount()); } @@ -475,11 +482,11 @@ public function testNotSavedFields() { $collection = $this->dm->getDocumentCollection('Documents\Functional\NotSaved'); $collection->drop(); - $test = array( + $test = [ '_id' => new ObjectId(), 'name' => 'Jonathan Wage', 'notSaved' => 'test', - ); + ]; $collection->insertOne($test); $notSaved = $this->dm->find('Documents\Functional\NotSaved', $test['_id']); $this->assertEquals('Jonathan Wage', $notSaved->name); @@ -492,7 +499,7 @@ public function testNotSavedFields() $this->dm->flush(); $this->dm->clear(); - $notSaved = $collection->findOne(array('name' => 'Roman Borschel')); + $notSaved = $collection->findOne(['name' => 'Roman Borschel']); $this->assertEquals('Roman Borschel', $notSaved['name']); $this->assertFalse(isset($notSaved['notSaved'])); } @@ -518,10 +525,10 @@ public function testTypeClassMissing() $this->dm->flush(); $this->dm->clear(); - /** @var $test FavoritesUser */ + /** @var FavoritesUser $test */ $test = $this->dm->find('Documents\Functional\FavoritesUser', $user->getId()); - /** @var $collection PersistentCollection */ + /** @var PersistentCollection $collection */ $collection = $test->getFavorites(); $collection->getTypeClass(); } @@ -536,10 +543,10 @@ public function testTypeClass() $this->dm->flush(); $this->dm->clear(); - /** @var $test Bar */ + /** @var Bar $test */ $test = $this->dm->find('Documents\Bars\Bar', $bar->getId()); - /** @var $collection PersistentCollection */ + /** @var PersistentCollection $collection */ $collection = $test->getLocations(); $this->assertInstanceOf('Doctrine\ODM\MongoDB\Mapping\ClassMetadata', $collection->getTypeClass()); } @@ -576,14 +583,14 @@ public function testFavoritesReference() $this->dm->flush(); $this->dm->clear(); - $test = $this->dm->getDocumentCollection('Documents\Functional\FavoritesUser')->findOne(array('name' => 'favorites')); + $test = $this->dm->getDocumentCollection('Documents\Functional\FavoritesUser')->findOne(['name' => 'favorites']); $this->assertTrue(isset($test['favorites'][0]['type'])); $this->assertEquals('project', $test['favorites'][0]['type']); $this->assertEquals('group', $test['favorites'][1]['type']); $this->assertTrue(isset($test['favorite']['_doctrine_class_name'])); $this->assertEquals('Documents\Project', $test['favorite']['_doctrine_class_name']); - $user = $this->dm->getRepository('Documents\Functional\FavoritesUser')->findOneBy(array('name' => 'favorites')); + $user = $this->dm->getRepository('Documents\Functional\FavoritesUser')->findOneBy(['name' => 'favorites']); $favorites = $user->getFavorites(); $this->assertInstanceOf('Documents\Project', $favorites[0]); $this->assertInstanceOf('Documents\Group', $favorites[1]); @@ -617,7 +624,7 @@ public function testPreUpdate() $this->dm->flush(); $this->dm->clear(); - $product = $this->dm->getRepository('Documents\Functional\PreUpdateTestProduct')->findOneBy(array('name' => 'Product')); + $product = $this->dm->getRepository('Documents\Functional\PreUpdateTestProduct')->findOneBy(['name' => 'Product']); $this->assertInstanceOf('Documents\Functional\PreUpdateTestSellable', $product->sellable); $this->assertInstanceOf('Documents\Functional\PreUpdateTestProduct', $product->sellable->getProduct()); @@ -631,14 +638,14 @@ public function testPreUpdate() $sellable = new PreUpdateTestSellable(); $sellable->product = $product; - $sellable->seller = $this->dm->getRepository('Documents\Functional\PreUpdateTestSeller')->findOneBy(array('name' => 'Seller')); + $sellable->seller = $this->dm->getRepository('Documents\Functional\PreUpdateTestSeller')->findOneBy(['name' => 'Seller']); $product->sellable = $sellable; $this->dm->flush(); $this->dm->clear(); - $product = $this->dm->getRepository('Documents\Functional\PreUpdateTestProduct')->findOneBy(array('name' => 'Product2')); + $product = $this->dm->getRepository('Documents\Functional\PreUpdateTestProduct')->findOneBy(['name' => 'Product2']); $this->assertEquals('Seller', $product->sellable->getSeller()->getName()); $this->assertEquals('Product2', $product->sellable->getProduct()->getName()); } @@ -659,25 +666,25 @@ public function testSameCollectionTest() $this->dm->persist($test3); $this->dm->flush(); - $test = $this->dm->getRepository('Documents\Functional\SameCollection1')->findOneBy(array('name' => 'test1')); + $test = $this->dm->getRepository('Documents\Functional\SameCollection1')->findOneBy(['name' => 'test1']); $this->assertNotNull($test); $this->assertInstanceOf('Documents\Functional\SameCollection1', $test); - $test = $this->dm->getRepository('Documents\Functional\SameCollection2')->findOneBy(array('name' => 'test2')); + $test = $this->dm->getRepository('Documents\Functional\SameCollection2')->findOneBy(['name' => 'test2']); $this->assertNotNull($test); $this->assertInstanceOf('Documents\Functional\SameCollection2', $test); - $test = $this->dm->getRepository('Documents\Functional\SameCollection1')->findOneBy(array('name' => 'test3')); + $test = $this->dm->getRepository('Documents\Functional\SameCollection1')->findOneBy(['name' => 'test3']); $this->assertNotNull($test); $this->assertInstanceOf('Documents\Functional\SameCollection1', $test); - $test = $this->dm->getRepository('Documents\Functional\SameCollection2')->findOneBy(array('name' => 'test1')); + $test = $this->dm->getRepository('Documents\Functional\SameCollection2')->findOneBy(['name' => 'test1']); $this->assertNull($test); - $qb = $this->dm->createQueryBuilder(array( + $qb = $this->dm->createQueryBuilder([ 'Documents\Functional\SameCollection1', - 'Documents\Functional\SameCollection2') - ); + 'Documents\Functional\SameCollection2', + ]); $q = $qb->getQuery(); $test = $q->execute()->toArray(); $this->assertCount(3, $test); @@ -696,10 +703,10 @@ public function testSameCollectionTest() */ public function testNotSameCollectionThrowsException() { - $test = $this->dm->createQueryBuilder(array( + $test = $this->dm->createQueryBuilder([ 'Documents\User', - 'Documents\Profile') - )->getQuery()->execute(); + 'Documents\Profile', + ])->getQuery()->execute(); } public function testEmbeddedNesting() @@ -842,7 +849,7 @@ public function testReplaceEntireGroupsArray() //$user->getGroups()->clear(); //$user->getGroups()->add($group2); - $user->setGroups(array($group2)); + $user->setGroups([$group2]); $this->assertCount(1, $user->getGroups()); @@ -896,7 +903,7 @@ class ParentAssociationTestB /** @ODM\Field(type="string") */ public $name; /** @ODM\EmbedMany */ - public $children = array(); + public $children = []; public function __construct($name) { $this->name = $name; diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/HasLifecycleCallbacksTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/HasLifecycleCallbacksTest.php index ece7dde069..cad6cc424b 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/HasLifecycleCallbacksTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/HasLifecycleCallbacksTest.php @@ -1,10 +1,13 @@ id; $this->dm->clear(); - $check1 = $this->dm->getRepository(__NAMESPACE__.'\UuidUser')->findOneBy(array('id' => $id)); + $check1 = $this->dm->getRepository(__NAMESPACE__ . '\UuidUser')->findOneBy(['id' => $id]); $this->assertNotNull($check1); - $check2 = $this->dm->createQueryBuilder(__NAMESPACE__.'\UuidUser') + $check2 = $this->dm->createQueryBuilder(__NAMESPACE__ . '\UuidUser') ->field('id')->equals($id)->getQuery()->getSingleResult(); $this->assertNotNull($check2); $this->assertSame($check1, $check2); - $check3 = $this->dm->createQueryBuilder(__NAMESPACE__.'\UuidUser') + $check3 = $this->dm->createQueryBuilder(__NAMESPACE__ . '\UuidUser') ->field('name')->equals('Jonathan H. Wage')->getQuery()->getSingleResult(); $this->assertNotNull($check3); $this->assertSame($check2, $check3); @@ -37,15 +54,15 @@ public function testAlnumIdChars() $this->dm->flush(); $this->dm->clear(); - $check1 = $this->dm->getRepository(__NAMESPACE__.'\AlnumCharsUser')->findOneBy(array('id' => 'x')); + $check1 = $this->dm->getRepository(__NAMESPACE__ . '\AlnumCharsUser')->findOneBy(['id' => 'x']); $this->assertNotNull($check1); - $check2 = $this->dm->createQueryBuilder(__NAMESPACE__.'\AlnumCharsUser') + $check2 = $this->dm->createQueryBuilder(__NAMESPACE__ . '\AlnumCharsUser') ->field('id')->equals('x')->getQuery()->getSingleResult(); $this->assertNotNull($check2); $this->assertSame($check1, $check2); - $check3 = $this->dm->createQueryBuilder(__NAMESPACE__.'\AlnumCharsUser') + $check3 = $this->dm->createQueryBuilder(__NAMESPACE__ . '\AlnumCharsUser') ->field('name')->equals('Kathrine R. Cage')->getQuery()->getSingleResult(); $this->assertNotNull($check3); $this->assertSame($check2, $check3); @@ -73,17 +90,16 @@ public function testCollectionId() $this->assertEquals($reference1->id, 1); $this->assertEquals($reference2->id, 2); - $check1 = $this->dm->getRepository(__NAMESPACE__.'\CollectionIdUser')->findOneBy(array('id' => $user1->id)); - $check2 = $this->dm->getRepository(__NAMESPACE__.'\CollectionIdUser')->findOneBy(array('id' => $user2->id)); + $check1 = $this->dm->getRepository(__NAMESPACE__ . '\CollectionIdUser')->findOneBy(['id' => $user1->id]); + $check2 = $this->dm->getRepository(__NAMESPACE__ . '\CollectionIdUser')->findOneBy(['id' => $user2->id]); $this->assertNotNull($check1); $this->assertNotNull($check2); $this->assertEquals('referenced 1', $check1->reference->getName()); $this->assertEquals('referenced 2', $check2->reference->getName()); - $check = $this->dm->getRepository(__NAMESPACE__.'\CollectionIdUser')->find($user1->id); + $check = $this->dm->getRepository(__NAMESPACE__ . '\CollectionIdUser')->find($user1->id); $this->assertNotNull($check); - } public function testCollectionIdWithStartingId() @@ -126,17 +142,17 @@ public function testEmbeddedDocumentWithId() public function testIdGeneratorInstance() { - $class = $this->dm->getClassMetadata(__NAMESPACE__.'\UuidUser'); - $this->assertEquals(\Doctrine\ODM\MongoDB\Mapping\ClassMetadata::GENERATOR_TYPE_UUID, $class->generatorType); - $this->assertEquals(array('salt' => 'test'), $class->generatorOptions); + $class = $this->dm->getClassMetadata(__NAMESPACE__ . '\UuidUser'); + $this->assertEquals(ClassMetadata::GENERATOR_TYPE_UUID, $class->generatorType); + $this->assertEquals(['salt' => 'test'], $class->generatorOptions); $this->assertInstanceOf('Doctrine\ODM\MongoDB\Id\UuidGenerator', $class->idGenerator); $this->assertEquals('test', $class->idGenerator->getSalt()); $serialized = serialize($class); $class = unserialize($serialized); - $this->assertEquals(\Doctrine\ODM\MongoDB\Mapping\ClassMetadata::GENERATOR_TYPE_UUID, $class->generatorType); - $this->assertEquals(array('salt' => 'test'), $class->generatorOptions); + $this->assertEquals(ClassMetadata::GENERATOR_TYPE_UUID, $class->generatorType); + $this->assertEquals(['salt' => 'test'], $class->generatorOptions); $this->assertInstanceOf('Doctrine\ODM\MongoDB\Id\UuidGenerator', $class->idGenerator); $this->assertEquals('test', $class->idGenerator->getSalt()); } @@ -146,11 +162,6 @@ public function testIdGeneratorInstance() */ public function testEqualButNotIdenticalIds($user1Id, $user2Id) { - /* Do not use assertEquals(), since the Scalar comparator tends to cast - * scalars of different types to strings before comparison. We actually - * want to check against PHP's loose equality logic here. - */ - $this->assertTrue($user1Id == $user2Id); $this->assertNotSame($user1Id, $user2Id); $user1 = new CustomIdUser(sprintf('User1 with %s ID', gettype($user1Id))); @@ -167,8 +178,8 @@ public function testEqualButNotIdenticalIds($user1Id, $user2Id) $this->assertSame($user1->id, $user1Id); $this->assertSame($user2->id, $user2Id); - $user1 = $this->dm->find(__NAMESPACE__.'\CustomIdUser', $user1Id); - $user2 = $this->dm->find(__NAMESPACE__.'\CustomIdUser', $user2Id); + $user1 = $this->dm->find(__NAMESPACE__ . '\CustomIdUser', $user1Id); + $user2 = $this->dm->find(__NAMESPACE__ . '\CustomIdUser', $user2Id); $this->assertNotSame($user1, $user2); $this->assertSame($user1->id, $user1Id); @@ -182,12 +193,12 @@ public function provideEqualButNotIdenticalIds() * * See: http://docs.mongodb.org/manual/faq/developers/#what-is-the-compare-order-for-bson-types */ - return array( - array('123', 123), - array('123', 123.0), - array('', 0), - array('0', 0), - ); + return [ + ['123', 123], + ['123', 123.0], + ['', 0], + ['0', 0], + ]; } /** @@ -207,7 +218,7 @@ public function testIdTypesAndStrategies($type, $strategy, $id = null, $expected $this->assertNotNull($object->id); if ($expectedMongoType !== null) { - $check = $this->dm->getDocumentCollection(get_class($object))->findOne(array()); + $check = $this->dm->getDocumentCollection(get_class($object))->findOne([]); $this->assertEquals($expectedMongoType, is_object($check['_id']) ? get_class($check['_id']) : gettype($check['_id'])); } @@ -232,59 +243,59 @@ public function testIdTypesAndStrategies($type, $strategy, $id = null, $expected public function getTestIdTypesAndStrategiesData() { - $identifier = new \MongoDB\BSON\ObjectId(); + $identifier = new ObjectId(); - return array( + return [ // boolean - array('boolean', 'none', true, true, 'boolean'), - array('boolean', 'none', 1, true, 'boolean'), - array('boolean', 'none', false, false, 'boolean'), + ['boolean', 'none', true, true, 'boolean'], + ['boolean', 'none', 1, true, 'boolean'], + ['boolean', 'none', false, false, 'boolean'], // integer - array('int', 'none', 0, 0, 'integer'), - array('int', 'none', 1, 1, 'integer'), - array('int', 'none', '1', 1, 'integer'), - array('int', 'increment', null, 1, 'integer'), + ['int', 'none', 0, 0, 'integer'], + ['int', 'none', 1, 1, 'integer'], + ['int', 'none', '1', 1, 'integer'], + ['int', 'increment', null, 1, 'integer'], // raw - array('raw', 'none', 0, 0, 'integer'), - array('raw', 'none', '1', '1', 'string'), - array('raw', 'none', true, true, 'boolean'), - array('raw', 'increment', null, 1, 'integer'), + ['raw', 'none', 0, 0, 'integer'], + ['raw', 'none', '1', '1', 'string'], + ['raw', 'none', true, true, 'boolean'], + ['raw', 'increment', null, 1, 'integer'], // float - array('float', 'none', 1.1, 1.1, 'double'), - array('float', 'none', '1.1', 1.1, 'double'), + ['float', 'none', 1.1, 1.1, 'double'], + ['float', 'none', '1.1', 1.1, 'double'], // string - array('string', 'none', '', '', 'string'), - array('string', 'none', 1, '1', 'string'), - array('string', 'none', 'test', 'test', 'string'), - array('string', 'increment', null, '1', 'string'), + ['string', 'none', '', '', 'string'], + ['string', 'none', 1, '1', 'string'], + ['string', 'none', 'test', 'test', 'string'], + ['string', 'increment', null, '1', 'string'], // custom_id - array('custom_id', 'none', 0, 0, 'integer'), - array('custom_id', 'none', '1', '1', 'string'), - array('custom_id', 'increment', null, 1, 'integer'), + ['custom_id', 'none', 0, 0, 'integer'], + ['custom_id', 'none', '1', '1', 'string'], + ['custom_id', 'increment', null, 1, 'integer'], // object_id - array('object_id', 'none', (string) $identifier, (string) $identifier, \MongoDB\BSON\ObjectId::class), + ['object_id', 'none', (string) $identifier, (string) $identifier, ObjectId::class], // date - array('date', 'none', new \DateTime(date('Y-m-d')), new \DateTime(date('Y-m-d')), \MongoDB\BSON\UTCDateTime::class), + ['date', 'none', new \DateTime(date('Y-m-d')), new \DateTime(date('Y-m-d')), UTCDateTime::class], // bin - array('bin', 'none', 'test-data', 'test-data', \MongoDB\BSON\Binary::class), - array('bin', 'uuid', null, null, \MongoDB\BSON\Binary::class), - array('bin_func', 'none', 'test-data', 'test-data', \MongoDB\BSON\Binary::class), - array('bin_bytearray', 'none', 'test-data', 'test-data', \MongoDB\BSON\Binary::class), - array('bin_uuid', 'none', 'TestTestTestTest', 'TestTestTestTest', \MongoDB\BSON\Binary::class), - array('bin_md5', 'none', md5('test'), md5('test'), \MongoDB\BSON\Binary::class), - array('bin_custom', 'none', 'test-data', 'test-data', \MongoDB\BSON\Binary::class), + ['bin', 'none', 'test-data', 'test-data', Binary::class], + ['bin', 'uuid', null, null, Binary::class], + ['bin_func', 'none', 'test-data', 'test-data', Binary::class], + ['bin_bytearray', 'none', 'test-data', 'test-data', Binary::class], + ['bin_uuid', 'none', 'TestTestTestTest', 'TestTestTestTest', Binary::class], + ['bin_md5', 'none', md5('test'), md5('test'), Binary::class], + ['bin_custom', 'none', 'test-data', 'test-data', Binary::class], // hash - array('hash', 'none', array('key' => 'value'), array('key' => 'value'), 'array'), - ); + ['hash', 'none', ['key' => 'value'], ['key' => 'value'], 'array'], + ]; } /** @@ -301,22 +312,22 @@ public function testBinIds($type, $expectedMongoBinDataType, $id) $this->dm->flush(); $this->dm->clear(); - $check = $this->dm->getDocumentCollection(get_class($object))->findOne(array()); + $check = $this->dm->getDocumentCollection(get_class($object))->findOne([]); - $this->assertEquals(\MongoDB\BSON\Binary::class, get_class($check['_id'])); + $this->assertEquals(Binary::class, get_class($check['_id'])); $this->assertEquals($expectedMongoBinDataType, $check['_id']->getType()); } public function getTestBinIdsData() { - return array( - array('bin', 0, 'test-data'), - array('bin_func', \MongoDB\BSON\Binary::TYPE_FUNCTION, 'test-data'), - array('bin_bytearray', \MongoDB\BSON\Binary::TYPE_OLD_BINARY, 'test-data'), - array('bin_uuid', \MongoDB\BSON\Binary::TYPE_OLD_UUID, 'testtesttesttest'), - array('bin_md5', \MongoDB\BSON\Binary::TYPE_MD5, md5('test')), - array('bin_custom', \MongoDB\BSON\Binary::TYPE_USER_DEFINED, 'test-data'), - ); + return [ + ['bin', 0, 'test-data'], + ['bin_func', Binary::TYPE_FUNCTION, 'test-data'], + ['bin_bytearray', Binary::TYPE_OLD_BINARY, 'test-data'], + ['bin_uuid', Binary::TYPE_OLD_UUID, 'testtesttesttest'], + ['bin_md5', Binary::TYPE_MD5, md5('test')], + ['bin_custom', Binary::TYPE_USER_DEFINED, 'test-data'], + ]; } /** @@ -343,11 +354,11 @@ public function testStrategyAutoWithNotValidIdThrowsException() private function createIdTestClass($type, $strategy) { $shortClassName = sprintf('TestIdTypes%s%sUser', ucfirst($type), ucfirst($strategy)); - $className = sprintf(__NAMESPACE__.'\\%s', $shortClassName); + $className = sprintf(__NAMESPACE__ . '\\%s', $shortClassName); - if (!class_exists($className)) { + if (! class_exists($className)) { $code = sprintf( -'namespace Doctrine\ODM\MongoDB\Tests\Functional; + 'namespace Doctrine\ODM\MongoDB\Tests\Functional; use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; @@ -359,7 +370,11 @@ class %s /** @Doctrine\ODM\MongoDB\Mapping\Annotations\Field("type=string") **/ public $test = "test"; -}', $shortClassName, $strategy, $type); +}', + $shortClassName, + $strategy, + $type + ); eval($code); } @@ -396,7 +411,7 @@ class CollectionIdUser public $reference; /** @ODM\EmbedMany(targetDocument="EmbeddedCollectionId") */ - public $embedded = array(); + public $embedded = []; public function __construct($name) { @@ -417,7 +432,7 @@ class CollectionIdUserWithStartingId public $reference; /** @ODM\EmbedMany(targetDocument="EmbeddedCollectionId") */ - public $embedded = array(); + public $embedded = []; public function __construct($name) { diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/IdentifiersTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/IdentifiersTest.php index a9ff7ce11d..ed35491b6f 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/IdentifiersTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/IdentifiersTest.php @@ -1,14 +1,21 @@ setUsername('jwage'); - $event = new \Documents\Event(); + $event = new Event(); $event->setTitle('test event title'); $event->setUser($user); $this->dm->persist($user); @@ -36,7 +43,7 @@ public function testGetIdentifierValue() public function testIdentifiersAreSet() { - $user = new \Documents\User(); + $user = new User(); $user->setUsername('jwage'); $user->setPassword('test'); @@ -48,7 +55,7 @@ public function testIdentifiersAreSet() public function testIdentityMap() { - $user = new \Documents\User(); + $user = new User(); $user->setUsername('jwage'); $this->dm->persist($user); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/IndexesTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/IndexesTest.php index e4921f14cc..91f886b145 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/IndexesTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/IndexesTest.php @@ -1,14 +1,17 @@ dm->getSchemaManager()->ensureDocumentIndexes($class); $test = new $class(); @@ -33,7 +36,7 @@ private function uniqueTest($class) public function testEmbeddedIndexes() { - $class = $this->dm->getClassMetadata(__NAMESPACE__.'\DocumentWithEmbeddedIndexes'); + $class = $this->dm->getClassMetadata(__NAMESPACE__ . '\DocumentWithEmbeddedIndexes'); $sm = $this->dm->getSchemaManager(); $indexes = $sm->getDocumentIndexes($class->name); @@ -52,7 +55,7 @@ public function testEmbeddedIndexes() public function testDiscriminatedEmbeddedIndexes() { - $class = $this->dm->getClassMetadata(__NAMESPACE__.'\DocumentWithIndexInDiscriminatedEmbeds'); + $class = $this->dm->getClassMetadata(__NAMESPACE__ . '\DocumentWithIndexInDiscriminatedEmbeds'); $sm = $this->dm->getSchemaManager(); $indexes = $sm->getDocumentIndexes($class->name); @@ -68,7 +71,7 @@ public function testDiscriminatedEmbeddedIndexes() public function testDiscriminatorIndexes() { - $class = $this->dm->getClassMetadata(__NAMESPACE__.'\DocumentWithDiscriminatorIndex'); + $class = $this->dm->getClassMetadata(__NAMESPACE__ . '\DocumentWithDiscriminatorIndex'); $sm = $this->dm->getSchemaManager(); $indexes = $sm->getDocumentIndexes($class->name); @@ -78,35 +81,35 @@ public function testDiscriminatorIndexes() public function testIndexDefinitions() { - $class = $this->dm->getClassMetadata(__NAMESPACE__.'\UniqueOnFieldTest'); + $class = $this->dm->getClassMetadata(__NAMESPACE__ . '\UniqueOnFieldTest'); $indexes = $class->getIndexes(); $this->assertTrue(isset($indexes[0]['keys']['username'])); $this->assertEquals(1, $indexes[0]['keys']['username']); $this->assertTrue(isset($indexes[0]['options']['unique'])); $this->assertEquals(true, $indexes[0]['options']['unique']); - $class = $this->dm->getClassMetadata(__NAMESPACE__.'\UniqueOnDocumentTest'); + $class = $this->dm->getClassMetadata(__NAMESPACE__ . '\UniqueOnDocumentTest'); $indexes = $class->getIndexes(); $this->assertTrue(isset($indexes[0]['keys']['username'])); $this->assertEquals(1, $indexes[0]['keys']['username']); $this->assertTrue(isset($indexes[0]['options']['unique'])); $this->assertEquals(true, $indexes[0]['options']['unique']); - $class = $this->dm->getClassMetadata(__NAMESPACE__.'\IndexesOnDocumentTest'); + $class = $this->dm->getClassMetadata(__NAMESPACE__ . '\IndexesOnDocumentTest'); $indexes = $class->getIndexes(); $this->assertTrue(isset($indexes[0]['keys']['username'])); $this->assertEquals(1, $indexes[0]['keys']['username']); $this->assertTrue(isset($indexes[0]['options']['unique'])); $this->assertEquals(true, $indexes[0]['options']['unique']); - $class = $this->dm->getClassMetadata(__NAMESPACE__.'\PartialIndexOnDocumentTest'); + $class = $this->dm->getClassMetadata(__NAMESPACE__ . '\PartialIndexOnDocumentTest'); $indexes = $class->getIndexes(); $this->assertTrue(isset($indexes[0]['keys']['username'])); $this->assertEquals(1, $indexes[0]['keys']['username']); $this->assertTrue(isset($indexes[0]['options']['partialFilterExpression'])); - $this->assertSame(array('counter' => array('$gt' => 5)), $indexes[0]['options']['partialFilterExpression']); + $this->assertSame(['counter' => ['$gt' => 5]], $indexes[0]['options']['partialFilterExpression']); - $class = $this->dm->getClassMetadata(__NAMESPACE__.'\UniqueSparseOnFieldTest'); + $class = $this->dm->getClassMetadata(__NAMESPACE__ . '\UniqueSparseOnFieldTest'); $indexes = $class->getIndexes(); $this->assertTrue(isset($indexes[0]['keys']['username'])); $this->assertEquals(1, $indexes[0]['keys']['username']); @@ -115,7 +118,7 @@ public function testIndexDefinitions() $this->assertTrue(isset($indexes[0]['options']['sparse'])); $this->assertEquals(true, $indexes[0]['options']['sparse']); - $class = $this->dm->getClassMetadata(__NAMESPACE__.'\UniqueSparseOnDocumentTest'); + $class = $this->dm->getClassMetadata(__NAMESPACE__ . '\UniqueSparseOnDocumentTest'); $indexes = $class->getIndexes(); $this->assertTrue(isset($indexes[0]['keys']['username'])); $this->assertEquals(1, $indexes[0]['keys']['username']); @@ -124,7 +127,7 @@ public function testIndexDefinitions() $this->assertTrue(isset($indexes[0]['options']['sparse'])); $this->assertEquals(true, $indexes[0]['options']['sparse']); - $class = $this->dm->getClassMetadata(__NAMESPACE__.'\SparseIndexesOnDocumentTest'); + $class = $this->dm->getClassMetadata(__NAMESPACE__ . '\SparseIndexesOnDocumentTest'); $indexes = $class->getIndexes(); $this->assertTrue(isset($indexes[0]['keys']['username'])); $this->assertEquals(1, $indexes[0]['keys']['username']); @@ -133,7 +136,7 @@ public function testIndexDefinitions() $this->assertTrue(isset($indexes[0]['options']['sparse'])); $this->assertEquals(true, $indexes[0]['options']['sparse']); - $class = $this->dm->getClassMetadata(__NAMESPACE__.'\MultipleFieldsUniqueIndexTest'); + $class = $this->dm->getClassMetadata(__NAMESPACE__ . '\MultipleFieldsUniqueIndexTest'); $indexes = $class->getIndexes(); $this->assertTrue(isset($indexes[0]['keys']['username'])); $this->assertEquals(1, $indexes[0]['keys']['username']); @@ -142,7 +145,7 @@ public function testIndexDefinitions() $this->assertTrue(isset($indexes[0]['options']['unique'])); $this->assertEquals(true, $indexes[0]['options']['unique']); - $class = $this->dm->getClassMetadata(__NAMESPACE__.'\MultipleFieldsUniqueSparseIndexTest'); + $class = $this->dm->getClassMetadata(__NAMESPACE__ . '\MultipleFieldsUniqueSparseIndexTest'); $indexes = $class->getIndexes(); $this->assertTrue(isset($indexes[0]['keys']['username'])); $this->assertEquals(1, $indexes[0]['keys']['username']); @@ -153,7 +156,7 @@ public function testIndexDefinitions() $this->assertTrue(isset($indexes[0]['options']['sparse'])); $this->assertEquals(true, $indexes[0]['options']['sparse']); - $class = $this->dm->getClassMetadata(__NAMESPACE__.'\MultipleFieldIndexes'); + $class = $this->dm->getClassMetadata(__NAMESPACE__ . '\MultipleFieldIndexes'); $indexes = $class->getIndexes(); $this->assertTrue(isset($indexes[0]['keys']['username'])); $this->assertEquals(1, $indexes[0]['keys']['username']); @@ -221,7 +224,7 @@ public function testPartialIndexCreation() $indexes = $this->dm->getSchemaManager()->getDocumentIndexes($className); $this->assertNotEmpty($indexes[0]['options']['partialFilterExpression']); - $this->assertSame(array('counter' => array('$gt' => 5)), $indexes[0]['options']['partialFilterExpression']); + $this->assertSame(['counter' => ['$gt' => 5]], $indexes[0]['options']['partialFilterExpression']); $this->assertTrue($indexes[0]['options']['unique']); } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/InheritanceTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/InheritanceTest.php index c5cf9d2f53..9f27b64916 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/InheritanceTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/InheritanceTest.php @@ -1,15 +1,26 @@ setFirstName('Jon'); - $user = new \Documents\SpecialUser(); + $user = new SpecialUser(); $user->setUsername('specialuser'); $user->setProfile($profile); @@ -33,36 +44,36 @@ public function testCollectionPerClassInheritance() $query = $qb->getQuery(); $user = $query->getSingleResult(); $this->assertEquals('Wage', $user->getProfile()->getLastName()); - $this->assertInstanceOf(\Documents\SpecialUser::class, $user); + $this->assertInstanceOf(SpecialUser::class, $user); } public function testSingleCollectionInhertiance() { - $subProject = new \Documents\SubProject('Sub Project'); + $subProject = new SubProject('Sub Project'); $this->dm->persist($subProject); $this->dm->flush(); $coll = $this->dm->getDocumentCollection('Documents\SubProject'); - $document = $coll->findOne(array('name' => 'Sub Project')); + $document = $coll->findOne(['name' => 'Sub Project']); $this->assertEquals('sub-project', $document['type']); - $project = new \Documents\OtherSubProject('Other Sub Project'); + $project = new OtherSubProject('Other Sub Project'); $this->dm->persist($project); $this->dm->flush(); $coll = $this->dm->getDocumentCollection('Documents\OtherSubProject'); - $document = $coll->findOne(array('name' => 'Other Sub Project')); + $document = $coll->findOne(['name' => 'Other Sub Project']); $this->assertEquals('other-sub-project', $document['type']); $this->dm->clear(); - $document = $this->dm->getRepository('Documents\SubProject')->findOneBy(array('name' => 'Sub Project')); + $document = $this->dm->getRepository('Documents\SubProject')->findOneBy(['name' => 'Sub Project']); $this->assertInstanceOf('Documents\SubProject', $document); - $document = $this->dm->getRepository('Documents\SubProject')->findOneBy(array('name' => 'Sub Project')); + $document = $this->dm->getRepository('Documents\SubProject')->findOneBy(['name' => 'Sub Project']); $this->assertInstanceOf('Documents\SubProject', $document); - $document = $this->dm->getRepository('Documents\Project')->findOneBy(array('name' => 'Sub Project')); + $document = $this->dm->getRepository('Documents\Project')->findOneBy(['name' => 'Sub Project']); $this->assertInstanceOf('Documents\SubProject', $document); $this->dm->clear(); @@ -70,13 +81,13 @@ public function testSingleCollectionInhertiance() $document = $this->dm->find('Documents\Project', $id); $this->assertInstanceOf('Documents\SubProject', $document); - $document = $this->dm->getRepository('Documents\Project')->findOneBy(array('name' => 'Other Sub Project')); + $document = $this->dm->getRepository('Documents\Project')->findOneBy(['name' => 'Other Sub Project']); $this->assertInstanceOf('Documents\OtherSubProject', $document); } public function testPrePersistIsCalledFromMappedSuperClass() { - $user = new \Documents\User(); + $user = new User(); $user->setUsername('test'); $this->dm->persist($user); $this->dm->flush(); @@ -85,13 +96,13 @@ public function testPrePersistIsCalledFromMappedSuperClass() public function testInheritanceProxy() { - $developer = new \Documents\Developer('avalanche123'); + $developer = new Developer('avalanche123'); $projects = $developer->getProjects(); - $projects->add(new \Documents\Project('Main Project')); - $projects->add(new \Documents\SubProject('Sub Project')); - $projects->add(new \Documents\OtherSubProject('Another Sub Project')); + $projects->add(new Project('Main Project')); + $projects->add(new SubProject('Sub Project')); + $projects->add(new OtherSubProject('Another Sub Project')); $this->dm->persist($developer); $this->dm->flush(); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Iterator/CachingIteratorTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Iterator/CachingIteratorTest.php index ec3569cfba..5cbdb9d4fc 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Iterator/CachingIteratorTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Iterator/CachingIteratorTest.php @@ -1,9 +1,12 @@ -getTraversableThatThrows([1, 2, new \Exception]); + $traversable = $this->getTraversableThatThrows([1, 2, new \Exception()]); $iterator = new CachingIterator($traversable); $expectedKey = 0; diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Iterator/HydratingIteratorTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Iterator/HydratingIteratorTest.php index 34f1a2556d..ab6b6a795a 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Iterator/HydratingIteratorTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Iterator/HydratingIteratorTest.php @@ -1,4 +1,6 @@ - new ObjectId(), 'username' => 'foo', 'hits' => 1], ['_id' => new ObjectId(), 'username' => 'bar', 'hits' => 2], diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Iterator/PrimingIteratorTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Iterator/PrimingIteratorTest.php index 82a5055a39..4cdf51c8d0 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Iterator/PrimingIteratorTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Iterator/PrimingIteratorTest.php @@ -1,4 +1,6 @@ - new ObjectId(), 'username' => 'foo', 'hits' => 1], ['_id' => new ObjectId(), 'username' => 'bar', 'hits' => 2], diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/LifecycleTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/LifecycleTest.php index ca50638806..b2a9b94311 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/LifecycleTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/LifecycleTest.php @@ -1,9 +1,11 @@ dm->clear(); - $parent = $this->dm->getRepository(__NAMESPACE__.'\ParentObject')->find($parent->getId()); + $parent = $this->dm->getRepository(__NAMESPACE__ . '\ParentObject')->find($parent->getId()); $this->assertNotNull($parent); $this->assertEquals('parent #changed', $parent->getName()); $this->assertCount(1, $parent->getChildren()); @@ -43,7 +45,7 @@ public function testEventEmptyFlush() $this->dm->flush(); $this->dm->clear(); - $parent = $this->dm->getRepository(__NAMESPACE__.'\ParentObject')->find($parent->getId()); + $parent = $this->dm->getRepository(__NAMESPACE__ . '\ParentObject')->find($parent->getId()); $this->assertNotNull($parent); $this->assertCount(1, $parent->getChildren()); } @@ -86,7 +88,7 @@ public function getName() /** @ODM\PrePersist @ODM\PreUpdate */ public function prePersistPreUpdate() { - $this->children = array($this->child); + $this->children = [$this->child]; } /** @ODM\PreUpdate */ diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/LockTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/LockTest.php index f215355244..c6112cdadf 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/LockTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/LockTest.php @@ -1,13 +1,23 @@ id = $id; @@ -49,12 +59,12 @@ public function testOptimisticLockingIntThrowsException() $this->dm->flush(); // Manually change the version so the next code will cause an exception - $this->dm->getDocumentCollection(get_class($article))->updateOne(array('_id' => new \MongoDB\BSON\ObjectId($article->id)), array('$set' => array('version' => 5))); + $this->dm->getDocumentCollection(get_class($article))->updateOne(['_id' => new ObjectId($article->id)], ['$set' => ['version' => 5]]); // Now lets change a property and try and save it again $article->title = 'ok'; - $this->expectException(\Doctrine\ODM\MongoDB\LockException::class); + $this->expectException(LockException::class); $this->dm->flush(); } @@ -78,7 +88,7 @@ public function testLockTimestampSetsDefaultValue() $test = new LockTimestamp(); $test->title = 'Testing'; - $this->assertNull($test->version, "Pre-Condition"); + $this->assertNull($test->version, 'Pre-Condition'); $this->dm->persist($test); $this->dm->flush(); @@ -97,13 +107,13 @@ public function testLockTimestampSetsDefaultValue() public function testLockTimestampSetsDefaultValueOnUpsert() { - $id = new \MongoDB\BSON\ObjectId(); + $id = new ObjectId(); $test = new LockTimestamp(); $test->title = 'Testing'; $test->id = $id; - $this->assertNull($test->version, "Pre-Condition"); + $this->assertNull($test->version, 'Pre-Condition'); $this->dm->persist($test); $this->dm->flush(); @@ -128,12 +138,12 @@ public function testLockTimestampThrowsException() $this->dm->flush(); // Manually change the version so the next code will cause an exception - $this->dm->getDocumentCollection(get_class($article))->updateOne(array('_id' => new \MongoDB\BSON\ObjectId($article->id)), array('$set' => array('version' => new \MongoDB\BSON\UTCDateTime(time() * 1000 + 600)))); + $this->dm->getDocumentCollection(get_class($article))->updateOne(['_id' => new ObjectId($article->id)], ['$set' => ['version' => new UTCDateTime(time() * 1000 + 600)]]); // Now lets change a property and try and save it again $article->title = 'ok'; - $this->expectException(\Doctrine\ODM\MongoDB\LockException::class); + $this->expectException(LockException::class); $this->dm->flush(); } @@ -144,7 +154,7 @@ public function testLockTimestampThrowsException() public function testLockVersionedDocument() { $article = new LockInt(); - $article->title = "my article"; + $article->title = 'my article'; $this->dm->persist($article); $this->dm->flush(); @@ -155,25 +165,25 @@ public function testLockVersionedDocument() public function testLockVersionedDocumentMissmatchThrowsException() { $article = new LockInt(); - $article->title = "my article"; + $article->title = 'my article'; $this->dm->persist($article); $this->dm->flush(); - $this->expectException(\Doctrine\ODM\MongoDB\LockException::class); + $this->expectException(LockException::class); $this->dm->lock($article, LockMode::OPTIMISTIC, $article->version + 1); } public function testLockUnversionedDocumentThrowsException() { - $user = new \Documents\User(); + $user = new User(); $user->setUsername('test'); $this->dm->persist($user); $this->dm->flush(); - $this->expectException(\Doctrine\ODM\MongoDB\LockException::class); + $this->expectException(LockException::class); $this->expectExceptionMessage('Document Documents\User is not versioned.'); $this->dm->lock($user, LockMode::OPTIMISTIC); @@ -192,7 +202,7 @@ public function testLockUnmanagedDocumentThrowsException() public function testLockPessimisticWrite() { $article = new LockInt(); - $article->title = "my article"; + $article->title = 'my article'; $this->dm->persist($article); $this->dm->flush(); @@ -206,7 +216,7 @@ public function testLockPessimisticWrite() public function testLockPessimisticRead() { $article = new LockInt(); - $article->title = "my article"; + $article->title = 'my article'; $this->dm->persist($article); $this->dm->flush(); @@ -220,7 +230,7 @@ public function testLockPessimisticRead() public function testUnlock() { $article = new LockInt(); - $article->title = "my article"; + $article->title = 'my article'; $this->dm->persist($article); $this->dm->flush(); @@ -241,15 +251,15 @@ public function testUnlock() public function testPessimisticReadLockThrowsExceptionOnRemove() { $article = new LockInt(); - $article->title = "my article"; + $article->title = 'my article'; $this->dm->persist($article); $this->dm->flush(); - $coll = $this->dm->getDocumentCollection(__NAMESPACE__.'\LockInt'); - $coll->replaceOne(array('_id' => new \MongoDB\BSON\ObjectId($article->id)), array('locked' => LockMode::PESSIMISTIC_READ)); + $coll = $this->dm->getDocumentCollection(__NAMESPACE__ . '\LockInt'); + $coll->replaceOne(['_id' => new ObjectId($article->id)], ['locked' => LockMode::PESSIMISTIC_READ]); - $this->expectException(\Doctrine\ODM\MongoDB\LockException::class); + $this->expectException(LockException::class); $this->dm->remove($article); $this->dm->flush(); @@ -258,15 +268,15 @@ public function testPessimisticReadLockThrowsExceptionOnRemove() public function testPessimisticReadLockThrowsExceptionOnUpdate() { $article = new LockInt(); - $article->title = "my article"; + $article->title = 'my article'; $this->dm->persist($article); $this->dm->flush(); - $coll = $this->dm->getDocumentCollection(__NAMESPACE__.'\LockInt'); - $coll->replaceOne(array('_id' => new \MongoDB\BSON\ObjectId($article->id)), array('locked' => LockMode::PESSIMISTIC_READ)); + $coll = $this->dm->getDocumentCollection(__NAMESPACE__ . '\LockInt'); + $coll->replaceOne(['_id' => new ObjectId($article->id)], ['locked' => LockMode::PESSIMISTIC_READ]); - $this->expectException(\Doctrine\ODM\MongoDB\LockException::class); + $this->expectException(LockException::class); $article->title = 'changed'; $this->dm->flush(); @@ -275,15 +285,15 @@ public function testPessimisticReadLockThrowsExceptionOnUpdate() public function testPessimisticWriteLockThrowExceptionOnRemove() { $article = new LockInt(); - $article->title = "my article"; + $article->title = 'my article'; $this->dm->persist($article); $this->dm->flush(); - $coll = $this->dm->getDocumentCollection(__NAMESPACE__.'\LockInt'); - $coll->replaceOne(array('_id' => new \MongoDB\BSON\ObjectId($article->id)), array('locked' => LockMode::PESSIMISTIC_WRITE)); + $coll = $this->dm->getDocumentCollection(__NAMESPACE__ . '\LockInt'); + $coll->replaceOne(['_id' => new ObjectId($article->id)], ['locked' => LockMode::PESSIMISTIC_WRITE]); - $this->expectException(\Doctrine\ODM\MongoDB\LockException::class); + $this->expectException(LockException::class); $this->dm->remove($article); $this->dm->flush(); @@ -292,15 +302,15 @@ public function testPessimisticWriteLockThrowExceptionOnRemove() public function testPessimisticWriteLockThrowExceptionOnUpdate() { $article = new LockInt(); - $article->title = "my article"; + $article->title = 'my article'; $this->dm->persist($article); $this->dm->flush(); - $coll = $this->dm->getDocumentCollection(__NAMESPACE__.'\LockInt'); - $coll->replaceOne(array('_id' => new \MongoDB\BSON\ObjectId($article->id)), array('locked' => LockMode::PESSIMISTIC_WRITE)); + $coll = $this->dm->getDocumentCollection(__NAMESPACE__ . '\LockInt'); + $coll->replaceOne(['_id' => new ObjectId($article->id)], ['locked' => LockMode::PESSIMISTIC_WRITE]); - $this->expectException(\Doctrine\ODM\MongoDB\LockException::class); + $this->expectException(LockException::class); $article->title = 'changed'; $this->dm->flush(); @@ -309,24 +319,24 @@ public function testPessimisticWriteLockThrowExceptionOnUpdate() public function testPessimisticWriteLockThrowExceptionOnRead() { $article = new LockInt(); - $article->title = "my article"; + $article->title = 'my article'; $this->dm->persist($article); $this->dm->flush(); - $coll = $this->dm->getDocumentCollection(__NAMESPACE__.'\LockInt'); - $coll->replaceOne(array('_id' => new \MongoDB\BSON\ObjectId($article->id)), array('locked' => LockMode::PESSIMISTIC_WRITE)); + $coll = $this->dm->getDocumentCollection(__NAMESPACE__ . '\LockInt'); + $coll->replaceOne(['_id' => new ObjectId($article->id)], ['locked' => LockMode::PESSIMISTIC_WRITE]); - $this->expectException(\Doctrine\ODM\MongoDB\LockException::class); + $this->expectException(LockException::class); $this->dm->clear(); - $article = $this->dm->find(__NAMESPACE__.'\LockInt', $article->id); + $article = $this->dm->find(__NAMESPACE__ . '\LockInt', $article->id); } public function testPessimisticReadLockFunctional() { $article = new LockInt(); - $article->title = "my article"; + $article->title = 'my article'; $this->dm->persist($article); $this->dm->flush(); @@ -336,7 +346,7 @@ public function testPessimisticReadLockFunctional() $article->title = 'test'; $this->dm->flush(); - $check = $this->dm->getDocumentCollection(__NAMESPACE__.'\LockInt')->findOne(); + $check = $this->dm->getDocumentCollection(__NAMESPACE__ . '\LockInt')->findOne(); $this->assertEquals(2, $check['version']); $this->assertArrayNotHasKey('locked', $check); $this->assertEquals('test', $check['title']); @@ -345,7 +355,7 @@ public function testPessimisticReadLockFunctional() public function testPessimisticWriteLockFunctional() { $article = new LockInt(); - $article->title = "my article"; + $article->title = 'my article'; $this->dm->persist($article); $this->dm->flush(); @@ -355,7 +365,7 @@ public function testPessimisticWriteLockFunctional() $article->title = 'test'; $this->dm->flush(); - $check = $this->dm->getDocumentCollection(__NAMESPACE__.'\LockInt')->findOne(); + $check = $this->dm->getDocumentCollection(__NAMESPACE__ . '\LockInt')->findOne(); $this->assertEquals(2, $check['version']); $this->assertArrayNotHasKey('locked', $check); $this->assertEquals('test', $check['title']); @@ -363,16 +373,16 @@ public function testPessimisticWriteLockFunctional() public function testInvalidLockDocument() { - $this->expectException(\Doctrine\ODM\MongoDB\MongoDBException::class); + $this->expectException(MongoDBException::class); $this->expectExceptionMessage('Invalid lock field type string. Lock field must be int.'); - $this->dm->getClassMetadata(__NAMESPACE__.'\InvalidLockDocument'); + $this->dm->getClassMetadata(__NAMESPACE__ . '\InvalidLockDocument'); } public function testInvalidVersionDocument() { - $this->expectException(\Doctrine\ODM\MongoDB\MongoDBException::class); + $this->expectException(MongoDBException::class); $this->expectExceptionMessage('Invalid version field type string. Version field must be int or date.'); - $this->dm->getClassMetadata(__NAMESPACE__.'\InvalidVersionDocument'); + $this->dm->getClassMetadata(__NAMESPACE__ . '\InvalidVersionDocument'); } /** @@ -386,13 +396,13 @@ public function testUpdatingCollectionRespectsVersionNumber() $this->dm->flush(); // simulate another request updating document in the meantime - $this->dm->getDocumentCollection(__NAMESPACE__.'\LockInt')->updateOne( - array('_id' => new \MongoDB\BSON\ObjectId($d->id)), - array('$set' => array('version' => 2)) + $this->dm->getDocumentCollection(__NAMESPACE__ . '\LockInt')->updateOne( + ['_id' => new ObjectId($d->id)], + ['$set' => ['version' => 2]] ); $d->issues->add(new Issue('oops', 'version mismatch')); - $this->uow->getCollectionPersister()->update($d->issues, array()); + $this->uow->getCollectionPersister()->update($d->issues, []); } /** @@ -406,12 +416,12 @@ public function testDeletingCollectionRespectsVersionNumber() $this->dm->flush(); // simulate another request updating document in the meantime - $this->dm->getDocumentCollection(__NAMESPACE__.'\LockInt')->updateOne( - array('_id' => new \MongoDB\BSON\ObjectId($d->id)), - array('$set' => array('version' => 2)) + $this->dm->getDocumentCollection(__NAMESPACE__ . '\LockInt')->updateOne( + ['_id' => new ObjectId($d->id)], + ['$set' => ['version' => 2]] ); - $this->uow->getCollectionPersister()->delete($d->issues, array()); + $this->uow->getCollectionPersister()->delete($d->issues, []); } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/MappedSuperclassTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/MappedSuperclassTest.php index bb3a308a10..29f2e98b5a 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/MappedSuperclassTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/MappedSuperclassTest.php @@ -1,19 +1,22 @@ setId(1); $e->setName('Roman'); $e->setMapped1(42); $e->setMapped2('bar'); - + $related = new MappedSuperclassRelated1(); $related->setId(1); $related->setName('Related'); @@ -29,7 +32,7 @@ public function testCRUD() $this->assertEquals(1, $e2->getId()); $this->assertEquals('Roman', $e2->getName()); $this->assertNotNull($e2->getMappedRelated1()); - $this->assertInstanceOf(__NAMESPACE__.'\MappedSuperclassRelated1', $e2->getMappedRelated1()); + $this->assertInstanceOf(__NAMESPACE__ . '\MappedSuperclassRelated1', $e2->getMappedRelated1()); $this->assertEquals(42, $e2->getMapped1()); $this->assertEquals('bar', $e2->getMapped2()); } @@ -95,17 +98,17 @@ public function setName($name) { $this->name = $name; } - + public function getName() { return $this->name; } - + public function setId($id) { $this->id = $id; } - + public function getId() { return $this->id; @@ -120,22 +123,22 @@ class DocumentSubClass extends MappedSuperclassBase /** @ODM\Field(type="string") */ private $name; - + public function setName($name) { $this->name = $name; } - + public function getName() { return $this->name; } - + public function setId($id) { $this->id = $id; } - + public function getId() { return $this->id; diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/MemoryUsageTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/MemoryUsageTest.php index 24d1221c76..5156665265 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/MemoryUsageTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/MemoryUsageTest.php @@ -1,21 +1,33 @@ phonenumber = '12345'; @@ -46,7 +58,7 @@ public function testMemoryUsage() private function formatMemory($size) { - $unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb'); + $unit = ['b', 'kb', 'mb', 'gb', 'tb', 'pb']; return round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . ' ' . $unit[$i]; } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/NestedCollectionsTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/NestedCollectionsTest.php index dfb8a6a49f..57ff80f071 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/NestedCollectionsTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/NestedCollectionsTest.php @@ -1,13 +1,17 @@ dm->flush(); $this->dm->clear(); - $test = $this->dm->getDocumentCollection(__NAMESPACE__.'\Order')->findOne(); + $test = $this->dm->getDocumentCollection(__NAMESPACE__ . '\Order')->findOne(); - $this->assertInstanceOf(\MongoDB\BSON\ObjectId::class, $test['product']['_id']); + $this->assertInstanceOf(ObjectId::class, $test['product']['_id']); $this->assertEquals('Order', $test['title']); $this->assertEquals('Product', $test['product']['title']); - $doc = $this->dm->find(__NAMESPACE__.'\Order', $order->id); - $this->assertInstanceOf(__NAMESPACE__.'\Order', $order); + $doc = $this->dm->find(__NAMESPACE__ . '\Order', $order->id); + $this->assertInstanceOf(__NAMESPACE__ . '\Order', $order); $this->assertInternalType('string', $doc->product->id); $this->assertEquals((string) $test['product']['_id'], $doc->product->id); $this->assertEquals('Order', $doc->title); @@ -42,22 +48,22 @@ public function testSimple() $this->dm->clear(); - $order = $this->dm->find(__NAMESPACE__.'\Order', $order->id); - $this->assertInstanceOf(__NAMESPACE__.'\Order', $order); + $order = $this->dm->find(__NAMESPACE__ . '\Order', $order->id); + $this->assertInstanceOf(__NAMESPACE__ . '\Order', $order); - $product = $this->dm->find(__NAMESPACE__.'\Product', $product->id); - $this->assertInstanceOf(__NAMESPACE__.'\Product', $product); + $product = $this->dm->find(__NAMESPACE__ . '\Product', $product->id); + $this->assertInstanceOf(__NAMESPACE__ . '\Product', $product); $order->product->title = 'tesgttttt'; $this->dm->flush(); $this->dm->clear(); - $test1 = $this->dm->getDocumentCollection(__NAMESPACE__.'\Product')->findOne(); - $test2 = $this->dm->getDocumentCollection(__NAMESPACE__.'\Order')->findOne(); + $test1 = $this->dm->getDocumentCollection(__NAMESPACE__ . '\Product')->findOne(); + $test2 = $this->dm->getDocumentCollection(__NAMESPACE__ . '\Order')->findOne(); $this->assertNotEquals($test1['title'], $test2['product']['title']); - $order = $this->dm->find(__NAMESPACE__.'\Order', $order->id); - $product = $this->dm->find(__NAMESPACE__.'\Product', $product->id); + $order = $this->dm->find(__NAMESPACE__ . '\Order', $order->id); + $product = $this->dm->find(__NAMESPACE__ . '\Product', $product->id); $this->assertNotEquals($product->title, $order->product->title); } @@ -70,7 +76,7 @@ public function testNestedCategories() $this->dm->flush(); $this->dm->clear(); - $category = $this->dm->find(__NAMESPACE__.'\Category', $category->getId()); + $category = $this->dm->find(__NAMESPACE__ . '\Category', $category->getId()); $this->assertNotNull($category); $category->setName('Root Changed'); $children = $category->getChildren(); @@ -81,7 +87,7 @@ public function testNestedCategories() $this->dm->flush(); $this->dm->clear(); - $category = $this->dm->find(__NAMESPACE__.'\Category', $category->getId()); + $category = $this->dm->find(__NAMESPACE__ . '\Category', $category->getId()); $children = $category->getChildren(); $this->assertEquals('Child 1 Changed', $children[0]->getName()); @@ -101,7 +107,7 @@ public function testNestedReference() $this->dm->flush(); $this->dm->clear(); - $test = $this->dm->getRepository(__NAMESPACE__.'\Hierarchy')->findOneBy(array('name' => 'Root')); + $test = $this->dm->getRepository(__NAMESPACE__ . '\Hierarchy')->findOneBy(['name' => 'Root']); $this->assertNotNull($test); $child1 = $test->getChild('Child 1')->setName('Child 1 Changed'); @@ -112,22 +118,22 @@ public function testNestedReference() $this->dm->flush(); $this->dm->clear(); - $test = $this->dm->find(__NAMESPACE__.'\Hierarchy', $test->getId()); + $test = $this->dm->find(__NAMESPACE__ . '\Hierarchy', $test->getId()); $this->assertNotNull($test); $this->assertEquals('Root Changed', $test->getName()); $this->assertEquals('Child 1 Changed', $test->getChild(0)->getName()); $this->assertEquals('Child 2 Changed', $test->getChild(1)->getName()); - $child3 = $this->dm->getRepository(__NAMESPACE__.'\Hierarchy')->findOneBy(array('name' => 'Child 3')); + $child3 = $this->dm->getRepository(__NAMESPACE__ . '\Hierarchy')->findOneBy(['name' => 'Child 3']); $this->assertNotNull($child3); $child3->setName('Child 3 Changed'); $this->dm->flush(); - $child3 = $this->dm->getRepository(__NAMESPACE__.'\Hierarchy')->findOneBy(array('name' => 'Child 3 Changed')); + $child3 = $this->dm->getRepository(__NAMESPACE__ . '\Hierarchy')->findOneBy(['name' => 'Child 3 Changed']); $this->assertNotNull($child3); $this->assertEquals('Child 3 Changed', $child3->getName()); - $test = $this->dm->getDocumentCollection(__NAMESPACE__.'\Hierarchy')->findOne(array('name' => 'Child 1 Changed')); + $test = $this->dm->getDocumentCollection(__NAMESPACE__ . '\Hierarchy')->findOne(['name' => 'Child 1 Changed']); $this->assertArrayNotHasKey('children', $test, 'Test empty array is not stored'); } } @@ -142,7 +148,7 @@ class Hierarchy private $name; /** @ODM\ReferenceMany(targetDocument="Hierarchy") */ - private $children = array(); + private $children = []; public function __construct($name) { diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/OrphanRemovalEmbedTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/OrphanRemovalEmbedTest.php index 2da2f47a3d..e961772e8b 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/OrphanRemovalEmbedTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/OrphanRemovalEmbedTest.php @@ -1,13 +1,17 @@ name = 'Jon Wage'; - $customer->cart = new \Documents\Cart; + $customer->cart = new Cart(); $customer->cart->numItems = 5; $customer->cart->customer = $customer; $customer->cartTest = 'test'; @@ -51,9 +65,9 @@ public function testOneToOne() public function testOneToManyBiDirectional() { - $product = new \Documents\Product('Book'); - $product->addFeature(new \Documents\Feature('Pages')); - $product->addFeature(new \Documents\Feature('Cover')); + $product = new Product('Book'); + $product->addFeature(new Feature('Pages')); + $product->addFeature(new Feature('Cover')); $this->dm->persist($product); $this->dm->flush(); $this->dm->clear(); @@ -75,15 +89,15 @@ public function testOneToManyBiDirectional() public function testOneToManySelfReferencing() { - $node = new \Documents\BrowseNode('Root'); - $node->addChild(new \Documents\BrowseNode('Child 1')); - $node->addChild(new \Documents\BrowseNode('Child 2')); + $node = new BrowseNode('Root'); + $node->addChild(new BrowseNode('Child 1')); + $node->addChild(new BrowseNode('Child 2')); $this->dm->persist($node); $this->dm->flush(); $this->dm->clear(); - $check = $this->dm->getDocumentCollection(get_class($node))->findOne(array('parent' => array('$exists' => false))); + $check = $this->dm->getDocumentCollection(get_class($node))->findOne(['parent' => ['$exists' => false]]); $this->assertNotNull($check); $this->assertArrayNotHasKey('children', $check); @@ -105,8 +119,8 @@ public function testOneToManySelfReferencing() public function testManyToMany() { - $baseballTag = new \Documents\Tag('baseball'); - $blogPost = new \Documents\BlogPost(); + $baseballTag = new Tag('baseball'); + $blogPost = new BlogPost(); $blogPost->name = 'Test'; $blogPost->addTag($baseballTag); @@ -137,10 +151,10 @@ public function testManyToMany() public function testManyToManySelfReferencing() { - $jwage = new \Documents\FriendUser('jwage'); - $fabpot = new \Documents\FriendUser('fabpot'); + $jwage = new FriendUser('jwage'); + $fabpot = new FriendUser('fabpot'); $fabpot->addFriend($jwage); - $romanb = new \Documents\FriendUser('romanb'); + $romanb = new FriendUser('romanb'); $romanb->addFriend($jwage); $jwage->addFriend($fabpot); $jwage->addFriend($romanb); @@ -202,9 +216,9 @@ public function testSortLimitAndSkipReferences() $date2 = new DateTime(); $date2->setTimestamp(strtotime('-10 seconds')); - $blogPost = new \Documents\BlogPost('Test'); - $blogPost->addComment(new \Documents\Comment('Comment 1', $date1)); - $blogPost->addComment(new \Documents\Comment('Comment 2', $date2)); + $blogPost = new BlogPost('Test'); + $blogPost->addComment(new Comment('Comment 1', $date1)); + $blogPost->addComment(new Comment('Comment 2', $date2)); $this->dm->persist($blogPost); $this->dm->flush(); @@ -243,8 +257,8 @@ public function testSortLimitAndSkipReferences() ->getQuery() ->getSingleResult(); - $blogPost->addComment(new \Documents\Comment('Comment 3 by admin', $date1, true)); - $blogPost->addComment(new \Documents\Comment('Comment 4 by admin', $date2, true)); + $blogPost->addComment(new Comment('Comment 3 by admin', $date1, true)); + $blogPost->addComment(new Comment('Comment 4 by admin', $date2, true)); $this->dm->flush(); $this->dm->clear(); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/PersistentCollectionCloneTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/PersistentCollectionCloneTest.php index 907662423d..9479ae494e 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/PersistentCollectionCloneTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/PersistentCollectionCloneTest.php @@ -1,11 +1,15 @@ username = "beberlei"; - $user1->name = "Benjamin"; - $user1->status = "active"; + $user1->username = 'beberlei'; + $user1->name = 'Benjamin'; + $user1->status = 'active'; $group1 = new CmsGroup(); - $group1->name = "test"; + $group1->name = 'test'; $group2 = new CmsGroup(); - $group2->name = "test"; + $group2->name = 'test'; $user1->addGroup($group1); $user1->addGroup($group2); $user2 = new CmsUser(); - $user2->username = "romanb"; - $user2->name = "Roman"; - $user2->status = "active"; + $user2->username = 'romanb'; + $user2->name = 'Roman'; + $user2->status = 'active'; $this->dm->persist($user1); $this->dm->persist($user2); @@ -77,7 +81,7 @@ public function testCloneThenDirtyPersistentCollection() $user2 = $this->user2; $group3 = new CmsGroup(); - $group3->name = "test"; + $group3->name = 'test'; $user2->groups = clone $user1->groups; $user2->groups->add($group3); @@ -98,7 +102,7 @@ public function testNotCloneAndPassAroundFlush() $user2 = $this->user2; $group3 = new CmsGroup(); - $group3->name = "test"; + $group3->name = 'test'; $user2->groups = $user1->groups; $user2->groups->add($group3); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/PersistingTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/PersistingTest.php index cbeaea76a2..c9f6d929f8 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/PersistingTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/PersistingTest.php @@ -1,14 +1,14 @@ dm->createQueryBuilder('Documents\User'); $embeddedQb = $this->dm->createQueryBuilder('Documents\Phonenumber'); - $qb->field('phonenumbers')->elemMatch($embeddedQb->expr()->field('lastCalledBy.$id')->equals(new \MongoDB\BSON\ObjectId($user1->getId()))); + $qb->field('phonenumbers')->elemMatch($embeddedQb->expr()->field('lastCalledBy.$id')->equals(new ObjectId($user1->getId()))); $query = $qb->getQuery(); $user = $query->getSingleResult(); $this->assertNotNull($user); @@ -73,12 +80,12 @@ public function testAddNot() $this->dm->flush(); $qb = $this->dm->createQueryBuilder('Documents\User'); - $qb->field('username')->not($qb->expr()->in(array('boo'))); + $qb->field('username')->not($qb->expr()->in(['boo'])); $query = $qb->getQuery(); $user = $query->getSingleResult(); $this->assertNull($user); - $qb->field('username')->not($qb->expr()->in(array('1boo'))); + $qb->field('username')->not($qb->expr()->in(['1boo'])); $query = $qb->getQuery(); $user = $query->getSingleResult(); $this->assertNotNull($user); @@ -112,23 +119,23 @@ public function testDistinct() ->field('username')->equals('distinct_test'); $q = $qb->getQuery(); $results = $q->execute(); - $this->assertEquals(array(1, 2, 3), $results); + $this->assertEquals([1, 2, 3], $results); $results = $this->dm->createQueryBuilder('Documents\User') ->distinct('count') ->field('username')->equals('distinct_test') ->getQuery() ->execute(); - $this->assertEquals(array(1, 2, 3), $results); + $this->assertEquals([1, 2, 3], $results); } public function testDistinctWithDifferentDbName() { $c1 = new CmsComment(); - $c1->authorIp = "127.0.0.1"; + $c1->authorIp = '127.0.0.1'; $c2 = new CmsComment(); $c3 = new CmsComment(); - $c2->authorIp = $c3->authorIp = "192.168.0.1"; + $c2->authorIp = $c3->authorIp = '192.168.0.1'; $this->dm->persist($c1); $this->dm->persist($c2); $this->dm->persist($c3); @@ -139,7 +146,7 @@ public function testDistinctWithDifferentDbName() ->distinct('authorIp') ->getQuery() ->execute(); - $this->assertEquals(array("127.0.0.1", "192.168.0.1"), $results); + $this->assertEquals(['127.0.0.1', '192.168.0.1'], $results); } public function testFindQuery() @@ -316,8 +323,8 @@ public function testDateRange() $qb = $this->dm->createQueryBuilder('Documents\Article'); $qb->field('createdAt')->range( - new \MongoDB\BSON\UTCDateTime(strtotime('1985-09-01 01:00:00') * 1000), - new \MongoDB\BSON\UTCDateTime(strtotime('1985-09-04') * 1000) + new UTCDateTime(strtotime('1985-09-01 01:00:00') * 1000), + new UTCDateTime(strtotime('1985-09-04') * 1000) ); $query = $qb->getQuery(); $articles = array_values($query->execute()->toArray()); @@ -343,7 +350,7 @@ public function testQueryIsIterable() public function testQueryReferences() { - $group = new \Documents\Group('Test Group'); + $group = new Group('Test Group'); $user = new User(); $user->setUsername('cool'); @@ -362,26 +369,22 @@ public function testQueryReferences() public function testQueryWhereIn() { $qb = $this->dm->createQueryBuilder('Documents\User'); - $choices = array('a', 'b'); + $choices = ['a', 'b']; $qb->field('username')->in($choices); - $expected = array( - 'username' => array( - '$in' => $choices - ) - ); + $expected = [ + 'username' => ['$in' => $choices], + ]; $this->assertSame($expected, $qb->getQueryArray()); } public function testQueryWhereInReferenceId() { $qb = $this->dm->createQueryBuilder('Documents\User'); - $choices = array(new \MongoDB\BSON\ObjectId(), new \MongoDB\BSON\ObjectId()); + $choices = [new ObjectId(), new ObjectId()]; $qb->field('account.$id')->in($choices); - $expected = array( - 'account.$id' => array( - '$in' => $choices - ) - ); + $expected = [ + 'account.$id' => ['$in' => $choices], + ]; $this->assertSame($expected, $qb->getQueryArray()); $this->assertSame($expected, $qb->getQuery()->debug('query')); } @@ -391,9 +394,7 @@ public function testQueryWhereOneValueOfCollection() { $qb = $this->dm->createQueryBuilder('Documents\Article'); $qb->field('tags')->equals('pet'); - $expected = array( - 'tags' => 'pet' - ); + $expected = ['tags' => 'pet']; $this->assertSame($expected, $qb->getQueryArray()); $this->assertSame($expected, $qb->getQuery()->debug('query')); } @@ -402,10 +403,10 @@ public function testQueryWhereOneValueOfCollection() public function testQueryWhereAllValuesOfCollection() { $qb = $this->dm->createQueryBuilder('Documents\Article'); - $qb->field('tags')->equals(array('pet', 'blue')); - $expected = array( - 'tags' => array('pet', 'blue') - ); + $qb->field('tags')->equals(['pet', 'blue']); + $expected = [ + 'tags' => ['pet', 'blue'], + ]; $this->assertSame($expected, $qb->getQueryArray()); $this->assertSame($expected, $qb->getQuery()->debug('query')); } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/RawTypeTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/RawTypeTest.php index 397916ed7b..7c0930a57f 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/RawTypeTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/RawTypeTest.php @@ -1,47 +1,53 @@ raw = $value; - - $this->dm->persist($test); - $this->dm->flush(); - - $result = $this->dm->getDocumentCollection(get_class($test))->findOne(array('_id' => new \MongoDB\BSON\ObjectId($test->id))); - $this->assertEquals($value, $result['raw']); - } - - public function getTestRawTypeData() - { - return array( - array('test'), - array(1), - array(0), - array(array('test' => 'test')), - array(new \MongoDB\BSON\UTCDateTime()), - array(true), - array(array('date' => new \MongoDB\BSON\UTCDateTime())), - array(new \MongoDB\BSON\ObjectId()) - ); - } + /** + * @dataProvider getTestRawTypeData + */ + public function testRawType($value) + { + $test = new RawType(); + $test->raw = $value; + + $this->dm->persist($test); + $this->dm->flush(); + + $result = $this->dm->getDocumentCollection(get_class($test))->findOne(['_id' => new ObjectId($test->id)]); + $this->assertEquals($value, $result['raw']); + } + + public function getTestRawTypeData() + { + return [ + ['test'], + [1], + [0], + [['test' => 'test']], + [new UTCDateTime()], + [true], + [['date' => new UTCDateTime()]], + [new ObjectId()], + ]; + } } /** @ODM\Document */ class RawType { - /** @ODM\Id */ - public $id; + /** @ODM\Id */ + public $id; - /** @ODM\Field(type="raw") */ - public $raw; + /** @ODM\Field(type="raw") */ + public $raw; } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReadOnlyDocumentTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReadOnlyDocumentTest.php index 22b9000576..6b0f4d518a 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReadOnlyDocumentTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReadOnlyDocumentTest.php @@ -1,11 +1,14 @@ dm->persist($rod); $this->dm->flush(); - $rod->value = "o.O"; + $rod->value = 'o.O'; $this->uow->recomputeSingleDocumentChangeSet($this->dm->getClassMetadata(ReadOnlyDocument::class), $rod); $this->assertEmpty($this->uow->getDocumentChangeSet($rod)); } @@ -66,7 +69,7 @@ public function testCantBeUpdated() $this->dm->clear(); $rod = $this->dm->find(ReadOnlyDocument::class, $rod->id); - $rod->value = "o.O"; + $rod->value = 'o.O'; $this->dm->flush(); $this->dm->clear(); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReadPreferenceTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReadPreferenceTest.php index ee45de1bc6..fe616141a4 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReadPreferenceTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReadPreferenceTest.php @@ -1,15 +1,18 @@ dm->getRepository(DocumentWithReadPreference::class) ->createQueryBuilder() - ->setReadPreference(new ReadPreference("secondary", [])) + ->setReadPreference(new ReadPreference('secondary', [])) ->getQuery(); $this->assertReadPreferenceHint(ReadPreference::RP_SECONDARY, $query->getQuery()['readPreference']); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReferenceDiscriminatorsTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReferenceDiscriminatorsTest.php index 18a19893b4..817ad1f63b 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReferenceDiscriminatorsTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReferenceDiscriminatorsTest.php @@ -1,10 +1,13 @@ comments = $comments; diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReferenceEmbeddedDocumentsTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReferenceEmbeddedDocumentsTest.php index b94df3b6af..eb7bd82f39 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReferenceEmbeddedDocumentsTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReferenceEmbeddedDocumentsTest.php @@ -1,13 +1,16 @@ setIssues(new ArrayCollection(array( + $subProject1->setIssues(new ArrayCollection([ new Issue('Issue #1', 'Issue #1 on Sub Project #1'), - new Issue('Issue #2', 'Issue #2 on Sub Project #1') - ))); + new Issue('Issue #2', 'Issue #2 on Sub Project #1'), + ])); - $subProject2->setIssues(new ArrayCollection(array( + $subProject2->setIssues(new ArrayCollection([ new Issue('Issue #1', 'Issue #1 on Sub Project #2'), - new Issue('Issue #2', 'Issue #2 on Sub Project #2') - ))); + new Issue('Issue #2', 'Issue #2 on Sub Project #2'), + ])); $subProjects->add($subProject1); $subProjects->add($subProject2); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReferencePrimerTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReferencePrimerTest.php index 46a086e169..745dacc1c5 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReferencePrimerTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReferencePrimerTest.php @@ -1,15 +1,23 @@ dm->createQueryBuilder(Group::class)->getQuery()->toArray(); $invoked = 0; - $primer = function(DocumentManager $dm, ClassMetadata $class, array $ids, array $hints) use (&$invoked) { + $primer = function (DocumentManager $dm, ClassMetadata $class, array $ids, array $hints) use (&$invoked) { $invoked++; }; @@ -418,8 +422,8 @@ public function testPrimeReferencesInvokesPrimer() $this->dm->flush(); $this->dm->clear(); - $invokedArgs = array(); - $primer = function(DocumentManager $dm, ClassMetadata $class, array $ids, array $hints) use (&$invokedArgs) { + $invokedArgs = []; + $primer = function (DocumentManager $dm, ClassMetadata $class, array $ids, array $hints) use (&$invokedArgs) { $invokedArgs[] = func_get_args(); }; @@ -435,8 +439,8 @@ public function testPrimeReferencesInvokesPrimer() $this->assertArrayHasKey(Query::HINT_READ_PREFERENCE, $invokedArgs[0][3], 'Primer was invoked with UnitOfWork hints from original query.'); $this->assertSame($readPreference, $invokedArgs[0][3][Query::HINT_READ_PREFERENCE], 'Primer was invoked with UnitOfWork hints from original query.'); - $accountIds = array($account->getId()); - $groupIds = array($group1->getId(), $group2->getId()); + $accountIds = [$account->getId()]; + $groupIds = [$group1->getId(), $group2->getId()]; $this->assertEquals($accountIds, $invokedArgs[0][2]); $this->assertEquals($groupIds, $invokedArgs[1][2]); @@ -474,7 +478,7 @@ public function testPrimeEmbeddedReferenceOneLevelDeep() { $user1 = new User(); $user2 = new User(); - $phone = new Phonenumber('555-GET-THIS',$user2); + $phone = new Phonenumber('555-GET-THIS', $user2); $user1->addPhonenumber($phone); $user1->setUsername('SomeName'); @@ -505,16 +509,25 @@ public function testPrimeEmbeddedReferenceTwoLevelsDeep() $product = new ConfigurableProduct('Bundle'); $product->addOption( - new Option('Lens1', new Money(75.00, new Currency('USD',1)), - new StockItem('Filter1', new Money(50.00, new Currency('USD',1)), 1)) + new Option( + 'Lens1', + new Money(75.00, new Currency('USD', 1)), + new StockItem('Filter1', new Money(50.00, new Currency('USD', 1)), 1) + ) ); $product->addOption( - new Option('Lens2', new Money(120.00, new Currency('USD',1)), - new StockItem('Filter2', new Money(100.00, new Currency('USD',1)), 1)) + new Option( + 'Lens2', + new Money(120.00, new Currency('USD', 1)), + new StockItem('Filter2', new Money(100.00, new Currency('USD', 1)), 1) + ) ); $product->addOption( - new Option('Lens3', new Money(180.00, new Currency('USD',1)), - new StockItem('Filter3', new Money(0.01, new Currency('USD',1)), 1)) + new Option( + 'Lens3', + new Money(180.00, new Currency('USD', 1)), + new StockItem('Filter3', new Money(0.01, new Currency('USD', 1)), 1) + ) ); $this->dm->persist($product); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReferenceRepositoryMethodTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReferenceRepositoryMethodTest.php index 659bc9aacf..c3345a49ce 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReferenceRepositoryMethodTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReferenceRepositoryMethodTest.php @@ -1,11 +1,16 @@ setTimestamp(strtotime('-10 seconds')); - $blogPost = new \Documents\BlogPost('Test'); - $blogPost->addComment(new \Documents\Comment('Comment 1', $date1)); - $blogPost->addComment(new \Documents\Comment('Comment 2', $date2)); + $blogPost = new BlogPost('Test'); + $blogPost->addComment(new Comment('Comment 1', $date1)); + $blogPost->addComment(new Comment('Comment 2', $date2)); $this->dm->persist($blogPost); $this->dm->flush(); $this->dm->clear(); @@ -70,9 +75,9 @@ public function testSetStrategy() { $repo = $this->dm->getRepository('Documents\BlogPost'); - $blogPost = new \Documents\BlogPost('Test'); + $blogPost = new BlogPost('Test'); - $blogPost->addComment(new \Documents\Comment('Comment', new \DateTime())); + $blogPost->addComment(new Comment('Comment', new \DateTime())); $this->dm->persist($blogPost); $this->dm->flush(); $this->dm->clear(); @@ -85,9 +90,9 @@ public function testSetStrategy() public function testRepositoryMethodWithoutMappedBy() { - $blogPost = new \Documents\BlogPost('Test'); + $blogPost = new BlogPost('Test'); - $blogPost->addComment(new \Documents\Comment('Comment', new \DateTime())); + $blogPost->addComment(new Comment('Comment', new \DateTime())); $this->dm->persist($blogPost); $this->dm->flush(); $this->dm->clear(); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReferencesTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReferencesTest.php index 0abbfad029..30a2f4eb7d 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReferencesTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/ReferencesTest.php @@ -1,24 +1,31 @@ addGroup(new Group('Group 1')); $user->addGroup(new Group('Group 2')); @@ -86,7 +93,7 @@ public function testLazyLoadedWithNotifyPropertyChanged() $this->dm->clear(); $user = $this->dm->find(get_class($user), $user->getId()); - $this->assertInstanceOf(\Doctrine\Common\Persistence\Proxy::class, $user->getProfileNotify()); + $this->assertInstanceOf(Proxy::class, $user->getProfileNotify()); $this->assertFalse($user->getProfileNotify()->__isInitialized()); $user->getProfileNotify()->setLastName('Malarz'); @@ -126,7 +133,7 @@ public function testOneEmbedded() public function testManyEmbedded() { - $user = new \Documents\User(); + $user = new User(); $user->addPhonenumber(new Phonenumber('6155139185')); $user->addPhonenumber(new Phonenumber('6153303769')); @@ -166,7 +173,7 @@ public function testOneReference() public function testManyReference() { - $user = new \Documents\User(); + $user = new User(); $user->addGroup(new Group('Group 1')); $user->addGroup(new Group('Group 2')); @@ -263,7 +270,7 @@ public function testFlushInitializesNotEmptyPersistentCollection() public function testManyReferenceWithAddToSetStrategy() { - $user = new \Documents\User(); + $user = new User(); $user->addUniqueGroup($group1 = new Group('Group 1')); $user->addUniqueGroup($group1); $user->addUniqueGroup(new Group('Group 2')); @@ -319,7 +326,7 @@ public function testManyReferenceWithAddToSetStrategy() public function testSortReferenceManyOwningSide() { - $user = new \Documents\User(); + $user = new User(); $user->addGroup(new Group('Group 1')); $user->addGroup(new Group('Group 2')); @@ -350,7 +357,7 @@ public function testDocumentNotFoundExceptionWithArrayId() { $test = new DocumentWithArrayReference(); $test->referenceOne = new DocumentWithArrayId(); - $test->referenceOne->id = array('identifier' => 1); + $test->referenceOne->id = ['identifier' => 1]; $this->dm->persist($test); $this->dm->persist($test->referenceOne); @@ -360,10 +367,12 @@ public function testDocumentNotFoundExceptionWithArrayId() $collection = $this->dm->getDocumentCollection(get_class($test)); $collection->updateOne( - array('_id' => new \MongoDB\BSON\ObjectId($test->id)), - array('$set' => array( - 'referenceOne.$id' => array('identifier' => 2), - )) + ['_id' => new ObjectId($test->id)], + [ + '$set' => [ + 'referenceOne.$id' => ['identifier' => 2], + ], + ] ); $test = $this->dm->find(get_class($test), $test->id); @@ -387,13 +396,13 @@ public function testDocumentNotFoundExceptionWithObjectId() $collection = $this->dm->getDocumentCollection(get_class($user)); - $invalidId = new \MongoDB\BSON\ObjectId('abcdefabcdefabcdefabcdef'); + $invalidId = new ObjectId('abcdefabcdefabcdefabcdef'); $collection->updateOne( - array('_id' => new \MongoDB\BSON\ObjectId($user->getId())), - array('$set' => array( - 'profile.$id' => $invalidId, - )) + ['_id' => new ObjectId($user->getId())], + [ + '$set' => ['profile.$id' => $invalidId], + ] ); $user = $this->dm->find(get_class($user), $user->getId()); @@ -418,13 +427,13 @@ public function testDocumentNotFoundExceptionWithMongoBinDataId() $collection = $this->dm->getDocumentCollection(get_class($test)); - $invalidBinData = new \MongoDB\BSON\Binary('testbindata', \MongoDB\BSON\Binary::TYPE_OLD_BINARY); + $invalidBinData = new Binary('testbindata', Binary::TYPE_OLD_BINARY); $collection->updateOne( - array('_id' => new \MongoDB\BSON\ObjectId($test->id)), - array('$set' => array( - 'referenceOne.$id' => $invalidBinData, - )) + ['_id' => new ObjectId($test->id)], + [ + '$set' => ['referenceOne.$id' => $invalidBinData], + ] ); $test = $this->dm->find(get_class($test), $test->id); @@ -444,13 +453,13 @@ public function testDocumentNotFoundEvent() $collection = $this->dm->getDocumentCollection(get_class($user)); - $invalidId = new \MongoDB\BSON\ObjectId('abcdefabcdefabcdefabcdef'); + $invalidId = new ObjectId('abcdefabcdefabcdefabcdef'); $collection->updateOne( - array('_id' => new \MongoDB\BSON\ObjectId($user->getId())), - array('$set' => array( - 'profile.$id' => $invalidId, - )) + ['_id' => new ObjectId($user->getId())], + [ + '$set' => ['profile.$id' => $invalidId], + ] ); $user = $this->dm->find(get_class($user), $user->getId()); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/RemoveTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/RemoveTest.php index 88ebb1f91c..4cc9841c17 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/RemoveTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/RemoveTest.php @@ -1,7 +1,10 @@ repository->find($this->user->getId()); $this->assertSame($this->user, $user2); - $user3 = $this->repository->findOneBy(array('username' => 'w00ting')); + $user3 = $this->repository->findOneBy(['username' => 'w00ting']); $this->assertSame($user2, $user3); } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/ShardKeyTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/ShardKeyTest.php index 985f58f442..711b60851b 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/ShardKeyTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/ShardKeyTest.php @@ -1,11 +1,16 @@ markTestSkipped('mongodb-driver: query logging does not exist'); - if ( ! isset($this->ql)) { + if (! isset($this->ql)) { $this->ql = new QueryLogger(); } @@ -31,7 +36,7 @@ public function setUp() { parent::setUp(); - $class = \Documents\Sharded\ShardedOne::class; + $class = ShardedOne::class; $this->skipTestIfNotSharded($class); $schemaManager = $this->dm->getSchemaManager(); $schemaManager->ensureDocumentSharding($class); @@ -43,7 +48,7 @@ public function testUpdateAfterSave() $this->dm->persist($o); $this->dm->flush(); - /** @var \Documents\Sharded\ShardedOne $o */ + /** @var ShardedOne $o */ $o = $this->dm->find(get_class($o), $o->id); $o->title = 'test2'; $this->dm->flush(); @@ -58,7 +63,7 @@ public function testUpdateAfterSave() public function testUpsert() { $o = new ShardedOne(); - $o->id = new \MongoDB\BSON\ObjectId(); + $o->id = new ObjectId(); $this->dm->persist($o); $this->dm->flush(); @@ -121,6 +126,6 @@ public function testUpdateWithUpsertTrue() $this->dm->flush(); $o->key = 'testing2'; - $this->dm->flush(null, array('upsert' => true)); + $this->dm->flush(null, ['upsert' => true]); } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/SimpleReferencesTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/SimpleReferencesTest.php index 79fe0b7edc..f7302789d7 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/SimpleReferencesTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/SimpleReferencesTest.php @@ -1,10 +1,15 @@ dm->getSchemaManager()->getDocumentIndexes('Documents\SimpleReferenceUser'); - $this->assertEquals(array('userId' => 1), $indexes[0]['keys']); + $this->assertEquals(['userId' => 1], $indexes[0]['keys']); } public function testStorage() { $test = $this->dm->getDocumentCollection('Documents\SimpleReferenceUser')->findOne(); $this->assertNotNull($test); - $this->assertInstanceOf(\MongoDB\BSON\ObjectId::class, $test['userId']); - $this->assertInstanceOf(\MongoDB\BSON\ObjectId::class, $test['users'][0]); + $this->assertInstanceOf(ObjectId::class, $test['userId']); + $this->assertInstanceOf(ObjectId::class, $test['users'][0]); } public function testQuery() { - $this->user = $this->dm->getRepository('Documents\User')->findOneBy(array('username' => 'jwage')); + $this->user = $this->dm->getRepository('Documents\User')->findOneBy(['username' => 'jwage']); $qb = $this->dm->createQueryBuilder('Documents\SimpleReferenceUser'); $qb->field('user')->references($this->user); - $this->assertEquals(array('userId' => new \MongoDB\BSON\ObjectId($this->user->getId())), $qb->getQuery()->debug('query')); + $this->assertEquals(['userId' => new ObjectId($this->user->getId())], $qb->getQuery()->debug('query')); $qb = $this->dm->createQueryBuilder('Documents\SimpleReferenceUser'); $qb->field('user')->equals($this->user->getId()); - $this->assertEquals(array('userId' => new \MongoDB\BSON\ObjectId($this->user->getId())), $qb->getQuery()->debug('query')); + $this->assertEquals(['userId' => new ObjectId($this->user->getId())], $qb->getQuery()->debug('query')); $qb = $this->dm->createQueryBuilder('Documents\SimpleReferenceUser'); - $qb->field('user')->in(array($this->user->getId())); - $this->assertEquals(array('userId' => array('$in' => array(new \MongoDB\BSON\ObjectId($this->user->getId())))), $qb->getQuery()->debug('query')); + $qb->field('user')->in([$this->user->getId()]); + $this->assertEquals(['userId' => ['$in' => [new ObjectId($this->user->getId())]]], $qb->getQuery()->debug('query')); } public function testProxy() { - $this->user = $this->dm->getRepository('Documents\User')->findOneBy(array('username' => 'jwage')); + $this->user = $this->dm->getRepository('Documents\User')->findOneBy(['username' => 'jwage']); $qb = $this->dm->createQueryBuilder('Documents\SimpleReferenceUser'); $qb->field('user')->references($this->user); - $this->assertEquals(array('userId' => new \MongoDB\BSON\ObjectId($this->user->getId())), $qb->getQuery()->debug('query')); + $this->assertEquals(['userId' => new ObjectId($this->user->getId())], $qb->getQuery()->debug('query')); $this->dm->clear(); @@ -81,7 +86,7 @@ public function testProxy() public function testPersistentCollectionOwningSide() { - $test = $this->dm->getRepository('Documents\SimpleReferenceUser')->findOneBy(array()); + $test = $this->dm->getRepository('Documents\SimpleReferenceUser')->findOneBy([]); $users = $test->getUsers()->toArray(); $this->assertEquals(2, $test->getUsers()->count()); $this->assertEquals('jwage', current($users)->getUsername()); @@ -90,40 +95,41 @@ public function testPersistentCollectionOwningSide() public function testPersistentCollectionInverseSide() { - $user = $this->dm->getRepository('Documents\User')->findOneBy(array()); + $user = $this->dm->getRepository('Documents\User')->findOneBy([]); $test = $user->getSimpleReferenceManyInverse()->toArray(); - $this->assertEquals('test' ,current($test)->getName()); + $this->assertEquals('test', current($test)->getName()); } public function testOneInverseSide() { - $user = $this->dm->getRepository('Documents\User')->findOneBy(array()); + $user = $this->dm->getRepository('Documents\User')->findOneBy([]); $test = $user->getSimpleReferenceOneInverse(); $this->assertEquals('test', $test->getName()); } - public function testQueryForNonIds() { + public function testQueryForNonIds() + { $qb = $this->dm->createQueryBuilder('Documents\SimpleReferenceUser'); $qb->field('user')->equals(null); - $this->assertEquals(array('userId' => null), $qb->getQueryArray()); + $this->assertEquals(['userId' => null], $qb->getQueryArray()); $qb = $this->dm->createQueryBuilder('Documents\SimpleReferenceUser'); $qb->field('user')->notEqual(null); - $this->assertEquals(array('userId' => array('$ne' => null)), $qb->getQueryArray()); + $this->assertEquals(['userId' => ['$ne' => null]], $qb->getQueryArray()); $qb = $this->dm->createQueryBuilder('Documents\SimpleReferenceUser'); $qb->field('user')->exists(true); - $this->assertEquals(array('userId' => array('$exists' => true)), $qb->getQueryArray()); + $this->assertEquals(['userId' => ['$exists' => true]], $qb->getQueryArray()); } public function testRemoveDocumentByEmptyRefMany() { $qb = $this->dm->createQueryBuilder('Documents\SimpleReferenceUser'); - $qb->field('users')->equals(array()); - $this->assertEquals(array('users' => array()), $qb->getQueryArray()); + $qb->field('users')->equals([]); + $this->assertEquals(['users' => []], $qb->getQueryArray()); $qb = $this->dm->createQueryBuilder('Documents\SimpleReferenceUser'); $qb->field('users')->equals(new \stdClass()); - $this->assertEquals(array('users' => new \stdClass()), $qb->getQueryArray()); + $this->assertEquals(['users' => new \stdClass()], $qb->getQueryArray()); } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/SimpleTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/SimpleTest.php index 042e3a1b29..8f88b63a38 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/SimpleTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/SimpleTest.php @@ -1,11 +1,14 @@ clear(); }, 0 ), - array( function (DocumentManager $dm, $doc) { $dm->clear(get_class($doc)); }, 1 ), - array( function (DocumentManager $dm, $doc) { $dm->detach($doc); }, 1 ), - ); + return [ + [ + function (DocumentManager $dm) { + $dm->clear(); + }, 0, + ], + [ + function (DocumentManager $dm, $doc) { + $dm->clear(get_class($doc)); + }, 1, + ], + [ + function (DocumentManager $dm, $doc) { + $dm->detach($doc); + }, 1, + ], + ]; } private function expectCount($prop, $expected) @@ -77,7 +92,7 @@ class SplColDoc public $one; /** @ODM\EmbedMany */ - public $many = array(); + public $many = []; } /** @ODM\EmbeddedDocument */ diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/TestTargetDocument.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/TestTargetDocument.php index 7bd43c891e..9755f27a61 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/TestTargetDocument.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/TestTargetDocument.php @@ -1,34 +1,37 @@ reference = new TargetDocumentTestReference(); - $this->dm->persist($test); - $this->dm->persist($test->reference); - $this->dm->flush(); + $test = new TargetDocumentTestDocument(); + $test->reference = new TargetDocumentTestReference(); + $this->dm->persist($test); + $this->dm->persist($test->reference); + $this->dm->flush(); } } /** @ODM\Document */ class TargetDocumentTestDocument { - /** @ODM\Id */ - public $id; + /** @ODM\Id */ + public $id; - /** @ODM\ReferenceOne(targetDocument="Doctrine\ODM\MongoDB\Tests\Functional\TargetDocumentTestReference") */ - public $reference; + /** @ODM\ReferenceOne(targetDocument="Doctrine\ODM\MongoDB\Tests\Functional\TargetDocumentTestReference") */ + public $reference; } /** @ODM\MappedSuperclass */ abstract class TargetDocumentTestReference { - /** @ODM\Id */ - public $id; -} \ No newline at end of file + /** @ODM\Id */ + public $id; +} diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1011Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1011Test.php index 98dbf6ac20..f3e70c2f8d 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1011Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1011Test.php @@ -1,11 +1,14 @@ dm->persist($owner); $this->dm->flush(); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1058Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1058Test.php index 014bf9799b..85abcf9a8d 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1058Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1058Test.php @@ -1,11 +1,16 @@ dm->getEventManager()->addEventListener(array(Events::onFlush), new GH1058Listener()); + $this->dm->getEventManager()->addEventListener([Events::onFlush], new GH1058Listener()); $document = new GH1058PersistDocument(); $document->setValue('value 1'); $this->dm->persist($document); @@ -26,7 +31,7 @@ public function testModifyingDuringOnFlushEventNewDocument() */ public function testModifyingDuringOnFlushEventNewDocumentWithId() { - $this->dm->getEventManager()->addEventListener(array(Events::onFlush), new GH1058Listener()); + $this->dm->getEventManager()->addEventListener([Events::onFlush], new GH1058Listener()); $document = new GH1058UpsertDocument(); $document->generateId(); $document->setValue('value 1'); @@ -37,7 +42,8 @@ public function testModifyingDuringOnFlushEventNewDocumentWithId() class GH1058Listener { - public function onFlush(OnFlushEventArgs $args) { + public function onFlush(OnFlushEventArgs $args) + { $dm = $args->getDocumentManager(); $uow = $dm->getUnitOfWork(); @@ -87,10 +93,10 @@ public function getId() return $this->id; } - public final function generateId() + final public function generateId() { - if (!isset($this->id)) { - $this->id = (string) new \MongoDB\BSON\ObjectId(); + if (! isset($this->id)) { + $this->id = (string) new ObjectId(); } } @@ -99,4 +105,3 @@ public function setValue($value) $this->value = $value; } } - diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1107Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1107Test.php index 5a44dd3a98..fa270d522f 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1107Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1107Test.php @@ -1,5 +1,7 @@ dm->persist($u); $this->dm->persist($u2); $this->dm->flush(); - + $u2->setPhonenumbers(clone $u->getPhonenumbers()); $u2->getPhonenumbers()->clear(); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1138Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1138Test.php index e4f9a99b5b..46367606f2 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1138Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1138Test.php @@ -1,13 +1,16 @@ markTestSkipped('mongodb-driver: query logging does not exist'); - if ( ! isset($this->ql)) { + if (! isset($this->ql)) { $this->ql = new QueryLogger(); } @@ -48,7 +51,7 @@ public function testUpdatingDocumentBeforeItsInsertionShouldNotEntailMultipleQue /** @ODM\Document */ class GH1138Document { - const CLASSNAME = __CLASS__; + public const CLASSNAME = __CLASS__; /** @ODM\Id */ public $id; @@ -81,4 +84,3 @@ public function onFlush(OnFlushEventArgs $args) } } } - diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1152Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1152Test.php index 74411940fe..36b3349640 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1152Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1152Test.php @@ -1,12 +1,15 @@ getDocumentManager(); $document = $args->getDocument(); - if (!$document instanceof GH1152Child) { + if (! $document instanceof GH1152Child) { return; } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1225Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1225Test.php index bf74f86f71..9e743e8723 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1225Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1225Test.php @@ -1,11 +1,15 @@ children->toArray(); } - /** - * @param GH1229Child $child - */ public function addChild(GH1229Child $child) { $child->setOrder(count($this->children)); $this->children->add($child); } - /** - * @param GH1229Child $child - */ public function removeChild(GH1229Child $child) { $this->children->removeElement($child); @@ -190,7 +189,7 @@ public function reorderChildren($starting, $change) /** @ODM\EmbeddedDocument */ class GH1229Child { - const CLASSNAME = __CLASS__; + public const CLASSNAME = __CLASS__; /** @ODM\Field(type="string") */ public $name; @@ -230,5 +229,5 @@ public function setOrder($order) /** @ODM\EmbeddedDocument */ class GH1229ChildTypeB extends GH1229Child { - const CLASSNAME = __CLASS__; + public const CLASSNAME = __CLASS__; } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1232Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1232Test.php index 8bf47267b2..cf9ef59718 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1232Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1232Test.php @@ -1,12 +1,15 @@ add($itemThree); $this->assertSame( - array('Number One', 'Number Two', 'Number Three'), + ['Number One', 'Number Two', 'Number Three'], array_map($getNameCallback, $container->items->toArray()) ); @@ -44,7 +48,7 @@ public function testResortAtomicCollectionsFlipItems() $this->dm->refresh($container); $this->assertSame( - array('Number One','Number Three', 'Number Two'), + ['Number One','Number Three', 'Number Two'], array_map($getNameCallback, $container->items->toArray()) ); } @@ -73,7 +77,7 @@ public function testResortAtomicCollections() $container->add($itemThree); $this->assertSame( - array('Number One', 'Number Two', 'Number Three'), + ['Number One', 'Number Two', 'Number Three'], array_map($getNameCallback, $container->items->toArray()) ); @@ -83,7 +87,7 @@ public function testResortAtomicCollections() $this->dm->refresh($container); $this->assertSame( - array('Number One', 'Number Two', 'Number Three'), + ['Number One', 'Number Two', 'Number Three'], array_map($getNameCallback, $container->items->toArray()) ); @@ -93,7 +97,7 @@ public function testResortAtomicCollections() $this->dm->refresh($container); $this->assertSame( - array('Number Two', 'Number One', 'Number Three'), + ['Number Two', 'Number One', 'Number Three'], array_map($getNameCallback, $container->items->toArray()) ); @@ -103,7 +107,7 @@ public function testResortAtomicCollections() $this->dm->refresh($container); $this->assertSame( - array('Number One', 'Number Three', 'Number Two'), + ['Number One', 'Number Three', 'Number Two'], array_map($getNameCallback, $container->items->toArray()) ); @@ -113,7 +117,7 @@ public function testResortAtomicCollections() $this->dm->refresh($container); $this->assertSame( - array('Number One', 'Number Three', 'Number Two'), + ['Number One', 'Number Three', 'Number Two'], array_map($getNameCallback, $container->items->toArray()) ); @@ -123,7 +127,7 @@ public function testResortAtomicCollections() $this->dm->refresh($container); $this->assertSame( - array('Number Three', 'Number One', 'Number Two'), + ['Number Three', 'Number One', 'Number Two'], array_map($getNameCallback, $container->items->toArray()) ); @@ -132,14 +136,14 @@ public function testResortAtomicCollections() public static function getCollectionStrategies() { - return array( - 'testResortWithStrategyAddToSet' => array(ClassMetadata::STORAGE_STRATEGY_ADD_TO_SET), - 'testResortWithStrategySet' => array(ClassMetadata::STORAGE_STRATEGY_SET), - 'testResortWithStrategySetArray' => array(ClassMetadata::STORAGE_STRATEGY_SET_ARRAY), - 'testResortWithStrategyPushAll' => array(ClassMetadata::STORAGE_STRATEGY_PUSH_ALL), - 'testResortWithStrategyAtomicSet' => array(ClassMetadata::STORAGE_STRATEGY_ATOMIC_SET), - 'testResortWithStrategyAtomicSetArray' => array(ClassMetadata::STORAGE_STRATEGY_ATOMIC_SET_ARRAY), - ); + return [ + 'testResortWithStrategyAddToSet' => [ClassMetadata::STORAGE_STRATEGY_ADD_TO_SET], + 'testResortWithStrategySet' => [ClassMetadata::STORAGE_STRATEGY_SET], + 'testResortWithStrategySetArray' => [ClassMetadata::STORAGE_STRATEGY_SET_ARRAY], + 'testResortWithStrategyPushAll' => [ClassMetadata::STORAGE_STRATEGY_PUSH_ALL], + 'testResortWithStrategyAtomicSet' => [ClassMetadata::STORAGE_STRATEGY_ATOMIC_SET], + 'testResortWithStrategyAtomicSetArray' => [ClassMetadata::STORAGE_STRATEGY_ATOMIC_SET_ARRAY], + ]; } /** @@ -161,7 +165,7 @@ public function testResortEmbedManyCollection($strategy) $this->dm->refresh($container); $this->assertSame( - array('one', 'two', 'three'), + ['one', 'two', 'three'], array_map($getNameCallback, $container->$strategy->toArray()) ); @@ -175,7 +179,7 @@ public function testResortEmbedManyCollection($strategy) $this->dm->refresh($container); $this->assertSame( - array('one', 'three', 'two'), + ['one', 'three', 'two'], array_map($getNameCallback, $container->$strategy->toArray()) ); } @@ -184,7 +188,8 @@ public function testResortEmbedManyCollection($strategy) /** * @ODM\Document(collection="item") */ -class Item { +class Item +{ /** @ODM\Id */ public $id; @@ -206,7 +211,8 @@ public function __construct(Container $c, $name) /** * @ODM\EmbeddedDocument */ -class Element { +class Element +{ /** @ODM\Id */ public $id; @@ -222,17 +228,18 @@ public function __construct($name) /** * @ODM\Document(collection="container") */ -class Container { +class Container +{ /** @ODM\Id */ public $id; /** @ODM\ReferenceMany( - * targetDocument="Item", - * cascade={"refresh","persist"}, - * orphanRemoval="true", - * strategy="atomicSet" - * ) - */ + * targetDocument="Item", + * cascade={"refresh","persist"}, + * orphanRemoval="true", + * strategy="atomicSet" + * ) + */ public $items; /** @@ -305,7 +312,7 @@ public function __construct() public function add(Item $item) { $this->items->add($item); - if ($this->items->count() == 1) { + if ($this->items->count() === 1) { $this->firstItem = $item; } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1294Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1294Test.php index 310886819a..b42f86680d 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1294Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1294Test.php @@ -1,10 +1,14 @@ dm->createQueryBuilder($userClass); $res = $qb->field('id') - ->equals(new \MongoDB\BSON\Regex("^bbb.*$", 'i')) + ->equals(new Regex('^bbb.*$', 'i')) ->getQueryArray(); - $this->assertInstanceOf(\MongoDB\BSON\Regex::class, $res['_id']); + $this->assertInstanceOf(Regex::class, $res['_id']); $this->assertEquals('^bbb.*$', $res['_id']->getPattern()); $this->assertEquals('i', $res['_id']->getFlags()); } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1346Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1346Test.php index 2ddcf51050..a9acd170d2 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1346Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1346Test.php @@ -1,11 +1,14 @@ dm->getHydratorFactory()->hydrate($document, array( + $document = new GH1418Document(); + $this->dm->getHydratorFactory()->hydrate($document, [ '_id' => 1, 'name' => 'maciej', 'embedOne' => ['name' => 'maciej', 'sourceId' => 1], 'embedMany' => [ - ['name' => 'maciej', 'sourceId' => 2] + ['name' => 'maciej', 'sourceId' => 2], ], - ), [ Query::HINT_READ_ONLY => true ]); + ], [ Query::HINT_READ_ONLY => true ]); $this->assertEquals(1, $document->embedOne->id); $this->assertEquals(2, $document->embedMany->first()->id); @@ -37,7 +40,7 @@ public function testManualHydrateAndMerge() public function testReadDocumentAndManage() { - $document = new GH1418Document; + $document = new GH1418Document(); $document->id = 1; $embedded = new GH1418Embedded(); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1428Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1428Test.php index 7f8eab65a7..c66ee9b569 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1428Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1428Test.php @@ -1,5 +1,7 @@ id = $id; diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1525Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1525Test.php index 43b9ef47a6..0dedf9b8df 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1525Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1525Test.php @@ -1,11 +1,15 @@ dm->clear(); for ($i = 0; $i < 2; ++$i) { - $test = $this->dm->getRepository(GH1525Document::class)->findOneBy(array('name' => 'test' . $i)); + $test = $this->dm->getRepository(GH1525Document::class)->findOneBy(['name' => 'test' . $i]); $this->assertInstanceOf(GH1525Document::class, $test); @@ -41,7 +45,7 @@ public function testEmbedCloneTwoFlushesPerDocument() public function testEmbedCloneWithIdStrategyNoneOnParentAndEarlyPersist() { - $uuidGen = new \Doctrine\ODM\MongoDB\Id\UuidGenerator(); + $uuidGen = new UuidGenerator(); $embedded = new GH1525Embedded('embedded'); $count = 2; @@ -55,7 +59,7 @@ public function testEmbedCloneWithIdStrategyNoneOnParentAndEarlyPersist() $this->dm->clear(); for ($i = 0; $i < $count; ++$i) { - $test = $this->dm->getRepository(GH1525DocumentIdStrategyNone::class)->findOneBy(array('name' => 'test' . $i)); + $test = $this->dm->getRepository(GH1525DocumentIdStrategyNone::class)->findOneBy(['name' => 'test' . $i]); $this->assertInstanceOf(GH1525DocumentIdStrategyNone::class, $test); @@ -66,7 +70,7 @@ public function testEmbedCloneWithIdStrategyNoneOnParentAndEarlyPersist() public function testEmbedCloneWithIdStrategyNoneOnParentAndLatePersist() { - $uuidGen = new \Doctrine\ODM\MongoDB\Id\UuidGenerator(); + $uuidGen = new UuidGenerator(); $embedded = new GH1525Embedded('embedded'); $count = 2; @@ -80,7 +84,7 @@ public function testEmbedCloneWithIdStrategyNoneOnParentAndLatePersist() $this->dm->clear(); for ($i = 0; $i < $count; ++$i) { - $test = $this->dm->getRepository(GH1525DocumentIdStrategyNone::class)->findOneBy(array('name' => 'test' . $i)); + $test = $this->dm->getRepository(GH1525DocumentIdStrategyNone::class)->findOneBy(['name' => 'test' . $i]); $this->assertInstanceOf(GH1525DocumentIdStrategyNone::class, $test); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1572Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1572Test.php index bbe7f9ea6e..5f325cd1a4 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1572Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1572Test.php @@ -1,5 +1,7 @@ id = 1; + public function testTest() + { + $order = new GH245Order(); + $order->id = 1; - $orderLog = new GH245OrderLog(); - $orderLog->order = $order; + $orderLog = new GH245OrderLog(); + $orderLog->order = $order; - $this->dm->persist($orderLog); - $this->dm->persist($order); - $this->dm->flush(); - $this->dm->clear(); + $this->dm->persist($orderLog); + $this->dm->persist($order); + $this->dm->flush(); + $this->dm->clear(); - $user = $this->dm->find(get_class($order), $order->id); + $user = $this->dm->find(get_class($order), $order->id); - $this->assertInternalType('int', $order->id); + $this->assertInternalType('int', $order->id); - $check = $this->dm->getDocumentCollection(get_class($orderLog))->findOne(); - $this->assertInternalType('int', $check['order']['$id']); - } + $check = $this->dm->getDocumentCollection(get_class($orderLog))->findOne(); + $this->assertInternalType('int', $check['order']['$id']); + } } /** @ODM\Document */ class GH245Order { - /** @ODM\Id(strategy="NONE") */ - public $id; + /** @ODM\Id(strategy="NONE") */ + public $id; } /** @ODM\Document */ class GH245OrderLog { - /** @ODM\Id */ - public $id; + /** @ODM\Id */ + public $id; - /** @ODM\ReferenceOne(targetDocument="GH245Order") */ - public $order; + /** @ODM\ReferenceOne(targetDocument="GH245Order") */ + public $order; } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH267Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH267Test.php index 197f553608..7a3d999b4f 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH267Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH267Test.php @@ -1,5 +1,7 @@ name = $name; } - public function setId($id) + public function setId($id) { $this->id = $id; } - public function getId() + public function getId() { return $this->id; } - public function setName($name) + public function setName($name) { $this->name = $name; } - public function getName() + public function getName() { return $this->name; } - public function setCompany($company) + public function setCompany($company) { $this->company = $company; } - public function getCompany() + public function getCompany() { return $this->company; } @@ -113,7 +115,7 @@ public function getCompany() * @ODM\DiscriminatorMap({"seller"="GH267SellerCompany", "buyer"="GH267BuyerCompany"}) */ class GH267Company -{ +{ /** @ODM\Id */ protected $id; @@ -122,22 +124,22 @@ class GH267Company */ protected $users; - public function setId($id) + public function setId($id) { $this->id = $id; } - public function getId() + public function getId() { return $this->id; } - public function setUsers($users) + public function setUsers($users) { $this->users = $users; } - public function getUsers() + public function getUsers() { return $this->users; } @@ -147,14 +149,12 @@ public function getUsers() * @ODM\Document(collection="companies") */ class GH267BuyerCompany extends GH267Company -{ - +{ } /** * @ODM\Document(collection="companies") */ class GH267SellerCompany extends GH267Company -{ - +{ } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH385Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH385Test.php index 1753843134..c7452dfc84 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH385Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH385Test.php @@ -1,14 +1,16 @@ dm->createQueryBuilder('Documents\User') ->upsert() @@ -19,11 +21,11 @@ public function testQueryBuilderShouldPrepareUnmappedFields() $debug = $qb->getQuery()->getQuery(); - $this->assertEquals(array('$inc' => array('foo.bar.level3a' => 1, 'foo.bar.level3b' => 1)), $debug['newObj']); + $this->assertEquals(['$inc' => ['foo.bar.level3a' => 1, 'foo.bar.level3b' => 1]], $debug['newObj']); $qb->getQuery()->execute(); - $check = $this->dm->getDocumentCollection('Documents\User')->findOne(array('_id' => $identifier)); + $check = $this->dm->getDocumentCollection('Documents\User')->findOne(['_id' => $identifier]); $this->assertNotNull($check); $this->assertTrue(isset($check['foo']['bar']['level3a'])); $this->assertTrue(isset($check['foo']['bar']['level3b'])); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH389Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH389Test.php index fab9e4d63f..036e0e7109 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH389Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH389Test.php @@ -1,10 +1,13 @@ 'x', 'b' => 'y', 'c' => 'z'); + $hash = ['a' => 'x', 'b' => 'y', 'c' => 'z']; $doc = new GH453Document(); $doc->hash = $hash; @@ -40,7 +46,7 @@ public function testHashWithStringKeys() public function testHashWithNumericKeys() { - $hash = array(0 => 'x', 1 => 'y', 2 => 'z'); + $hash = [0 => 'x', 1 => 'y', 2 => 'z']; $doc = new GH453Document(); $doc->hash = $hash; @@ -71,7 +77,7 @@ public function testHashWithNumericKeys() public function testCollection() { - $col = array('x', 'y', 'z'); + $col = ['x', 'y', 'z']; $doc = new GH453Document(); $doc->colPush = $col; @@ -107,14 +113,20 @@ public function testCollection() public function testEmbedMany() { - $colPush = new ArrayCollection(array( + $colPush = new ArrayCollection([ new GH453EmbeddedDocument(), new GH453EmbeddedDocument(), new GH453EmbeddedDocument(), - )); - $colSet = $colPush->map(function($v) { return clone $v; }); - $colSetArray = $colPush->map(function($v) { return clone $v; }); - $colAddToSet = $colPush->map(function($v) { return clone $v; }); + ]); + $colSet = $colPush->map(function ($v) { + return clone $v; + }); + $colSetArray = $colPush->map(function ($v) { + return clone $v; + }); + $colAddToSet = $colPush->map(function ($v) { + return clone $v; + }); $doc = new GH453Document(); $doc->embedManyPush = $colPush; @@ -151,21 +163,39 @@ public function testEmbedMany() public function testReferenceMany() { - $colPush = new ArrayCollection(array( + $colPush = new ArrayCollection([ new GH453ReferencedDocument(), new GH453ReferencedDocument(), new GH453ReferencedDocument(), - )); - $colSet = $colPush->map(function($v) { return clone $v; }); - $colSetArray = $colPush->map(function($v) { return clone $v; }); - $colAddToSet = $colPush->map(function($v) { return clone $v; }); + ]); + $colSet = $colPush->map(function ($v) { + return clone $v; + }); + $colSetArray = $colPush->map(function ($v) { + return clone $v; + }); + $colAddToSet = $colPush->map(function ($v) { + return clone $v; + }); $dm = $this->dm; - $colPush->forAll(function($k, $v) use ($dm) { $dm->persist($v); return true; }); - $colSet->forAll(function($k, $v) use ($dm) { $dm->persist($v); return true; }); - $colSetArray->forAll(function($k, $v) use ($dm) { $dm->persist($v); return true; }); - $colAddToSet->forAll(function($k, $v) use ($dm) { $dm->persist($v); return true; }); + $colPush->forAll(function ($k, $v) use ($dm) { + $dm->persist($v); + return true; + }); + $colSet->forAll(function ($k, $v) use ($dm) { + $dm->persist($v); + return true; + }); + $colSetArray->forAll(function ($k, $v) use ($dm) { + $dm->persist($v); + return true; + }); + $colAddToSet->forAll(function ($k, $v) use ($dm) { + $dm->persist($v); + return true; + }); $doc = new GH453Document(); $doc->referenceManyPush = $colPush; @@ -216,13 +246,13 @@ private function assertBsonObject($documentId, $fieldName) private function assertBsonType($bsonType, $documentId, $fieldName) { - $criteria = array('_id' => $documentId); + $criteria = ['_id' => $documentId]; - if (4 === $bsonType) { + if ($bsonType === 4) { // See: https://jira.mongodb.org/browse/SERVER-1475 $criteria['$where'] = sprintf('Array.isArray(this.%s)', $fieldName); } else { - $criteria[$fieldName] = array('$type' => $bsonType); + $criteria[$fieldName] = ['$type' => $bsonType]; } $this->assertNotNull($this->dm->getRepository(__NAMESPACE__ . '\GH453Document')->findOneBy($criteria)); @@ -240,22 +270,22 @@ private function assertBsonObjectAndValue($expectedValue, $documentId, $fieldNam private function assertBsonTypeAndValue($bsonType, $expectedValue, $documentId, $fieldName) { - if (4 === $bsonType) { + if ($bsonType === 4) { $expectedValue = array_values((array) $expectedValue); - } elseif (3 === $bsonType) { + } elseif ($bsonType === 3) { $expectedValue = (object) $expectedValue; } - $criteria = array( + $criteria = [ '_id' => $documentId, - '$and' => array(array($fieldName => $expectedValue)), - ); + '$and' => [[$fieldName => $expectedValue]], + ]; - if (4 === $bsonType) { + if ($bsonType === 4) { // See: https://jira.mongodb.org/browse/SERVER-1475 - $criteria['$and'][] = array('$where' => sprintf('Array.isArray(this.%s)', $fieldName)); + $criteria['$and'][] = ['$where' => sprintf('Array.isArray(this.%s)', $fieldName)]; } else { - $criteria['$and'][] = array($fieldName => array('$type' => $bsonType)); + $criteria['$and'][] = [$fieldName => ['$type' => $bsonType]]; } $this->assertNotNull($this->dm->getRepository(__NAMESPACE__ . '\GH453Document')->findOneBy($criteria)); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH467Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH467Test.php index 282ae50e02..9cb246c263 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH467Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH467Test.php @@ -1,10 +1,13 @@ addRef($b); $a->addRef($c); @@ -24,10 +28,10 @@ public function testSetRefMany() $collection = $this->dm->getDocumentCollection(__NAMESPACE__ . '\GH499Document'); - $a = $collection->findOne(array('_id' => new \MongoDB\BSON\ObjectId($a->getId()))); + $a = $collection->findOne(['_id' => new ObjectId($a->getId())]); - $this->assertEquals(new \MongoDB\BSON\ObjectId($b->getId()), $a['refMany'][$b->getId()]); - $this->assertEquals(new \MongoDB\BSON\ObjectId($c->getId()), $a['refMany'][$c->getId()]); + $this->assertEquals(new ObjectId($b->getId()), $a['refMany'][$b->getId()]); + $this->assertEquals(new ObjectId($c->getId()), $a['refMany'][$c->getId()]); } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH520Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH520Test.php index 117b51a3c5..092f64a66c 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH520Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH520Test.php @@ -1,5 +1,7 @@ dm->clear(); $primedIds = null; - $primer = function(DocumentManager $dm, ClassMetadata $class, array $ids, array $hints) use (&$primedIds) { + $primer = function (DocumentManager $dm, ClassMetadata $class, array $ids, array $hints) use (&$primedIds) { $primedIds = $ids; }; diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH529Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH529Test.php index ca8828c522..a4fdfbe990 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH529Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH529Test.php @@ -1,14 +1,19 @@ id = $identifier; diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH560Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH560Test.php index 73f29243f3..53ae20d164 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH560Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH560Test.php @@ -1,22 +1,26 @@ dm->getEventManager()->addEventSubscriber($listener); @@ -25,10 +29,10 @@ public function testPersistListenersAreCalled($id) $this->dm->flush(); $this->dm->clear(); - $called = array( - array(Events::prePersist, __NAMESPACE__ . '\GH560Document'), - array(Events::postPersist, __NAMESPACE__ . '\GH560Document'), - ); + $called = [ + [Events::prePersist, __NAMESPACE__ . '\GH560Document'], + [Events::postPersist, __NAMESPACE__ . '\GH560Document'], + ]; $this->assertEquals($called, $listener->called); } @@ -52,10 +56,10 @@ public function testDocumentWithCustomIdStrategyIsSavedAndFoundFromDatabase($id) */ public function testUpdateListenersAreCalled($id) { - $listener = new GH560EventSubscriber(array( + $listener = new GH560EventSubscriber([ Events::preUpdate, Events::postUpdate, - )); + ]); $this->dm->getEventManager()->addEventSubscriber($listener); @@ -67,20 +71,20 @@ public function testUpdateListenersAreCalled($id) $this->dm->flush(); $this->dm->clear(); - $called = array( - array(Events::preUpdate, __NAMESPACE__ . '\GH560Document'), - array(Events::postUpdate, __NAMESPACE__ . '\GH560Document'), - ); + $called = [ + [Events::preUpdate, __NAMESPACE__ . '\GH560Document'], + [Events::postUpdate, __NAMESPACE__ . '\GH560Document'], + ]; $this->assertEquals($called, $listener->called); } public function provideDocumentIds() { - return array( - array(123456), - array('516ee7636803faea5600090a:path10421'), - ); + return [ + [123456], + ['516ee7636803faea5600090a:path10421'], + ]; } } @@ -91,7 +95,7 @@ class GH560EventSubscriber implements EventSubscriber public function __construct(array $events) { - $this->called = array(); + $this->called = []; $this->events = $events; } @@ -102,7 +106,7 @@ public function getSubscribedEvents() public function __call($eventName, $args) { - $this->called[] = array($eventName, get_class($args[0]->getDocument())); + $this->called[] = [$eventName, get_class($args[0]->getDocument())]; } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH561Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH561Test.php index c26af52df4..17d1243eaa 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH561Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH561Test.php @@ -1,11 +1,14 @@ dm->flush(); $this->dm->clear(); - $document = $this->dm->find(__NAMESPACE__.'\GH561Document', $document->id); - $this->assertInstanceOf(__NAMESPACE__.'\GH561Document', $document); + $document = $this->dm->find(__NAMESPACE__ . '\GH561Document', $document->id); + $this->assertInstanceOf(__NAMESPACE__ . '\GH561Document', $document); $this->assertCount(1, $document->embeddedDocuments); $embeddedDocument = $document->embeddedDocuments->first(); - $this->assertInstanceOf(__NAMESPACE__.'\GH561EmbeddedDocument', $embeddedDocument); + $this->assertInstanceOf(__NAMESPACE__ . '\GH561EmbeddedDocument', $embeddedDocument); $this->assertCount(1, $embeddedDocument->embeddedDocuments); $anotherEmbeddedDocument = $embeddedDocument->embeddedDocuments->first(); - $this->assertInstanceOf(__NAMESPACE__.'\GH561AnotherEmbeddedDocument', $anotherEmbeddedDocument); + $this->assertInstanceOf(__NAMESPACE__ . '\GH561AnotherEmbeddedDocument', $anotherEmbeddedDocument); $this->assertEquals('foo', $anotherEmbeddedDocument->name); } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH566Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH566Test.php index 0b46660fdc..a2ba55c071 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH566Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH566Test.php @@ -1,11 +1,15 @@ parent = $doc2; $doc3->version = $embeddedDoc2; - $doc3->versions = new ArrayCollection(array( + $doc3->versions = new ArrayCollection([ $embeddedDoc1, $embeddedDoc2, - )); + ]); $this->dm->flush(); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH580Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH580Test.php index c1aa60114e..880cc14aac 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH580Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH580Test.php @@ -1,11 +1,14 @@ assertFalse($user1following[1]->__isInitialized()); $this->assertEquals($user3->getId(), $user1following[1]->getId()); - try { - $user1following[1]->__load(); - $this->fail('Expected DocumentNotFoundException for filtered Proxy object'); - } catch (DocumentNotFoundException $e) { - } + $this->expectException(DocumentNotFoundException::class); + $user1following[1]->__load(); } public function testReferenceManyInverseSidePreparesFilterCriteria() diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH596Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH596Test.php index 38e193c581..5685f9f7b5 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH596Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH596Test.php @@ -1,10 +1,13 @@ getQuery(); $query = $query->getQuery(); - $expected = array('$and' => array( - array('$or' => array( - array('name' => 'foo'), - array('name' => 'bar'), - )), - array('deleted' => false), - )); + $expected = [ + '$and' => [ + [ + '$or' => [ + ['name' => 'foo'], + ['name' => 'bar'], + ], + ], + ['deleted' => false], + ], + ]; $this->assertEquals($expected, $query['query']); } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH597Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH597Test.php index 21c90b7267..fc28e76af4 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH597Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH597Test.php @@ -1,11 +1,15 @@ dm->clear(); // default behavior on inserts already leaves out embedded documents - $expectedDocument = array('_id' => new \MongoDB\BSON\ObjectId($post->getId())); + $expectedDocument = ['_id' => new ObjectId($post->getId())]; $this->assertPostDocument($expectedDocument, $post); // fill documents with comments $post = $this->dm->find(__NAMESPACE__ . '\GH597Post', $post->getId()); - $post->comments = new ArrayCollection(array( + $post->comments = new ArrayCollection([ new GH597Comment('Comment 1'), new GH597Comment('Comment 2'), - new GH597Comment('Comment 3') - )); + new GH597Comment('Comment 3'), + ]); $this->dm->persist($post); $this->dm->flush(); $this->dm->clear(); - $expectedDocument = array( - '_id' => new \MongoDB\BSON\ObjectId($post->getId()), - 'comments' => array( - array('comment' => 'Comment 1'), - array('comment' => 'Comment 2'), - array('comment' => 'Comment 3') - ) - ); + $expectedDocument = [ + '_id' => new ObjectId($post->getId()), + 'comments' => [ + ['comment' => 'Comment 1'], + ['comment' => 'Comment 2'], + ['comment' => 'Comment 3'], + ], + ]; $this->assertPostDocument($expectedDocument, $post); // trigger update @@ -50,7 +54,7 @@ public function testEmbedManyGetsUnset() $this->assertCount(0, $post->getComments()); // make sure embedded documents got unset - $expectedDocument = array('_id' => new \MongoDB\BSON\ObjectId($post->getId())); + $expectedDocument = ['_id' => new ObjectId($post->getId())]; $this->assertPostDocument($expectedDocument, $post); } @@ -62,7 +66,7 @@ public function testReferenceManyGetsUnset() $this->dm->clear(); // default behavior on inserts already leaves out referenced documents - $expectedDocument = array('_id' => new \MongoDB\BSON\ObjectId($post->getId())); + $expectedDocument = ['_id' => new ObjectId($post->getId())]; $this->assertPostDocument($expectedDocument, $post); // associate post with many GH597ReferenceMany documents @@ -73,18 +77,18 @@ public function testReferenceManyGetsUnset() $referenceMany2 = new GH597ReferenceMany('two'); $this->dm->persist($referenceMany2); - $post->referenceMany = new ArrayCollection(array($referenceMany1, $referenceMany2)); + $post->referenceMany = new ArrayCollection([$referenceMany1, $referenceMany2]); $this->dm->persist($post); $this->dm->flush(); $this->dm->clear(); - $expectedDocument = array( - '_id' => new \MongoDB\BSON\ObjectId($post->getId()), - 'referenceMany' => array( - new \MongoDB\BSON\ObjectId($referenceMany1->getId()), - new \MongoDB\BSON\ObjectId($referenceMany2->getId()) - ) - ); + $expectedDocument = [ + '_id' => new ObjectId($post->getId()), + 'referenceMany' => [ + new ObjectId($referenceMany1->getId()), + new ObjectId($referenceMany2->getId()), + ], + ]; $this->assertPostDocument($expectedDocument, $post); // trigger update @@ -98,7 +102,7 @@ public function testReferenceManyGetsUnset() $this->assertCount(0, $post->getReferenceMany()); // make sure reference-many documents got unset - $expectedDocument = array('_id' => new \MongoDB\BSON\ObjectId($post->getId())); + $expectedDocument = ['_id' => new ObjectId($post->getId())]; $this->assertPostDocument($expectedDocument, $post); } @@ -106,12 +110,11 @@ public function testReferenceManyGetsUnset() * Asserts that raw document matches expected document. * * @param array $expected - * @param GH597Post $post */ private function assertPostDocument(array $expected, GH597Post $post) { $collection = $this->dm->getDocumentCollection(__NAMESPACE__ . '\GH597Post'); - $document = $collection->findOne(array('_id' => new \MongoDB\BSON\ObjectId($post->getId()))); + $document = $collection->findOne(['_id' => new ObjectId($post->getId())]); $this->assertEquals($expected, $document); } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH602Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH602Test.php index 446b2ed877..531d75c828 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH602Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH602Test.php @@ -1,12 +1,16 @@ assertFalse($user1likes[1]->__isInitialized()); $this->assertEquals($thing2->getId(), $user1likes[1]->getId()); - try { - $user1likes[1]->__load(); - $this->fail('Expected DocumentNotFoundException for filtered Proxy object'); - } catch (DocumentNotFoundException $e) { - } + $this->expectException(DocumentNotFoundException::class); + $user1likes[1]->__load(); } public function testReferenceManyInverseSidePreparesFilterCriteriaForDifferentClass() diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH611Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH611Test.php index 500507e1d6..651d4f0486 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH611Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH611Test.php @@ -1,14 +1,17 @@ id = $documentId; @@ -67,7 +70,7 @@ public function testPreparationofEmbeddedDocumentValues() ->updateOne() ->field('id')->equals($documentId) ->field('embedded._id')->exists(false) - ->field('embedded')->set(array('id' => 5, 'n' => 'c')) + ->field('embedded')->set(['id' => 5, 'n' => 'c']) ->getQuery() ->execute(); @@ -84,7 +87,7 @@ public function testPreparationofEmbeddedDocumentValues() ->updateOne() ->field('id')->equals($documentId) ->field('embedded._id')->exists(false) - ->field('embedded')->set((object) array('id' => 6, 'n' => 'd')) + ->field('embedded')->set((object) ['id' => 6, 'n' => 'd']) ->getQuery() ->execute(); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH628Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH628Test.php index 386f6d505e..1c9bec811e 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH628Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH628Test.php @@ -1,5 +1,7 @@ getQuery() ->getQuery(); - $expected = array('f.bar.baz' => 1); + $expected = ['f.bar.baz' => 1]; $this->assertEquals($expected, $query['query']); } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH665Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH665Test.php index a6907ae883..ac9a5c91de 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH665Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH665Test.php @@ -1,11 +1,14 @@ dm->clear(); $check = $this->dm->getDocumentCollection(__NAMESPACE__ . '\GH665Document') - ->findOne(array('embeddedPushAll.name' => 'foo')); + ->findOne(['embeddedPushAll.name' => 'foo']); $this->assertNotNull($check); $this->assertSame($document->id, (string) $check['_id']); $check = $this->dm->getDocumentCollection(__NAMESPACE__ . '\GH665Document') - ->findOne(array('embeddedAddToSet.name' => 'bar')); + ->findOne(['embeddedAddToSet.name' => 'bar']); $this->assertNotNull($check); $this->assertSame($document->id, (string) $check['_id']); @@ -33,11 +36,11 @@ public function testUseAddToSetStrategyOnEmbeddedDocument() ->getQuery() ->getSingleResult(); - $expected = array( + $expected = [ '_id' => $document->id, - 'embeddedPushAll' => array(array('name' => 'foo')), - 'embeddedAddToSet' => array(array('name' => 'bar')) - ); + 'embeddedPushAll' => [['name' => 'foo']], + 'embeddedAddToSet' => [['name' => 'bar']], + ]; $this->assertEquals($expected, $persisted); } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH683Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH683Test.php index 85e2aa8eec..9b451bff49 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH683Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH683Test.php @@ -1,14 +1,15 @@ name = 'Parent'; - + $sub1 = new EmbeddedSubDocument1(); $sub1->name = 'Sub 1'; - + $parent->embedOne = $sub1; $this->dm->persist($parent); $this->dm->flush(); $this->dm->clear(); - + $id = $parent->id; $parent = $this->dm->find(get_class($parent), $id); @@ -36,13 +37,13 @@ public function testEmbedMany() { $parent = new ParentDocument(); $parent->name = 'Parent'; - + $sub1 = new EmbeddedSubDocument1(); $sub1->name = 'Sub 1'; - + $sub2 = new EmbeddedSubDocument2(); $sub2->name = 'Sub 2'; - + $parent->embedMany = new ArrayCollection(); $parent->embedMany->add($sub1); $parent->embedMany->add($sub2); @@ -50,7 +51,7 @@ public function testEmbedMany() $this->dm->persist($parent); $this->dm->flush(); $this->dm->clear(); - + $id = $parent->id; $parent = $this->dm->find(get_class($parent), $id); @@ -59,5 +60,4 @@ public function testEmbedMany() $this->assertInstanceOf(get_class($sub1), $firstSub); $this->assertInstanceOf(get_class($sub2), $secondSub); } - -} \ No newline at end of file +} diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH774Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH774Test.php index a799817f95..cbd28dc52c 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH774Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH774Test.php @@ -1,15 +1,18 @@ id = $id; diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH788Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH788Test.php index e5e24b41ea..bfd9bd6e36 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH788Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH788Test.php @@ -1,9 +1,12 @@ dm->clear(); $doc = $this->dm->find(get_class($listed), $listed->id); - $this->assertInstanceOf(__NAMESPACE__.'\GH788DocumentListed', $doc); + $this->assertInstanceOf(__NAMESPACE__ . '\GH788DocumentListed', $doc); $this->assertEquals('listed', $doc->name); $doc = $this->dm->find(get_class($unlisted), $unlisted->id); - $this->assertInstanceOf(__NAMESPACE__.'\GH788DocumentUnlisted', $doc); + $this->assertInstanceOf(__NAMESPACE__ . '\GH788DocumentUnlisted', $doc); $this->assertEquals('unlisted', $doc->name); /* Attempting to find the unlisted class by the parent class will not @@ -57,9 +60,9 @@ public function testEmbedManyWithExternalDiscriminatorMap() $collection = $doc->externEmbedMany; $this->assertCount(2, $collection); - $this->assertInstanceOf(__NAMESPACE__.'\GH788ExternEmbedListed', $collection[0]); + $this->assertInstanceOf(__NAMESPACE__ . '\GH788ExternEmbedListed', $collection[0]); $this->assertEquals('listed', $collection[0]->name); - $this->assertInstanceOf(__NAMESPACE__.'\GH788ExternEmbedUnlisted', $collection[1]); + $this->assertInstanceOf(__NAMESPACE__ . '\GH788ExternEmbedUnlisted', $collection[1]); $this->assertEquals('unlisted', $collection[1]->name); } @@ -83,9 +86,9 @@ public function testEmbedManyWithInlineDiscriminatorMap() $collection = $doc->inlineEmbedMany; $this->assertCount(2, $collection); - $this->assertInstanceOf(__NAMESPACE__.'\GH788InlineEmbedListed', $collection[0]); + $this->assertInstanceOf(__NAMESPACE__ . '\GH788InlineEmbedListed', $collection[0]); $this->assertEquals('listed', $collection[0]->name); - $this->assertInstanceOf(__NAMESPACE__.'\GH788InlineEmbedUnlisted', $collection[1]); + $this->assertInstanceOf(__NAMESPACE__ . '\GH788InlineEmbedUnlisted', $collection[1]); $this->assertEquals('unlisted', $collection[1]->name); } @@ -109,9 +112,9 @@ public function testEmbedManyWithNoTargetAndExternalDiscriminatorMap() $collection = $doc->noTargetEmbedMany; $this->assertCount(2, $collection); - $this->assertInstanceOf(__NAMESPACE__.'\GH788ExternEmbedListed', $collection[0]); + $this->assertInstanceOf(__NAMESPACE__ . '\GH788ExternEmbedListed', $collection[0]); $this->assertEquals('listed', $collection[0]->name); - $this->assertInstanceOf(__NAMESPACE__.'\GH788ExternEmbedUnlisted', $collection[1]); + $this->assertInstanceOf(__NAMESPACE__ . '\GH788ExternEmbedUnlisted', $collection[1]); $this->assertEquals('unlisted', $collection[1]->name); } @@ -129,7 +132,7 @@ public function testEmbedOneWithExternalDiscriminatorMap() $doc = $this->dm->find(get_class($doc), $doc->id); - $this->assertInstanceOf(__NAMESPACE__.'\GH788ExternEmbedUnlisted', $doc->externEmbedOne); + $this->assertInstanceOf(__NAMESPACE__ . '\GH788ExternEmbedUnlisted', $doc->externEmbedOne); $this->assertEquals('unlisted', $doc->externEmbedOne->name); } @@ -147,7 +150,7 @@ public function testEmbedOneWithInlineDiscriminatorMap() $doc = $this->dm->find(get_class($doc), $doc->id); - $this->assertInstanceOf(__NAMESPACE__.'\GH788InlineEmbedUnlisted', $doc->inlineEmbedOne); + $this->assertInstanceOf(__NAMESPACE__ . '\GH788InlineEmbedUnlisted', $doc->inlineEmbedOne); $this->assertEquals('unlisted', $doc->inlineEmbedOne->name); } @@ -165,7 +168,7 @@ public function testEmbedOneWithNoTargetAndExternalDiscriminatorMap() $doc = $this->dm->find(get_class($doc), $doc->id); - $this->assertInstanceOf(__NAMESPACE__.'\GH788ExternEmbedUnlisted', $doc->noTargetEmbedOne); + $this->assertInstanceOf(__NAMESPACE__ . '\GH788ExternEmbedUnlisted', $doc->noTargetEmbedOne); $this->assertEquals('unlisted', $doc->noTargetEmbedOne->name); } @@ -189,10 +192,10 @@ public function testRefManyWithExternalDiscriminatorMap() $collection = $doc->externRefMany; $this->assertCount(2, $collection); - $this->assertInstanceOf(__NAMESPACE__.'\GH788ExternRefListed', $collection[0]); + $this->assertInstanceOf(__NAMESPACE__ . '\GH788ExternRefListed', $collection[0]); $this->assertEquals($listed->id, $collection[0]->id); $this->assertEquals('listed', $collection[0]->name); - $this->assertInstanceOf(__NAMESPACE__.'\GH788ExternRefUnlisted', $collection[1]); + $this->assertInstanceOf(__NAMESPACE__ . '\GH788ExternRefUnlisted', $collection[1]); $this->assertEquals($unlisted->id, $collection[1]->id); $this->assertEquals('unlisted', $collection[1]->name); } @@ -217,10 +220,10 @@ public function testRefManyWithInlineDiscriminatorMap() $collection = $doc->inlineRefMany; $this->assertCount(2, $collection); - $this->assertInstanceOf(__NAMESPACE__.'\GH788InlineRefListed', $collection[0]); + $this->assertInstanceOf(__NAMESPACE__ . '\GH788InlineRefListed', $collection[0]); $this->assertEquals($listed->id, $collection[0]->id); $this->assertEquals('listed', $collection[0]->name); - $this->assertInstanceOf(__NAMESPACE__.'\GH788InlineRefUnlisted', $collection[1]); + $this->assertInstanceOf(__NAMESPACE__ . '\GH788InlineRefUnlisted', $collection[1]); $this->assertEquals($unlisted->id, $collection[1]->id); $this->assertEquals('unlisted', $collection[1]->name); } @@ -245,10 +248,10 @@ public function testRefManyWithNoTargetAndExternalDiscriminatorMap() $collection = $doc->noTargetRefMany; $this->assertCount(2, $collection); - $this->assertInstanceOf(__NAMESPACE__.'\GH788ExternRefListed', $collection[0]); + $this->assertInstanceOf(__NAMESPACE__ . '\GH788ExternRefListed', $collection[0]); $this->assertEquals($listed->id, $collection[0]->id); $this->assertEquals('listed', $collection[0]->name); - $this->assertInstanceOf(__NAMESPACE__.'\GH788ExternRefUnlisted', $collection[1]); + $this->assertInstanceOf(__NAMESPACE__ . '\GH788ExternRefUnlisted', $collection[1]); $this->assertEquals($unlisted->id, $collection[1]->id); $this->assertEquals('unlisted', $collection[1]->name); } @@ -267,7 +270,7 @@ public function testRefOneWithExternalDiscriminatorMap() $doc = $this->dm->find(get_class($doc), $doc->id); - $this->assertInstanceOf(__NAMESPACE__.'\GH788ExternRefUnlisted', $doc->externRefOne); + $this->assertInstanceOf(__NAMESPACE__ . '\GH788ExternRefUnlisted', $doc->externRefOne); $this->assertEquals($unlisted->id, $doc->externRefOne->id); $this->assertEquals('unlisted', $doc->externRefOne->name); } @@ -286,7 +289,7 @@ public function testRefOneWithInlineDiscriminatorMap() $doc = $this->dm->find(get_class($doc), $doc->id); - $this->assertInstanceOf(__NAMESPACE__.'\GH788InlineRefUnlisted', $doc->inlineRefOne); + $this->assertInstanceOf(__NAMESPACE__ . '\GH788InlineRefUnlisted', $doc->inlineRefOne); $this->assertEquals($unlisted->id, $doc->inlineRefOne->id); $this->assertEquals('unlisted', $doc->inlineRefOne->name); } @@ -305,7 +308,7 @@ public function testRefOneWithNoTargetAndExternalDiscriminatorMap() $doc = $this->dm->find(get_class($doc), $doc->id); - $this->assertInstanceOf(__NAMESPACE__.'\GH788ExternRefUnlisted', $doc->noTargetRefOne); + $this->assertInstanceOf(__NAMESPACE__ . '\GH788ExternRefUnlisted', $doc->noTargetRefOne); $this->assertEquals($unlisted->id, $doc->noTargetRefOne->id); $this->assertEquals('unlisted', $doc->noTargetRefOne->name); } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH816Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH816Test.php index 0adea98af6..19d0fa85c1 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH816Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH816Test.php @@ -1,15 +1,18 @@ _id=new \MongoDB\BSON\ObjectId(); + $d->_id=new ObjectId(); $this->assertEmpty($this->dm->getRepository('Doctrine\ODM\MongoDB\Tests\GH816Document')->findAll()); $this->dm->persist($d); $this->dm->detach($d); @@ -20,7 +23,7 @@ public function testPersistAfterDetachWithIdSet() public function testPersistAfterDetachWithTitleSet() { $d=new GH816Document(); - $d->title="Test"; + $d->title='Test'; $this->assertEmpty($this->dm->getRepository('Doctrine\ODM\MongoDB\Tests\GH816Document')->findAll()); $this->dm->persist($d); $this->dm->detach($d); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH850Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH850Test.php index 2356618278..9eaf329ca4 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH850Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH850Test.php @@ -1,10 +1,13 @@ dm->clear(); $docs = $this->dm->getRepository(get_class($parent)) - ->matching(new \Doctrine\Common\Collections\Criteria()); + ->matching(new Criteria()); $this->assertCount(4, $docs); } public function provideIdGenerators() { - $binDataType = \MongoDB\BSON\Binary::TYPE_GENERIC; - - return array( - array(function($id) { return array('foo' => $id); }), - array(function($id) use ($binDataType) { return new \MongoDB\BSON\Binary($id, $binDataType); }), - ); + $binDataType = Binary::TYPE_GENERIC; + + return [ + [function ($id) { + return ['foo' => $id]; + }, + ], + [function ($id) use ($binDataType) { + return new Binary($id, $binDataType); + }, + ], + ]; } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH878Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH878Test.php index dc9fd6e25e..ca869459a3 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH878Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH878Test.php @@ -1,5 +1,7 @@ embeddedField = new GH878SubDocument(); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH880Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH880Test.php index 80ecfc4982..a2887e80c0 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH880Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH880Test.php @@ -1,14 +1,17 @@ status = $status; $this->category = $category; diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH897Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH897Test.php index 3de15b4766..94cd1bb92d 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH897Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH897Test.php @@ -1,10 +1,14 @@ dm->flush(); $this->dm->clear(); - $documentA = $this->dm->find(__NAMESPACE__.'\GH897A', $documentA->id); - $documentB = $this->dm->find(__NAMESPACE__.'\GH897B', $documentB->id); + $documentA = $this->dm->find(__NAMESPACE__ . '\GH897A', $documentA->id); + $documentB = $this->dm->find(__NAMESPACE__ . '\GH897B', $documentB->id); $documentB->refOne = $documentA; /* Necessary to inject DocumentManager since it is not currently @@ -30,7 +34,7 @@ public function testRecomputeSingleDocumentChangesetForManagedDocumentWithoutCha $this->dm->flush(); $this->dm->clear(); - $documentA = $this->dm->find(__NAMESPACE__.'\GH897A', $documentA->id); + $documentA = $this->dm->find(__NAMESPACE__ . '\GH897A', $documentA->id); $this->assertSame('a-changed', $documentA->name); } @@ -63,7 +67,7 @@ class GH897B /** @ODM\PreFlush */ public function preFlush() { - if ( ! $this->refOne instanceof GH897A) { + if (! $this->refOne instanceof GH897A) { return; } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH909Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH909Test.php index 202fe38114..d97e8e25c9 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH909Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH909Test.php @@ -1,12 +1,15 @@ dm->flush(); $this->dm->clear(); - $user = $this->dm->getRepository(__NAMESPACE__.'\GH921User')->findOneBy(['name' => 'smith']); + $user = $this->dm->getRepository(__NAMESPACE__ . '\GH921User')->findOneBy(['name' => 'smith']); $postA = new GH921Post(); $user->addPost($postA); @@ -67,12 +70,30 @@ class GH921User /** @ODM\ReferenceMany(targetDocument="GH921Post") */ private $posts; - public function __construct() { $this->posts = new ArrayCollection(); } - public function getId() { return $this->id; } - public function getName() { return $this->name; } - public function setName($name) { $this->name = $name; } - public function addPost(GH921Post $post) { $this->posts[] = $post; } - public function getPosts() { return $this->posts; } + public function __construct() + { + $this->posts = new ArrayCollection(); + } + public function getId() + { + return $this->id; + } + public function getName() + { + return $this->name; + } + public function setName($name) + { + $this->name = $name; + } + public function addPost(GH921Post $post) + { + $this->posts[] = $post; + } + public function getPosts() + { + return $this->posts; + } } /** @ODM\Document */ @@ -84,7 +105,16 @@ class GH921Post /** @ODM\Field(type="string") */ private $name; - public function getId() { return $this->id; } - public function getName() { return $this->name; } - public function setName($name) { $this->name = $name; } + public function getId() + { + return $this->id; + } + public function getName() + { + return $this->name; + } + public function setName($name) + { + $this->name = $name; + } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH927Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH927Test.php index 73fafeba94..9fbc1b2d27 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH927Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH927Test.php @@ -1,10 +1,13 @@ dm->flush(); $this->dm->clear(); - $collection = $this->dm->getDocumentCollection(__NAMESPACE__.'\GH928Document'); + $collection = $this->dm->getDocumentCollection(__NAMESPACE__ . '\GH928Document'); $this->assertEquals(2, $collection->count()); - $qb = $this->dm->createQueryBuilder(__NAMESPACE__.'\GH928Document') + $qb = $this->dm->createQueryBuilder(__NAMESPACE__ . '\GH928Document') ->remove() ->field('id')->equals(null) ->getQuery() diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH936Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH936Test.php index 1ae46bfcd5..d8706dab7d 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH936Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH936Test.php @@ -1,12 +1,15 @@ dm->clear(); $doc = $this->dm->getDocumentCollection(GH942Document::CLASSNAME) - ->findOne(array('_id' => new \MongoDB\BSON\ObjectId($doc->id))); + ->findOne(['_id' => new ObjectId($doc->id)]); $this->assertSame('foo', $doc['name']); $this->assertSame(GH942Document::CLASSNAME, $doc['type']); @@ -35,13 +39,13 @@ public function testDiscriminatorValueUsesClassNameIfNotInMap() $this->dm->clear(); $parent = $this->dm->getDocumentCollection(GH942DocumentParent::CLASSNAME) - ->findOne(array('_id' => new \MongoDB\BSON\ObjectId($parent->id))); + ->findOne(['_id' => new ObjectId($parent->id)]); $this->assertSame('parent', $parent['name']); $this->assertSame('p', $parent['type']); $child = $this->dm->getDocumentCollection(GH942DocumentChild::CLASSNAME) - ->findOne(array('_id' => new \MongoDB\BSON\ObjectId($child->id))); + ->findOne(['_id' => new ObjectId($child->id)]); $this->assertSame('child', $child['name']); $this->assertSame(GH942DocumentChild::CLASSNAME, $child['type']); @@ -55,7 +59,7 @@ public function testDiscriminatorValueUsesClassNameIfNotInMap() */ class GH942Document { - const CLASSNAME = __CLASS__; + public const CLASSNAME = __CLASS__; /** @ODM\Id */ public $id; @@ -72,7 +76,7 @@ class GH942Document */ class GH942DocumentParent { - const CLASSNAME = __CLASS__; + public const CLASSNAME = __CLASS__; /** @ODM\Id */ public $id; @@ -84,5 +88,5 @@ class GH942DocumentParent /** @ODM\Document */ class GH942DocumentChild extends GH942DocumentParent { - const CLASSNAME = __CLASS__; + public const CLASSNAME = __CLASS__; } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH944Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH944Test.php index 2fd3f7a6fe..d2ebb8be9c 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH944Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH944Test.php @@ -1,11 +1,15 @@ dm->createQueryBuilder(__NAMESPACE__ . '\Car') @@ -46,8 +48,8 @@ public function testUpsertThrowsExceptionWithIndecisiveDiscriminator() $this->dm->createQueryBuilder(__NAMESPACE__ . '\Bicycle') ->findAndUpdate() ->upsert(true) - ->field('name')->equals("Cool") - ->field('features')->push("2 people") + ->field('name')->equals('Cool') + ->field('features')->push('2 people') ->getQuery()->execute(); } @@ -57,8 +59,8 @@ public function testUpsertWillUseProvidedDiscriminator() ->findAndUpdate() ->upsert(true) ->field('type')->equals('tandem') - ->field('name')->equals("Cool") - ->field('features')->push("2 people") + ->field('name')->equals('Cool') + ->field('features')->push('2 people') ->getQuery()->execute(); $results = $this->dm->getRepository(__NAMESPACE__ . '\Tandem')->findAll(); @@ -87,14 +89,20 @@ class Vehicle /** * @ODM\Document */ -class Car extends Vehicle {} +class Car extends Vehicle +{ +} /** * @ODM\Document */ -class Bicycle extends Vehicle {} +class Bicycle extends Vehicle +{ +} /** * @ODM\Document */ -class Tandem extends Bicycle {} +class Tandem extends Bicycle +{ +} diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH977Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH977Test.php index a3605703dd..8b00277a27 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH977Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH977Test.php @@ -1,51 +1,54 @@ value1 = "Value 1"; + $d->value1 = 'Value 1'; $this->dm->persist($d); $this->dm->flush(); $this->dm->clear(); - $d = $this->dm->getRepository(get_class($d))->findOneBy(['value1' => "Value 1"]); - $d->value1 = "Changed"; + $d = $this->dm->getRepository(get_class($d))->findOneBy(['value1' => 'Value 1']); + $d->value1 = 'Changed'; $this->uow->computeChangeSet($this->dm->getClassMetadata(get_class($d)), $d); $changeSet = $this->uow->getDocumentChangeSet($d); if (isset($changeSet['value1'])) { - $d->value2 = "v1 has changed"; + $d->value2 = 'v1 has changed'; } $this->dm->flush(); $this->dm->clear(); - - $d = $this->dm->getRepository(get_class($d))->findOneBy(['value1' => "Changed"]); + + $d = $this->dm->getRepository(get_class($d))->findOneBy(['value1' => 'Changed']); $this->assertNotNull($d); - $this->assertEquals("v1 has changed", $d->value2); + $this->assertEquals('v1 has changed', $d->value2); } public function testRefreshClearsChangeSet() { $d = new GH977TestDocument(); - $d->value1 = "Value 1"; + $d->value1 = 'Value 1'; $this->dm->persist($d); $this->dm->flush(); $this->dm->clear(); - $d = $this->dm->getRepository(get_class($d))->findOneBy(['value1' => "Value 1"]); - $d->value1 = "Changed"; + $d = $this->dm->getRepository(get_class($d))->findOneBy(['value1' => 'Value 1']); + $d->value1 = 'Changed'; $this->uow->computeChangeSet($this->dm->getClassMetadata(get_class($d)), $d); $this->dm->refresh($d); $this->dm->flush(); $this->dm->clear(); - $d = $this->dm->getRepository(get_class($d))->findOneBy(['value1' => "Value 1"]); + $d = $this->dm->getRepository(get_class($d))->findOneBy(['value1' => 'Value 1']); $this->assertNotNull($d); } } @@ -62,4 +65,3 @@ class GH977TestDocument /** @ODM\Field(type="string") */ public $value2; } - diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH978Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH978Test.php index 536008f6b6..6e9a2f8aaa 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH978Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH978Test.php @@ -1,6 +1,10 @@ dm->getEventManager()->addEventListener(array(Events::onFlush), new GH999Listener()); + $this->dm->getEventManager()->addEventListener([Events::onFlush], new GH999Listener()); $document = new GH999Document('name'); $this->dm->persist($document); @@ -26,7 +29,8 @@ public function testModifyingInFlushHandler() class GH999Listener { - public function onFlush(OnFlushEventArgs $args) { + public function onFlush(OnFlushEventArgs $args) + { $dm = $args->getDocumentManager(); foreach ($dm->getUnitOfWork()->getScheduledDocumentInsertions() as $document) { @@ -72,4 +76,3 @@ public function postUpdate() throw new \Exception('Did not expect postUpdate to be called when persisting a new document'); } } - diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM116Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM116Test.php index f0938972fb..45609a0df8 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM116Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM116Test.php @@ -1,10 +1,15 @@ {'_'.$name}; + return $this->{'_' . $name}; } public function __set($name, $value) { - $this->{'_'.$name} = $value; + $this->{'_' . $name} = $value; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM140Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM140Test.php index 549a90713e..79ddb27fe8 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM140Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM140Test.php @@ -1,23 +1,24 @@ name = "My Category"; + $category = new Category(); + $category->name = 'My Category'; - $post1 = new Post; + $post1 = new Post(); $post1->versions->add(new PostVersion('P1V1')); $post1->versions->add(new PostVersion('P1V2')); @@ -28,7 +29,7 @@ public function testInsertingNestedEmbeddedCollections() $this->dm->clear(); $category = $this->dm->getRepository(__NAMESPACE__ . '\Category')->findOneBy(['name' => 'My Category']); - $post2 = new Post; + $post2 = new Post(); $post2->versions->add(new PostVersion('P2V1')); $post2->versions->add(new PostVersion('P2V2')); $category->posts->add($post2); @@ -51,7 +52,7 @@ public function testInsertingEmbeddedCollectionWithRefMany() $post->comments[] = $comment; $category = new Category(); - $category->name = "My Category"; + $category->name = 'My Category'; $category->posts->add($post); $this->dm->persist($comment); @@ -74,18 +75,18 @@ public function testAddingAnotherEmbeddedDocument() $this->dm->flush(); $this->dm->clear(); - $test = $this->dm->getRepository('Documents\Functional\EmbeddedTestLevel0')->findOneBy(array('name' => 'test')); + $test = $this->dm->getRepository('Documents\Functional\EmbeddedTestLevel0')->findOneBy(['name' => 'test']); $this->assertInstanceOf('Documents\Functional\EmbeddedTestLevel0', $test); $level1 = new EmbeddedTestLevel1(); - $level1->name = "test level 1 #1"; + $level1->name = 'test level 1 #1'; $level2 = new EmbeddedTestLevel2(); - $level2->name = "test level 2 #1 in level 1 #1"; + $level2->name = 'test level 2 #1 in level 1 #1'; $level1->level2[] = $level2; $level2 = new EmbeddedTestLevel2(); - $level2->name = "test level 2 #2 in level 1 #1"; + $level2->name = 'test level 2 #2 in level 1 #1'; $level1->level2[] = $level2; $test->level1[] = $level1; @@ -93,19 +94,19 @@ public function testAddingAnotherEmbeddedDocument() $this->dm->flush(); $this->dm->clear(); - $test = $this->dm->getRepository('Documents\Functional\EmbeddedTestLevel0')->findOneBy(array('name' => 'test')); + $test = $this->dm->getRepository('Documents\Functional\EmbeddedTestLevel0')->findOneBy(['name' => 'test']); $this->assertCount(1, $test->level1); $this->assertCount(2, $test->level1[0]->level2); $level1 = new EmbeddedTestLevel1(); - $level1->name = "test level 1 #2"; + $level1->name = 'test level 1 #2'; $level2 = new EmbeddedTestLevel2(); - $level2->name = "test level 2 #1 in level 1 #2"; + $level2->name = 'test level 2 #1 in level 1 #2'; $level1->level2[] = $level2; $level2 = new EmbeddedTestLevel2(); - $level2->name = "test level 2 #2 in level 1 #2"; + $level2->name = 'test level 2 #2 in level 1 #2'; $level1->level2[] = $level2; $test->level1[] = $level1; @@ -113,69 +114,65 @@ public function testAddingAnotherEmbeddedDocument() $this->dm->flush(); $this->dm->clear(); - $test = $this->dm->getRepository('Documents\Functional\EmbeddedTestLevel0')->findOneBy(array('name' => 'test')); + $test = $this->dm->getRepository('Documents\Functional\EmbeddedTestLevel0')->findOneBy(['name' => 'test']); $this->assertCount(2, $test->level1); $this->assertCount(2, $test->level1[0]->level2); $this->assertCount(2, $test->level1[1]->level2); } - } /** @ODM\Document */ class Category { - /** @ODM\Id */ - protected $id; - - /** @ODM\Field(type="string") */ - public $name; + /** @ODM\Id */ + protected $id; - /** @ODM\EmbedMany(targetDocument="Post") */ - public $posts; + /** @ODM\Field(type="string") */ + public $name; - public function __construct() - { - $this->posts = new ArrayCollection(); - } + /** @ODM\EmbedMany(targetDocument="Post") */ + public $posts; + public function __construct() + { + $this->posts = new ArrayCollection(); + } } /** @ODM\EmbeddedDocument */ class Post { - /** @ODM\EmbedMany(targetDocument="PostVersion") */ - public $versions; + /** @ODM\EmbedMany(targetDocument="PostVersion") */ + public $versions; - /** @ODM\ReferenceMany(targetDocument="Comment") */ - public $comments; - - public function __construct() - { - $this->versions = new ArrayCollection(); - $this->comments = new ArrayCollection(); - } + /** @ODM\ReferenceMany(targetDocument="Comment") */ + public $comments; + public function __construct() + { + $this->versions = new ArrayCollection(); + $this->comments = new ArrayCollection(); + } } /** @ODM\EmbeddedDocument */ class PostVersion { - /** @ODM\Field(type="string") */ - public $name; - - public function __construct($name) - { - $this->name = $name; - } + /** @ODM\Field(type="string") */ + public $name; + public function __construct($name) + { + $this->name = $name; + } } /** @ODM\Document */ class Comment { - /** @ODM\Id */ - protected $id; + /** @ODM\Id */ + protected $id; - /** @ODM\Field(type="string") */ - public $content; + /** @ODM\Field(type="string") */ + public $content; } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM160Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM160Test.php index 7d85f6183c..87ff239549 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM160Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM160Test.php @@ -1,10 +1,13 @@ dm->clear(); $repository = $this->dm->getRepository(get_class($test)); - $test = $repository->findOneBy(array('username' => 'lucy')); + $test = $repository->findOneBy(['username' => 'lucy']); - $phonenumbers = array(); - foreach ($test->getPhonenumbers() as $phonenumber){ + $phonenumbers = []; + foreach ($test->getPhonenumbers() as $phonenumber) { $phonenumbers[] = $phonenumber->getPhonenumber(); } sort($phonenumbers); - $this->assertEquals(array('1111', '2222'), $phonenumbers); + $this->assertEquals(['1111', '2222'], $phonenumbers); } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM167Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM167Test.php index ff6ed6fb5c..b52906b18b 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM167Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM167Test.php @@ -1,14 +1,17 @@ detach($document); } } -} \ No newline at end of file +} diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM29Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM29Test.php index 3c5ad796d9..8313c45f05 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM29Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM29Test.php @@ -1,18 +1,22 @@ dm->flush(); // place element '0' after '1' - $collection = new \Doctrine\Common\Collections\ArrayCollection(array( + $collection = new ArrayCollection([ $collection[1], $collection[0], - $collection[2] - )); + $collection[2], + ]); $doc->set($collection); @@ -37,11 +41,11 @@ public function testTest() $this->dm->refresh($doc); - $array = array(); - foreach($doc->get() as $value) { + $array = []; + foreach ($doc->get() as $value) { $array[] = $value->get(); } - $this->assertEquals(array('1', 'tmp', '2'), $array); + $this->assertEquals(['1', 'tmp', '2'], $array); } } @@ -54,10 +58,19 @@ class MODM29Doc /** @ODM\EmbedMany(targetDocument="MODM29Embedded", strategy="set") */ protected $collection; - function __construct($c) {$this->set($c);} + function __construct($c) + { + $this->set($c); + } - function set($c) {$this->collection = $c;} - function get() {return $this->collection;} + function set($c) + { + $this->collection = $c; + } + function get() + { + return $this->collection; + } } /** @ODM\EmbeddedDocument */ @@ -66,7 +79,16 @@ class MODM29Embedded /** @ODM\Field(type="string") */ protected $val; - function __construct($val) {$this->set($val);} - function get() {return $this->val;} - function set($val) {$this->val = $val;} + function __construct($val) + { + $this->set($val); + } + function get() + { + return $this->val; + } + function set($val) + { + $this->val = $val; + } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM43Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM43Test.php index b4618376bb..357c524700 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM43Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM43Test.php @@ -1,21 +1,25 @@ new ObjectId(), - 'name' => 'Jonathan Wage' - ); - $this->dm->getDocumentCollection(__NAMESPACE__.'\Person')->insertOne($person); - $user = $this->dm->find(__NAMESPACE__.'\Person', $person['_id']); + 'name' => 'Jonathan Wage', + ]; + $this->dm->getDocumentCollection(__NAMESPACE__ . '\Person')->insertOne($person); + $user = $this->dm->find(__NAMESPACE__ . '\Person', $person['_id']); $this->assertEquals('Jonathan', $user->firstName); $this->assertEquals('Wage', $user->lastName); } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM45Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM45Test.php index 35922b4476..4ba40696e2 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM45Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM45Test.php @@ -1,10 +1,13 @@ dm->flush(); $this->dm->clear(); - $a = $this->dm->find(__NAMESPACE__.'\MODM45A', $a->getId()); - $c = (null !== $a->getB()); + $a = $this->dm->find(__NAMESPACE__ . '\MODM45A', $a->getId()); + $c = ($a->getB() !== null); $this->assertTrue($c); // returns false, while expecting true } } @@ -30,9 +33,18 @@ class MODM45A /** @ODM\EmbedOne(targetDocument="MODM45B") */ protected $b; - function getId() {return $this->id;} - function getB() {return $this->b;} - function setB($b) {$this->b = $b;} + function getId() + { + return $this->id; + } + function getB() + { + return $this->b; + } + function setB($b) + { + $this->b = $b; + } } /** @ODM\EmbeddedDocument */ @@ -40,6 +52,12 @@ class MODM45B { /** @ODM\Field(type="string") */ protected $val; - function setVal($val) {$this->val = $val;} - function getVal() {return $this->val;} + function setVal($val) + { + $this->val = $val; + } + function getVal() + { + return $this->val; + } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM46Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM46Test.php index eb79755d58..0a18deb2c7 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM46Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM46Test.php @@ -1,21 +1,24 @@ new ObjectId(), - 'c' => array('value' => 'value') - ); - $this->dm->getDocumentCollection(__NAMESPACE__.'\MODM46A')->insertOne($a); + 'c' => ['value' => 'value'], + ]; + $this->dm->getDocumentCollection(__NAMESPACE__ . '\MODM46A')->insertOne($a); - $a = $this->dm->find(__NAMESPACE__.'\MODM46A', $a['_id']); + $a = $this->dm->find(__NAMESPACE__ . '\MODM46A', $a['_id']); $this->assertTrue(isset($a->b)); $this->assertEquals('value', $a->b->value); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM47Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM47Test.php index a558968e9d..e891b8b74c 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM47Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM47Test.php @@ -1,21 +1,24 @@ new ObjectId(), - 'c' => 'c value' - ); - $this->dm->getDocumentCollection(__NAMESPACE__.'\MODM47A')->insertOne($a); + 'c' => 'c value', + ]; + $this->dm->getDocumentCollection(__NAMESPACE__ . '\MODM47A')->insertOne($a); - $a = $this->dm->find(__NAMESPACE__.'\MODM47A', $a['_id']); + $a = $this->dm->find(__NAMESPACE__ . '\MODM47A', $a['_id']); $this->assertEquals('c value', $a->b); } } @@ -30,6 +33,12 @@ class MODM47A public $b = 'tmp'; /** @ODM\AlsoLoad("c") */ - function renameC($c) {$this->b = $c;} - function getId() {return $this->id;} + function renameC($c) + { + $this->b = $c; + } + function getId() + { + return $this->id; + } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM48Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM48Test.php index e222896a6d..438fe03b63 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM48Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM48Test.php @@ -1,10 +1,13 @@ dm->flush(); $this->dm->clear(); - $a = $this->dm->find(__NAMESPACE__.'\MODM48A', $a->id); + $a = $this->dm->find(__NAMESPACE__ . '\MODM48A', $a->id); $this->assertNotNull($a); $a->getB()->setVal('test'); @@ -22,7 +25,7 @@ public function testTest() $this->dm->flush(); $this->dm->clear(); - $a = $this->dm->find(__NAMESPACE__.'\MODM48A', $a->id); + $a = $this->dm->find(__NAMESPACE__ . '\MODM48A', $a->id); $this->assertEquals('test', $a->getB()->getVal()); } } @@ -36,9 +39,18 @@ class MODM48A /** @ODM\EmbedOne(targetDocument="MODM48B") */ public $b; - function getId() {return $this->id;} - function getB() {return $this->b;} - function setB($b) {$this->b = $b;} + function getId() + { + return $this->id; + } + function getB() + { + return $this->b; + } + function setB($b) + { + $this->b = $b; + } } /** @ODM\EmbeddedDocument */ @@ -47,6 +59,12 @@ class MODM48B /** @ODM\Field(type="string") */ public $val; - function setVal($val) {$this->val = $val;} - function getVal() {return $this->val;} + function setVal($val) + { + $this->val = $val; + } + function getVal() + { + return $this->val; + } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM52Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM52Test.php index 2e8d3194bf..865b2cb0ab 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM52Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM52Test.php @@ -1,15 +1,19 @@ dm->persist($doc); $this->dm->flush(); @@ -39,7 +43,7 @@ class MODM52Container public $value; /** @ODM\EmbedMany(targetDocument="MODM52Embedded", strategy="set") */ - public $items = array(); + public $items = []; public function __construct($items = null, $value = null) { @@ -67,7 +71,8 @@ public function removeItem($i) /** @ODM\EmbeddedDocument */ class MODM52Embedded extends MODM52Container -{} +{ +} /** @ODM\Document */ class MODM52Doc extends MODM52Container diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM56Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM56Test.php index 9bfc8a8860..70fea20874 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM56Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM56Test.php @@ -1,10 +1,14 @@ children[] = $childTwo; $this->dm->flush(); - $test = $this->dm->getDocumentCollection(__NAMESPACE__.'\MODM56Parent')->findOne(); + $test = $this->dm->getDocumentCollection(__NAMESPACE__ . '\MODM56Parent')->findOne(); $this->assertEquals('Parent', $test['name']); - $this->assertInstanceOf(\MongoDB\BSON\UTCDateTime::class, $test['updatedAt']); + $this->assertInstanceOf(UTCDateTime::class, $test['updatedAt']); $this->assertCount(2, $test['children']); $this->assertEquals('Child One', $test['children'][0]['name']); $this->assertEquals('Child Two', $test['children'][1]['name']); @@ -42,7 +46,7 @@ class MODM56Parent public $updatedAt; /** @ODM\EmbedMany(targetDocument="MODM56Child") */ - public $children = array(); + public $children = []; public function __construct($name) { diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM62Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM62Test.php index 83fd66403b..62dfebe510 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM62Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM62Test.php @@ -1,10 +1,13 @@ dm->flush(); $this->dm->refresh($test); - $test->setB(array('test', 'test2')); + $test->setB(['test', 'test2']); $this->dm->flush(); $this->dm->clear(); - $test = $this->dm->find(__NAMESPACE__.'\MODM62Document', $test->id); - $this->assertEquals(array('test', 'test2'), $test->b); + $test = $this->dm->find(__NAMESPACE__ . '\MODM62Document', $test->id); + $this->assertEquals(['test', 'test2'], $test->b); } } @@ -29,7 +32,10 @@ class MODM62Document public $id; /** @ODM\Field(type="collection") */ - public $b = array('ok'); + public $b = ['ok']; - public function setB($b) {$this->b = $b;} + public function setB($b) + { + $this->b = $b; + } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM65Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM65Test.php index c6f47c74b4..b24152fa82 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM65Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM65Test.php @@ -1,10 +1,13 @@ dm->flush(); $this->dm->clear(); - $user = $this->dm->getDocumentCollection(__NAMESPACE__.'\MODM65User')->findOne(); + $user = $this->dm->getDocumentCollection(__NAMESPACE__ . '\MODM65User')->findOne(); $this->assertTrue(isset($user['snu']['lN'])); $this->assertTrue(isset($user['snu']['fN'])); - $user = $this->dm->find(__NAMESPACE__.'\MODM65User', $user['_id']); + $user = $this->dm->find(__NAMESPACE__ . '\MODM65User', $user['_id']); $this->assertEquals('Jonathan', $user->socialNetworkUser->firstName); $this->assertEquals('Wage', $user->socialNetworkUser->lastName); } @@ -31,20 +34,20 @@ public function testTest() */ class MODM65User { - /** - * @ODM\Id - */ - public $id; - /** - * @ODM\EmbedOne( - * discriminatorField="php", - * discriminatorMap={ - * "fbu"="Doctrine\ODM\MongoDB\Tests\Functional\Ticket\MODM65SocialNetworkUser" - * }, - * name="snu" - * ) - */ - public $socialNetworkUser; + /** + * @ODM\Id + */ + public $id; + /** + * @ODM\EmbedOne( + * discriminatorField="php", + * discriminatorMap={ + * "fbu"="Doctrine\ODM\MongoDB\Tests\Functional\Ticket\MODM65SocialNetworkUser" + * }, + * name="snu" + * ) + */ + public $socialNetworkUser; } /** @@ -52,14 +55,14 @@ class MODM65User */ class MODM65SocialNetworkUser { - /** - * @ODM\Field(name="fN", type="string") - * @var string - */ - public $firstName; - /** - * @ODM\Field(name="lN", type="string") - * @var string - */ - public $lastName; + /** + * @ODM\Field(name="fN", type="string") + * @var string + */ + public $firstName; + /** + * @ODM\Field(name="lN", type="string") + * @var string + */ + public $lastName; } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM66Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM66Test.php index 60721e246a..06db0f0292 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM66Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM66Test.php @@ -1,17 +1,19 @@ dm->persist($a); $this->dm->flush(); $b2 = new MODM52B('second'); @@ -23,17 +25,19 @@ public function testTest() $this->assertCount(2, $b); - $this->assertEquals(array( - $b1->getId(), $b2->getId() - ), array( - $b[0]->getId(), $b[1]->getId() - )); + $this->assertEquals([ + $b1->getId(), + $b2->getId(), + ], [ + $b[0]->getId(), + $b[1]->getId(), + ]); } public function testRefresh() { $b1 = new MODM52B('first'); - $a = new MODM52A(array($b1)); + $a = new MODM52A([$b1]); $this->dm->persist($a); $this->dm->flush(); $b2 = new MODM52B('second'); @@ -47,13 +51,14 @@ public function testRefresh() $this->assertCount(2, $b); - $this->assertEquals(array( - $b1->getId(), $b2->getId() - ), array( - $b[0]->getId(), $b[1]->getId() - )); + $this->assertEquals([ + $b1->getId(), + $b2->getId(), + ], [ + $b[0]->getId(), + $b[1]->getId(), + ]); } - } /** @ODM\Document */ @@ -79,7 +84,6 @@ function getB() /** @ODM\Document */ class MODM52B { - /** @ODM\Id */ protected $id; @@ -95,5 +99,4 @@ public function getId() { return $this->id; } - } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM67Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM67Test.php index 12d846b8fc..76ceebf2fa 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM67Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM67Test.php @@ -1,24 +1,27 @@ listener = new MODM67TestEventListener($this->dm); $evm = $this->dm->getEventManager(); - $events = array( + $events = [ Events::prePersist, Events::postPersist, Events::preUpdate, Events::postUpdate, - ); + ]; $evm->addEventListener($events, $this->listener); return $this->dm; diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM70Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM70Test.php index 48b2eed454..4bb13d128b 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM70Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM70Test.php @@ -1,27 +1,31 @@ dm->persist($avatar); - $this->dm->flush(); - $this->dm->refresh($avatar); + $this->dm->persist($avatar); + $this->dm->flush(); + $this->dm->refresh($avatar); - $avatar->addAvatarPart(new AvatarPart('#FFF')); + $avatar->addAvatarPart(new AvatarPart('#FFF')); - $this->dm->flush(); - $this->dm->refresh($avatar); + $this->dm->flush(); + $this->dm->refresh($avatar); - $parts = $avatar->getAvatarParts(); - $this->assertCount(2, $parts); - $this->assertEquals('#FFF', $parts[1]->getColor()); + $parts = $avatar->getAvatarParts(); + $this->assertCount(2, $parts); + $this->assertEquals('#FFF', $parts[1]->getColor()); } } @@ -30,87 +34,86 @@ public function testTest() */ class Avatar { + /** + * @ODM\Id + */ + protected $id; + + /** + * @ODM\Field(name="na", type="string") + * @var string + */ + protected $name; + + /** + * @ODM\Field(name="sex", type="int") + * @var int + */ + protected $sex; + + /** + * @ODM\EmbedMany( + * targetDocument="AvatarPart", + * name="aP" + * ) + * @var array AvatarPart + */ + protected $avatarParts; + + public function __construct($name, $sex, $avatarParts = null) + { + $this->name = $name; + $this->sex = $sex; + $this->avatarParts = $avatarParts; + } + + public function getId() + { + return $this->id; + } + + public function getName() + { + return $this->name; + } + + public function setName($name) + { + $this->name = $name; + } + + public function getSex() + { + return $this->sex; + } + + public function setSex($sex) + { + $this->sex = $sex; + } + + public function getAvatarParts() + { + return $this->avatarParts; + } + + public function addAvatarPart($part) + { + $this->avatarParts[] = $part; + } - /** - * @ODM\Id - */ - protected $id; - - /** - * @ODM\Field(name="na", type="string") - * @var string - */ - protected $name; - - /** - * @ODM\Field(name="sex", type="int") - * @var int - */ - protected $sex; - - /** - * @ODM\EmbedMany( - * targetDocument="AvatarPart", - * name="aP" - * ) - * @var array AvatarPart - */ - protected $avatarParts; - - public function __construct($name, $sex, $avatarParts = null) - { - $this->name = $name; - $this->sex = $sex; - $this->avatarParts = $avatarParts; - } - - public function getId() - { - return $this->id; - } - - public function getName() - { - return $this->name; - } - - public function setName($name) - { - $this->name = $name; - } - - public function getSex() - { - return $this->sex; - } - - public function setSex($sex) - { - $this->sex = $sex; - } - - public function getAvatarParts() - { - return $this->avatarParts; - } - - public function addAvatarPart($part) - { - $this->avatarParts[] = $part; - } - - public function setAvatarParts($parts) - { - $this->avatarParts = $parts; - } - - public function removeAvatarPart($part) - { - $key = array_search($this->avatarParts, $part); - if ($key !== false) { - unset($this->avatarParts[$key]); - } - } + public function setAvatarParts($parts) + { + $this->avatarParts = $parts; + } + + public function removeAvatarPart($part) + { + $key = array_search($this->avatarParts, $part); + if ($key !== false) { + unset($this->avatarParts[$key]); + } + } } /** @@ -118,24 +121,24 @@ public function removeAvatarPart($part) */ class AvatarPart { - /** - * @ODM\Field(name="col", type="string") - * @var string - */ - protected $color; - - public function __construct($color = null) - { - $this->color = $color; - } - - public function getColor() - { - return $this->color; - } - - public function setColor($color) - { - $this->color = $color; - } + /** + * @ODM\Field(name="col", type="string") + * @var string + */ + protected $color; + + public function __construct($color = null) + { + $this->color = $color; + } + + public function getColor() + { + return $this->color; + } + + public function setColor($color) + { + $this->color = $color; + } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM72Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM72Test.php index 25a24288a6..301a0b2f09 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM72Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM72Test.php @@ -1,15 +1,18 @@ dm->getClassMetadata(__NAMESPACE__.'\MODM72User'); - $this->assertEquals(array('test' => 'test'), $class->fieldMappings['name']['options']); + $class = $this->dm->getClassMetadata(__NAMESPACE__ . '\MODM72User'); + $this->assertEquals(['test' => 'test'], $class->fieldMappings['name']['options']); } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM76Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM76Test.php index 7334acb62b..663fc5a345 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM76Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM76Test.php @@ -1,19 +1,22 @@ dm->persist($a); $this->dm->persist($b); @@ -21,7 +24,7 @@ public function testTest() $this->dm->persist($c2); $this->dm->flush(); - $this->assertTrue($a->getId() != null); + $this->assertTrue($a->getId() !== null); } } @@ -35,10 +38,10 @@ class MODM76A protected $test = 'test'; /** @ODM\EmbedMany(targetDocument="MODM76B") */ - protected $b = array(); + protected $b = []; /** @ODM\ReferenceMany(targetDocument="MODM76C") */ - protected $c = array(); + protected $c = []; public function __construct($b, $c) { diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM81Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM81Test.php index 278359aff0..d3b4aa82a9 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM81Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM81Test.php @@ -1,11 +1,14 @@ flush(); $embedded = new MODM81TestEmbeddedDocument($doc1, $doc2, 'Test1'); - $doc1->setEmbeddedDocuments(array($embedded)); - $doc2->setEmbeddedDocuments(array($embedded)); + $doc1->setEmbeddedDocuments([$embedded]); + $doc2->setEmbeddedDocuments([$embedded]); $dm->flush(); $dm->clear(); @@ -95,7 +98,7 @@ public function setName($name) } /** - * @return \Doctrine\Common\Collections\ArrayCollection + * @return ArrayCollection */ public function getEmbeddedDocuments() { @@ -109,7 +112,6 @@ public function setEmbeddedDocuments($documents) { $this->embeddedDocuments = new ArrayCollection($documents); } - } /** @ODM\EmbeddedDocument */ diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM83Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM83Test.php index 2669ee6851..727ab0c12e 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM83Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM83Test.php @@ -1,20 +1,24 @@ listener = new MODM83EventListener(); $evm = $this->dm->getEventManager(); - $events = array( + $events = [ Events::preUpdate, Events::postUpdate, - ); + ]; $evm->addEventListener($events, $this->listener); return $this->dm; } @@ -34,23 +38,23 @@ public function testDocumentWithEmbeddedDocumentNotUpdated() $dm->flush(); $dm->clear(); - $won = $dm->find(__NAMESPACE__.'\MODM83TestDocument', $won->id); - $too = $dm->find(__NAMESPACE__.'\MODM83OtherDocument', $too->id); + $won = $dm->find(__NAMESPACE__ . '\MODM83TestDocument', $won->id); + $too = $dm->find(__NAMESPACE__ . '\MODM83OtherDocument', $too->id); $too->name = 'Bob'; $dm->flush(); $dm->clear(); - $called = array( - Events::preUpdate => array(__NAMESPACE__.'\MODM83OtherDocument'), - Events::postUpdate => array(__NAMESPACE__.'\MODM83OtherDocument') - ); + $called = [ + Events::preUpdate => [__NAMESPACE__ . '\MODM83OtherDocument'], + Events::postUpdate => [__NAMESPACE__ . '\MODM83OtherDocument'], + ]; $this->assertEquals($called, $this->listener->called); } } class MODM83EventListener { - public $called = array(); + public $called = []; public function __call($method, $args) { $document = $args[0]->getDocument(); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM88Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM88Test.php index b4781b3db8..2ce8ad3e16 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM88Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM88Test.php @@ -1,12 +1,17 @@ setTitle('Test Title'); $article->setBody('Test Body'); $this->dm->persist($article); @@ -17,7 +22,7 @@ public function testTest() ->select('_id', 'title'); $q = $qb->getQuery(); $document = $q->getSingleResult(); - + $this->assertEquals('Test Title', $document->getTitle()); $this->assertNull($document->getBody()); @@ -28,4 +33,4 @@ public function testTest() $this->assertEquals('changed', $check['title']); $this->assertEquals('Test Body', $check['body']); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM90Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM90Test.php index ee0dd3fc73..2ca33005d8 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM90Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM90Test.php @@ -1,20 +1,24 @@ listener = new MODM90EventListener(); $evm = $this->dm->getEventManager(); - $events = array( + $events = [ Events::preUpdate, Events::postUpdate, - ); + ]; $evm->addEventListener($events, $this->listener); return $this->dm; } @@ -31,14 +35,14 @@ public function testDocumentWithEmbeddedDocumentNotUpdatedOnFlush() $dm->flush(); $dm->clear(); - $testDoc = $dm->find(__NAMESPACE__.'\MODM90TestDocument', $testDoc->id); + $testDoc = $dm->find(__NAMESPACE__ . '\MODM90TestDocument', $testDoc->id); // run a flush, in theory, nothing should be flushed. $dm->flush(); $dm->clear(); // no update events should be called - $called = array(); + $called = []; $this->assertEquals($called, $this->listener->called); } @@ -58,7 +62,7 @@ public function testDiscriminatorFieldValuePresentIfRealProperty() $dm->flush(); $dm->clear(); - $testDoc = $dm->find(__NAMESPACE__.'\MODM90TestDocument', $testDoc->id); + $testDoc = $dm->find(__NAMESPACE__ . '\MODM90TestDocument', $testDoc->id); $this->assertEquals($testDoc->embedded->type, 'test2'); } @@ -66,7 +70,7 @@ public function testDiscriminatorFieldValuePresentIfRealProperty() class MODM90EventListener { - public $called = array(); + public $called = []; public function __call($method, $args) { $document = $args[0]->getDocument(); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM91Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM91Test.php index 38025f2ad5..7860556aa7 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM91Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM91Test.php @@ -1,20 +1,24 @@ listener = new MODM91EventListener(); $evm = $this->dm->getEventManager(); - $events = array( + $events = [ Events::preUpdate, Events::postUpdate, - ); + ]; $evm->addEventListener($events, $this->listener); return $this->dm; } @@ -31,18 +35,18 @@ public function testDocumentWithEmbeddedDocumentNotUpdated() $dm->flush(); $dm->clear(); - $testDoc = $dm->find(__NAMESPACE__.'\MODM91TestDocument', $testDoc->id); + $testDoc = $dm->find(__NAMESPACE__ . '\MODM91TestDocument', $testDoc->id); $dm->flush(); $dm->clear(); - $called = array(); + $called = []; $this->assertEquals($called, $this->listener->called); } } class MODM91EventListener { - public $called = array(); + public $called = []; public function __call($method, $args) { $document = $args[0]->getDocument(); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM92Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM92Test.php index 5972ef1ebd..f5b5b71733 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM92Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM92Test.php @@ -1,15 +1,19 @@ setEmbeddedDocuments($embeddedDocuments); @@ -17,17 +21,17 @@ public function testDocumentWithEmbeddedDocuments() $this->dm->flush(); $this->dm->clear(); - $testDoc = $this->dm->find(__NAMESPACE__.'\MODM92TestDocument', $testDoc->id); + $testDoc = $this->dm->find(__NAMESPACE__ . '\MODM92TestDocument', $testDoc->id); $this->assertEquals($embeddedDocuments, $testDoc->embeddedDocuments->toArray()); - $embeddedDocuments = array(new MODM92TestEmbeddedDocument('bar')); + $embeddedDocuments = [new MODM92TestEmbeddedDocument('bar')]; $testDoc->setEmbeddedDocuments($embeddedDocuments); $this->assertEquals($embeddedDocuments, $testDoc->embeddedDocuments->toArray()); $this->dm->flush(); $this->dm->clear(); - $testDoc = $this->dm->find(__NAMESPACE__.'\MODM92TestDocument', $testDoc->id); + $testDoc = $this->dm->find(__NAMESPACE__ . '\MODM92TestDocument', $testDoc->id); $this->assertEquals($embeddedDocuments, $testDoc->embeddedDocuments->toArray()); } @@ -43,7 +47,8 @@ class MODM92TestDocument /** @ODM\EmbedMany(targetDocument="MODM92TestEmbeddedDocument") */ public $embeddedDocuments; - public function __construct() { + public function __construct() + { $this->embeddedDocuments = new ArrayCollection(); } @@ -58,7 +63,8 @@ public function __construct() { * * @param array|Traversable $children */ - public function setEmbeddedDocuments($embeddedDocuments) { + public function setEmbeddedDocuments($embeddedDocuments) + { $this->embeddedDocuments->clear(); if (! (is_array($embeddedDocuments) || $embeddedDocuments instanceof \Traversable)) { @@ -77,7 +83,8 @@ class MODM92TestEmbeddedDocument /** @ODM\Field(type="string") */ public $name; - public function __construct($name) { + public function __construct($name) + { $this->name = $name; } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM95Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM95Test.php index b38e52ee85..ec08cd1d32 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM95Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM95Test.php @@ -1,15 +1,19 @@ setEmbeddedDocuments($embeddedDocuments); @@ -17,7 +21,7 @@ public function testDocumentWithEmbeddedDocuments() $this->dm->flush(); $this->dm->clear(); - $testDoc = $this->dm->find(__NAMESPACE__.'\MODM95TestDocument', $testDoc->id); + $testDoc = $this->dm->find(__NAMESPACE__ . '\MODM95TestDocument', $testDoc->id); $this->assertEquals($embeddedDocuments, $testDoc->embeddedDocuments->toArray()); @@ -25,14 +29,14 @@ public function testDocumentWithEmbeddedDocuments() $this->dm->flush(); $this->dm->clear(); - $testDocLoad = $this->dm->find(__NAMESPACE__.'\MODM95TestDocument', $testDoc->id); + $testDocLoad = $this->dm->find(__NAMESPACE__ . '\MODM95TestDocument', $testDoc->id); $this->assertNull($testDocLoad); $this->dm->persist($testDoc); $this->dm->flush(); $this->dm->clear(); - $testDocLoad = $this->dm->find(__NAMESPACE__.'\MODM95TestDocument', $testDoc->id); + $testDocLoad = $this->dm->find(__NAMESPACE__ . '\MODM95TestDocument', $testDoc->id); $this->assertNotNull($testDocLoad); $this->assertEquals($embeddedDocuments, $testDocLoad->embeddedDocuments->toArray()); @@ -49,7 +53,8 @@ class MODM95TestDocument /** @ODM\EmbedMany(targetDocument="MODM95TestEmbeddedDocument") */ public $embeddedDocuments; - public function __construct() { + public function __construct() + { $this->embeddedDocuments = new ArrayCollection(); } @@ -64,7 +69,8 @@ public function __construct() { * * @param array|Traversable $children */ - public function setEmbeddedDocuments($embeddedDocuments) { + public function setEmbeddedDocuments($embeddedDocuments) + { $this->embeddedDocuments->clear(); if (! (is_array($embeddedDocuments) || $embeddedDocuments instanceof \Traversable)) { @@ -83,7 +89,8 @@ class MODM95TestEmbeddedDocument /** @ODM\Field(type="string") */ public $name; - public function __construct($name) { + public function __construct($name) + { $this->name = $name; } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/UpsertTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/UpsertTest.php index 4bf88967fe..8ba6ec4477 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/UpsertTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/UpsertTest.php @@ -1,10 +1,14 @@ id = (string) new \MongoDB\BSON\ObjectId(); + $test->id = (string) new ObjectId(); $embedded = new UpsertTestUserEmbedded(); - $embedded->id = (string) new \MongoDB\BSON\ObjectId(); + $embedded->id = (string) new ObjectId(); $embedded->test = 'test'; $test->embedMany[] = $embedded; diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/VersionTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/VersionTest.php index 4eb41efe8d..243595e0e3 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/VersionTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/VersionTest.php @@ -1,10 +1,14 @@ embedMany[] = new VersionedEmbeddedDocument('embed 3'); $this->dm->flush(); $this->assertEquals($expectedVersion++, $doc->version); - + $doc->embedMany[0]->embedMany[] = new VersionedEmbeddedDocument('deeply embed 1'); $this->dm->flush(); $this->assertEquals($expectedVersion++, $doc->version); - + unset($doc->embedMany[1]); $this->dm->flush(); $this->assertEquals($expectedVersion++, $doc->version); $doc->embedMany->clear(); $this->dm->flush(); - $this->assertEquals($expectedVersion++, $doc->version); - + $this->assertEquals($expectedVersion++, $doc->version); + $doc->embedMany = null; $this->dm->flush(); $this->assertEquals($expectedVersion++, $doc->version); @@ -46,19 +50,19 @@ class VersionedDocument { /** @ODM\Id */ public $id; - + /** @ODM\Field(type="int", name="_version") @ODM\Version */ public $version = 1; - + /** @ODM\Field(type="string") */ public $name; - + /** @ODM\EmbedMany(targetDocument="VersionedEmbeddedDocument") */ - public $embedMany = array(); - + public $embedMany = []; + public function __construct() { - $this->embedMany = new \Doctrine\Common\Collections\ArrayCollection(); + $this->embedMany = new ArrayCollection(); } } @@ -69,13 +73,13 @@ class VersionedEmbeddedDocument { /** @ODM\Field(type="string") */ public $value; - + /** @ODM\EmbedMany(targetDocument="VersionedEmbeddedDocument") */ public $embedMany; - - public function __construct($value) + + public function __construct($value) { $this->value = $value; - $this->embedMany = new \Doctrine\Common\Collections\ArrayCollection(); + $this->embedMany = new ArrayCollection(); } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/HydratorTest.php b/tests/Doctrine/ODM/MongoDB/Tests/HydratorTest.php index 5fa4815908..50c36b8918 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/HydratorTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/HydratorTest.php @@ -1,5 +1,7 @@ dm->getClassMetadata(__NAMESPACE__.'\HydrationClosureUser'); + $class = $this->dm->getClassMetadata(__NAMESPACE__ . '\HydrationClosureUser'); $user = new HydrationClosureUser(); - $this->dm->getHydratorFactory()->hydrate($user, array( + $this->dm->getHydratorFactory()->hydrate($user, [ '_id' => 1, 'title' => null, 'name' => 'jon', 'birthdate' => new \DateTime('1961-01-01'), - 'referenceOne' => array('$id' => '1'), - 'referenceMany' => array( - array( - '$id' => '1' - ), - array( - '$id' => '2' - ) - ), - 'embedOne' => array('name' => 'jon'), - 'embedMany' => array( - array('name' => 'jon') - ) - )); + 'referenceOne' => ['$id' => '1'], + 'referenceMany' => [ + ['$id' => '1'], + ['$id' => '2'], + ], + 'embedOne' => ['name' => 'jon'], + 'embedMany' => [ + ['name' => 'jon'], + ], + ]); $this->assertEquals(1, $user->id); $this->assertNull($user->title); $this->assertEquals('jon', $user->name); $this->assertInstanceOf('DateTime', $user->birthdate); - $this->assertInstanceOf(__NAMESPACE__.'\HydrationClosureReferenceOne', $user->referenceOne); + $this->assertInstanceOf(__NAMESPACE__ . '\HydrationClosureReferenceOne', $user->referenceOne); $this->assertInstanceOf('Doctrine\ODM\MongoDB\PersistentCollection', $user->referenceMany); $this->assertInstanceOf('Doctrine\ODM\MongoDB\Proxy\Proxy', $user->referenceMany[0]); $this->assertInstanceOf('Doctrine\ODM\MongoDB\Proxy\Proxy', $user->referenceMany[1]); @@ -47,7 +45,7 @@ public function testHydrator() public function testReadOnly() { - $class = $this->dm->getClassMetadata(__NAMESPACE__.'\HydrationClosureUser'); + $class = $this->dm->getClassMetadata(__NAMESPACE__ . '\HydrationClosureUser'); $user = new HydrationClosureUser(); $this->dm->getHydratorFactory()->hydrate($user, [ @@ -56,7 +54,7 @@ public function testReadOnly() 'birthdate' => new \DateTime('1961-01-01'), 'embedOne' => ['name' => 'maciej'], 'embedMany' => [ - ['name' => 'maciej'] + ['name' => 'maciej'], ], ], [ Query::HINT_READ_ONLY => true ]); @@ -85,13 +83,13 @@ class HydrationClosureUser public $referenceOne; /** @ODM\ReferenceMany(targetDocument="HydrationClosureReferenceMany") */ - public $referenceMany = array(); + public $referenceMany = []; /** @ODM\EmbedOne(targetDocument="HydrationClosureEmbedOne") */ public $embedOne; /** @ODM\EmbedMany(targetDocument="HydrationClosureEmbedMany") */ - public $embedMany = array(); + public $embedMany = []; } /** @ODM\Document */ diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Id/IncrementGeneratorTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Id/IncrementGeneratorTest.php index 523b197442..68c933ce96 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Id/IncrementGeneratorTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Id/IncrementGeneratorTest.php @@ -1,11 +1,15 @@ _loadDriver(); $class = new ClassMetadata($className); @@ -52,7 +59,7 @@ public function testDocumentMarkedAsReadOnly($class) */ public function testDocumentLevelReadPreference($class) { - $this->assertEquals("primaryPreferred", $class->readPreference); + $this->assertEquals('primaryPreferred', $class->readPreference); $this->assertEquals([ ['dc' => 'east'], ['dc' => 'west'], @@ -164,9 +171,9 @@ public function testVersionFieldMappings($class) } /** - * @depends testFieldMappings - * @param ClassMetadata $class - */ + * @depends testFieldMappings + * @param ClassMetadata $class + */ public function testLockFieldMappings($class) { $this->assertEquals('int', $class->fieldMappings['lock']['type']); @@ -210,10 +217,10 @@ public function testOwningOneToOneAssocation($class) */ public function testLifecycleCallbacks($class) { - $expectedLifecycleCallbacks = array( - 'prePersist' => array('doStuffOnPrePersist', 'doOtherStuffOnPrePersistToo'), - 'postPersist' => array('doStuffOnPostPersist'), - ); + $expectedLifecycleCallbacks = [ + 'prePersist' => ['doStuffOnPrePersist', 'doOtherStuffOnPrePersistToo'], + 'postPersist' => ['doStuffOnPostPersist'], + ]; $this->assertEquals($expectedLifecycleCallbacks, $class->lifecycleCallbacks); @@ -266,9 +273,7 @@ public function testDiscriminator($class) $this->assertTrue(isset($class->discriminatorMap)); $this->assertTrue(isset($class->defaultDiscriminatorValue)); $this->assertEquals('discr', $class->discriminatorField); - $this->assertEquals(array( - 'default' => 'Doctrine\ODM\MongoDB\Tests\Mapping\AbstractMappingDriverUser', - ), $class->discriminatorMap); + $this->assertEquals(['default' => 'Doctrine\ODM\MongoDB\Tests\Mapping\AbstractMappingDriverUser'], $class->discriminatorMap); $this->assertEquals('default', $class->defaultDiscriminatorValue); return $class; @@ -284,10 +289,10 @@ public function testEmbedDiscriminator($class) $this->assertTrue(isset($class->fieldMappings['otherPhonenumbers']['discriminatorMap'])); $this->assertTrue(isset($class->fieldMappings['otherPhonenumbers']['defaultDiscriminatorValue'])); $this->assertEquals('discr', $class->fieldMappings['otherPhonenumbers']['discriminatorField']); - $this->assertEquals(array( + $this->assertEquals([ 'home' => 'Doctrine\ODM\MongoDB\Tests\Mapping\HomePhonenumber', - 'work' => 'Doctrine\ODM\MongoDB\Tests\Mapping\WorkPhonenumber' - ), $class->fieldMappings['otherPhonenumbers']['discriminatorMap']); + 'work' => 'Doctrine\ODM\MongoDB\Tests\Mapping\WorkPhonenumber', + ], $class->fieldMappings['otherPhonenumbers']['discriminatorMap']); $this->assertEquals('home', $class->fieldMappings['otherPhonenumbers']['defaultDiscriminatorValue']); return $class; @@ -303,10 +308,10 @@ public function testReferenceDiscriminator($class) $this->assertTrue(isset($class->fieldMappings['phonenumbers']['discriminatorMap'])); $this->assertTrue(isset($class->fieldMappings['phonenumbers']['defaultDiscriminatorValue'])); $this->assertEquals('discr', $class->fieldMappings['phonenumbers']['discriminatorField']); - $this->assertEquals(array( + $this->assertEquals([ 'home' => 'Doctrine\ODM\MongoDB\Tests\Mapping\HomePhonenumber', - 'work' => 'Doctrine\ODM\MongoDB\Tests\Mapping\WorkPhonenumber' - ), $class->fieldMappings['phonenumbers']['discriminatorMap']); + 'work' => 'Doctrine\ODM\MongoDB\Tests\Mapping\WorkPhonenumber', + ], $class->fieldMappings['phonenumbers']['discriminatorMap']); $this->assertEquals('home', $class->fieldMappings['phonenumbers']['defaultDiscriminatorValue']); return $class; @@ -323,7 +328,7 @@ public function testIndexes($class) /* Sort indexes by their first fieldname. This is necessary since the * index registration order may differ among drivers. */ - $this->assertTrue(usort($indexes, function(array $a, array $b) { + $this->assertTrue(usort($indexes, function (array $a, array $b) { return strcmp(key($a['keys']), key($b['keys'])); })); @@ -345,7 +350,7 @@ public function testIndexes($class) $this->assertEquals(1, $indexes[2]['keys']['lock']); $this->assertNotEmpty($indexes[2]['options']); $this->assertTrue(isset($indexes[2]['options']['partialFilterExpression'])); - $this->assertSame(array('version' => array('$gt' => 1), 'discr' => array('$eq' => 'default')), $indexes[2]['options']['partialFilterExpression']); + $this->assertSame(['version' => ['$gt' => 1], 'discr' => ['$eq' => 'default']], $indexes[2]['options']['partialFilterExpression']); $this->assertTrue(isset($indexes[3]['keys']['mysqlProfileId'])); $this->assertEquals(-1, $indexes[3]['keys']['mysqlProfileId']); @@ -472,7 +477,7 @@ class AbstractMappingDriverUser /** * @ODM\Field(type="collection") */ - public $roles = array(); + public $roles = []; /** * @ODM\PrePersist @@ -502,97 +507,92 @@ public static function loadMetadata(ClassMetadata $metadata) $metadata->addLifecycleCallback('doStuffOnPrePersist', 'prePersist'); $metadata->addLifecycleCallback('doOtherStuffOnPrePersistToo', 'prePersist'); $metadata->addLifecycleCallback('doStuffOnPostPersist', 'postPersist'); - $metadata->setDiscriminatorField(array( - 'fieldName' => 'discr', - )); - $metadata->setDiscriminatorMap(array( - 'default' => __CLASS__, - )); + $metadata->setDiscriminatorField(['fieldName' => 'discr']); + $metadata->setDiscriminatorMap(['default' => __CLASS__]); $metadata->setDefaultDiscriminatorValue('default'); - $metadata->mapField(array( + $metadata->mapField([ 'id' => true, 'fieldName' => 'id', - )); - $metadata->mapField(array( + ]); + $metadata->mapField([ 'fieldName' => 'version', 'type' => 'int', 'version' => true, - )); - $metadata->mapField(array( + ]); + $metadata->mapField([ 'fieldName' => 'lock', 'type' => 'int', 'lock' => true, - )); - $metadata->mapField(array( + ]); + $metadata->mapField([ 'fieldName' => 'name', 'name' => 'username', 'type' => 'string', - )); - $metadata->mapField(array( + ]); + $metadata->mapField([ 'fieldName' => 'email', 'type' => 'string', - )); - $metadata->mapField(array( + ]); + $metadata->mapField([ 'fieldName' => 'mysqlProfileId', 'type' => 'integer', - )); - $metadata->mapOneReference(array( + ]); + $metadata->mapOneReference([ 'fieldName' => 'address', 'targetDocument' => 'Doctrine\\ODM\\MongoDB\\Tests\\Mapping\\Address', - 'cascade' => array(0 => 'remove'), - )); - $metadata->mapManyReference(array( + 'cascade' => [0 => 'remove'], + ]); + $metadata->mapManyReference([ 'fieldName' => 'phonenumbers', 'targetDocument' => 'Doctrine\\ODM\\MongoDB\\Tests\\Mapping\\Phonenumber', 'collectionClass' => 'Doctrine\\ODM\\MongoDB\\Tests\\Mapping\\PhonenumberCollection', - 'cascade' => array(1 => 'persist'), + 'cascade' => [1 => 'persist'], 'discriminatorField' => 'discr', - 'discriminatorMap' => array( + 'discriminatorMap' => [ 'home' => 'HomePhonenumber', - 'work' => 'WorkPhonenumber' - ), + 'work' => 'WorkPhonenumber', + ], 'defaultDiscriminatorValue' => 'home', - )); - $metadata->mapManyReference(array( + ]); + $metadata->mapManyReference([ 'fieldName' => 'morePhoneNumbers', 'name' => 'more_phone_numbers', 'targetDocument' => 'Doctrine\\ODM\\MongoDB\\Tests\\Mapping\\Phonenumber', 'collectionClass' => 'Doctrine\\ODM\\MongoDB\\Tests\\Mapping\\PhonenumberCollection', - )); - $metadata->mapManyReference(array( + ]); + $metadata->mapManyReference([ 'fieldName' => 'groups', 'targetDocument' => 'Doctrine\\ODM\\MongoDB\\Tests\\Mapping\\Group', - 'cascade' => array( + 'cascade' => [ 0 => 'remove', 1 => 'persist', 2 => 'refresh', 3 => 'merge', 4 => 'detach', - ), - )); - $metadata->mapOneEmbedded(array( + ], + ]); + $metadata->mapOneEmbedded([ 'fieldName' => 'embeddedPhonenumber', 'name' => 'embedded_phone_number', - )); - $metadata->mapManyEmbedded(array( + ]); + $metadata->mapManyEmbedded([ 'fieldName' => 'otherPhonenumbers', 'targetDocument' => 'Doctrine\\ODM\\MongoDB\\Tests\\Mapping\\Phonenumber', 'discriminatorField' => 'discr', - 'discriminatorMap' => array( + 'discriminatorMap' => [ 'home' => 'HomePhonenumber', 'work' => 'WorkPhonenumber', - ), + ], 'defaultDiscriminatorValue' => 'home', - )); - $metadata->addIndex(array('username' => 'desc'), array('unique' => true, 'dropDups' => false)); - $metadata->addIndex(array('email' => 'desc'), array('unique' => true, 'dropDups' => true)); - $metadata->addIndex(array('mysqlProfileId' => 'desc'), array('unique' => true, 'dropDups' => true)); - $metadata->addIndex(array('createdAt' => 'asc'), array('expireAfterSeconds' => 3600)); - $metadata->setShardKey(array('name' => 'asc'), array('unique' => true, 'numInitialChunks' => 4096)); + ]); + $metadata->addIndex(['username' => 'desc'], ['unique' => true, 'dropDups' => false]); + $metadata->addIndex(['email' => 'desc'], ['unique' => true, 'dropDups' => true]); + $metadata->addIndex(['mysqlProfileId' => 'desc'], ['unique' => true, 'dropDups' => true]); + $metadata->addIndex(['createdAt' => 'asc'], ['expireAfterSeconds' => 3600]); + $metadata->setShardKey(['name' => 'asc'], ['unique' => true, 'numInitialChunks' => 4096]); } } -class PhonenumberCollection extends \Doctrine\Common\Collections\ArrayCollection +class PhonenumberCollection extends ArrayCollection { - } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Mapping/AnnotationDriverTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Mapping/AnnotationDriverTest.php index 356401ca82..fa11fe2a20 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Mapping/AnnotationDriverTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Mapping/AnnotationDriverTest.php @@ -1,9 +1,14 @@ expectException(\Doctrine\ODM\MongoDB\Mapping\MappingException::class); + $this->expectException(MappingException::class); $annotationDriver->loadMetadataForClass('stdClass', $cm); } @@ -78,8 +83,8 @@ public function testLoadMetadataForNonDocumentThrowsException() public function testColumnWithMissingTypeDefaultsToString() { $cm = new ClassMetadata('Doctrine\ODM\MongoDB\Tests\Mapping\ColumnWithoutType'); - $reader = new \Doctrine\Common\Annotations\AnnotationReader(); - $annotationDriver = new \Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver($reader); + $reader = new AnnotationReader(); + $annotationDriver = new AnnotationDriver($reader); $annotationDriver->loadMetadataForClass('Doctrine\ODM\MongoDB\Tests\Mapping\InvalidColumn', $cm); $this->assertEquals('id', $cm->fieldMappings['id']['type']); @@ -163,14 +168,14 @@ public function testDocumentAnnotationCanSpecifyWriteConcern() protected function _loadDriverForCMSDocuments() { $annotationDriver = $this->_loadDriver(); - $annotationDriver->addPaths(array(__DIR__ . '/../../../../../Documents')); + $annotationDriver->addPaths([__DIR__ . '/../../../../../Documents']); return $annotationDriver; } protected function _loadDriver() { - $reader = new \Doctrine\Common\Annotations\AnnotationReader(); - return new \Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver($reader); + $reader = new AnnotationReader(); + return new AnnotationDriver($reader); } } @@ -178,7 +183,7 @@ protected function _loadDriver() class ColumnWithoutType { /** @ODM\Id */ - public $id; + public $id; } /** @ODM\MappedSuperclass */ diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Mapping/BasicInheritanceMappingTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Mapping/BasicInheritanceMappingTest.php index bf69fd9d15..c12afc0ce4 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Mapping/BasicInheritanceMappingTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Mapping/BasicInheritanceMappingTest.php @@ -1,11 +1,16 @@ factory->getMetadataFor(DocumentSubClass2::class); - $this->assertSame("secondary", $class->readPreference); + $this->assertSame('secondary', $class->readPreference); $this->assertEquals([ ['dc' => 'east'] ], $class->readPreferenceTags); } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Mapping/ClassMetadataFactoryTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Mapping/ClassMetadataFactoryTest.php index 8a1c6a1bac..ab0ab66593 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Mapping/ClassMetadataFactoryTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Mapping/ClassMetadataFactoryTest.php @@ -1,114 +1,116 @@ -setCollection('group'); - // Add a mapped field - $cm1->mapField(array('fieldName' => 'name', 'type' => 'string')); - // Add a mapped field - $cm1->mapField(array('fieldName' => 'id', 'id' => true)); - // and a mapped association - $cm1->mapOneEmbedded(array('fieldName' => 'other', 'targetDocument' => 'Other')); - $cm1->mapOneEmbedded(array('fieldName' => 'association', 'targetDocument' => 'Other')); - - // SUT - $cmf = new ClassMetadataFactoryTestSubject(); - $cmf->setMetadataFor('Doctrine\ODM\MongoDB\Tests\Mapping\TestDocument1', $cm1); - - // Prechecks - $this->assertEquals(array(), $cm1->parentClasses); - $this->assertEquals(ClassMetadata::INHERITANCE_TYPE_NONE, $cm1->inheritanceType); - $this->assertTrue($cm1->hasField('name')); - $this->assertCount(4, $cm1->fieldMappings); - - // Go - $cm1 = $cmf->getMetadataFor('Doctrine\ODM\MongoDB\Tests\Mapping\TestDocument1'); - - $this->assertEquals('group', $cm1->collection); - $this->assertEquals(array(), $cm1->parentClasses); - $this->assertTrue($cm1->hasField('name')); - } - - public function testHasGetMetadata_NamespaceSeperatorIsNotNormalized() - { - require_once __DIR__."/Documents/GlobalNamespaceDocument.php"; - - $driver = AnnotationDriver::create(__DIR__ . '/Documents'); - - $dm = $this->getMockDocumentManager($driver); - - $cmf = new ClassMetadataFactory(); - $cmf->setConfiguration($dm->getConfiguration()); - $cmf->setDocumentManager($dm); - - $m1 = $cmf->getMetadataFor("DoctrineGlobal_Article"); - $h1 = $cmf->hasMetadataFor("DoctrineGlobal_Article"); - $h2 = $cmf->hasMetadataFor("\DoctrineGlobal_Article"); - $m2 = $cmf->getMetadataFor("\DoctrineGlobal_Article"); - - $this->assertNotSame($m1, $m2); - $this->assertFalse($h2); - $this->assertTrue($h1); - } - - protected function getMockDocumentManager($driver) - { - $config = new Configuration(); - $config->setMetadataDriverImpl($driver); - - $em = $this->createMock('Doctrine\Common\EventManager'); - - $dm = new DocumentManagerMock(); - $dm->config = $config; - $dm->eventManager = $em; - - return $dm; - } -} - -/* Test subject class with overriden factory method for mocking purposes */ -class ClassMetadataFactoryTestSubject extends \Doctrine\ODM\MongoDB\Mapping\ClassMetadataFactory -{ - private $_mockMetadata = array(); - private $_requestedClasses = array(); - - /** @override */ - protected function _newClassMetadataInstance($className) - { - $this->_requestedClasses[] = $className; - if ( ! isset($this->_mockMetadata[$className])) { - throw new InvalidArgumentException("No mock metadata found for class $className."); - } - return $this->_mockMetadata[$className]; - } - - public function setMetadataForClass($className, $metadata) - { - $this->_mockMetadata[$className] = $metadata; - } - - public function getRequestedClasses() - { - return $this->_requestedClasses; - } -} - -class TestDocument1 -{ - private $id; - private $name; - private $other; - private $association; -} +setCollection('group'); + // Add a mapped field + $cm1->mapField(['fieldName' => 'name', 'type' => 'string']); + // Add a mapped field + $cm1->mapField(['fieldName' => 'id', 'id' => true]); + // and a mapped association + $cm1->mapOneEmbedded(['fieldName' => 'other', 'targetDocument' => 'Other']); + $cm1->mapOneEmbedded(['fieldName' => 'association', 'targetDocument' => 'Other']); + + // SUT + $cmf = new ClassMetadataFactoryTestSubject(); + $cmf->setMetadataFor('Doctrine\ODM\MongoDB\Tests\Mapping\TestDocument1', $cm1); + + // Prechecks + $this->assertEquals([], $cm1->parentClasses); + $this->assertEquals(ClassMetadata::INHERITANCE_TYPE_NONE, $cm1->inheritanceType); + $this->assertTrue($cm1->hasField('name')); + $this->assertCount(4, $cm1->fieldMappings); + + // Go + $cm1 = $cmf->getMetadataFor('Doctrine\ODM\MongoDB\Tests\Mapping\TestDocument1'); + + $this->assertEquals('group', $cm1->collection); + $this->assertEquals([], $cm1->parentClasses); + $this->assertTrue($cm1->hasField('name')); + } + + public function testHasGetMetadata_NamespaceSeperatorIsNotNormalized() + { + require_once __DIR__ . '/Documents/GlobalNamespaceDocument.php'; + + $driver = AnnotationDriver::create(__DIR__ . '/Documents'); + + $dm = $this->getMockDocumentManager($driver); + + $cmf = new ClassMetadataFactory(); + $cmf->setConfiguration($dm->getConfiguration()); + $cmf->setDocumentManager($dm); + + $m1 = $cmf->getMetadataFor('DoctrineGlobal_Article'); + $h1 = $cmf->hasMetadataFor('DoctrineGlobal_Article'); + $h2 = $cmf->hasMetadataFor('\DoctrineGlobal_Article'); + $m2 = $cmf->getMetadataFor('\DoctrineGlobal_Article'); + + $this->assertNotSame($m1, $m2); + $this->assertFalse($h2); + $this->assertTrue($h1); + } + + protected function getMockDocumentManager($driver) + { + $config = new Configuration(); + $config->setMetadataDriverImpl($driver); + + $em = $this->createMock('Doctrine\Common\EventManager'); + + $dm = new DocumentManagerMock(); + $dm->config = $config; + $dm->eventManager = $em; + + return $dm; + } +} + +/* Test subject class with overriden factory method for mocking purposes */ +class ClassMetadataFactoryTestSubject extends ClassMetadataFactory +{ + private $_mockMetadata = []; + private $_requestedClasses = []; + + protected function _newClassMetadataInstance($className) + { + $this->_requestedClasses[] = $className; + if (! isset($this->_mockMetadata[$className])) { + throw new InvalidArgumentException("No mock metadata found for class $className."); + } + return $this->_mockMetadata[$className]; + } + + public function setMetadataForClass($className, $metadata) + { + $this->_mockMetadata[$className] = $metadata; + } + + public function getRequestedClasses() + { + return $this->_requestedClasses; + } +} + +class TestDocument1 +{ + private $id; + private $name; + private $other; + private $association; +} diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Mapping/ClassMetadataLoadEventTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Mapping/ClassMetadataLoadEventTest.php index 2ca3a00e8a..353e2df936 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Mapping/ClassMetadataLoadEventTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Mapping/ClassMetadataLoadEventTest.php @@ -1,11 +1,15 @@ assertTrue($classMetadata->hasField('about')); } - public function loadClassMetadata(\Doctrine\ODM\MongoDB\Event\LoadClassMetadataEventArgs $eventArgs) + public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs) { $classMetadata = $eventArgs->getClassMetadata(); - $field = array( + $field = [ 'fieldName' => 'about', - 'type' => 'string' - ); + 'type' => 'string', + ]; $classMetadata->mapField($field); } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Mapping/ClassMetadataTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Mapping/ClassMetadataTest.php index e046acadbf..25619075c4 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Mapping/ClassMetadataTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Mapping/ClassMetadataTest.php @@ -1,19 +1,27 @@ assertInstanceOf(\ReflectionClass::class, $cm->reflClass); $this->assertEquals('Documents\CmsUser', $cm->name); $this->assertEquals('Documents\CmsUser', $cm->rootDocumentName); - $this->assertEquals(array(), $cm->subClasses); - $this->assertEquals(array(), $cm->parentClasses); + $this->assertEquals([], $cm->subClasses); + $this->assertEquals([], $cm->parentClasses); $this->assertEquals(ClassMetadata::INHERITANCE_TYPE_NONE, $cm->inheritanceType); // Customize state $cm->setInheritanceType(ClassMetadata::INHERITANCE_TYPE_SINGLE_COLLECTION); - $cm->setSubclasses(array("One", "Two", "Three")); - $cm->setParentClasses(array("UserParent")); - $cm->setCustomRepositoryClass("UserRepository"); + $cm->setSubclasses(['One', 'Two', 'Three']); + $cm->setParentClasses(['UserParent']); + $cm->setCustomRepositoryClass('UserRepository'); $cm->setDiscriminatorField('disc'); - $cm->mapOneEmbedded(array('fieldName' => 'phonenumbers', 'targetDocument' => 'Bar')); - $cm->setShardKey(array('_id' => '1')); + $cm->mapOneEmbedded(['fieldName' => 'phonenumbers', 'targetDocument' => 'Bar']); + $cm->setShardKey(['_id' => '1']); $cm->setCollectionCapped(true); $cm->setCollectionMax(1000); $cm->setCollectionSize(500); @@ -52,14 +60,14 @@ public function testClassMetadataInstanceSerialization() $this->assertInstanceOf(\ReflectionClass::class, $cm->reflClass); $this->assertEquals('Documents\CmsUser', $cm->name); $this->assertEquals('UserParent', $cm->rootDocumentName); - $this->assertEquals(array('Documents\One', 'Documents\Two', 'Documents\Three'), $cm->subClasses); - $this->assertEquals(array('UserParent'), $cm->parentClasses); + $this->assertEquals(['Documents\One', 'Documents\Two', 'Documents\Three'], $cm->subClasses); + $this->assertEquals(['UserParent'], $cm->parentClasses); $this->assertEquals('Documents\UserRepository', $cm->customRepositoryClassName); $this->assertEquals('disc', $cm->discriminatorField); $this->assertInternalType('array', $cm->getFieldMapping('phonenumbers')); $this->assertCount(1, $cm->fieldMappings); $this->assertCount(1, $cm->associationMappings); - $this->assertEquals(array('keys' => array('_id' => 1), 'options' => array()), $cm->getShardKey()); + $this->assertEquals(['keys' => ['_id' => 1], 'options' => []], $cm->getShardKey()); $mapping = $cm->getFieldMapping('phonenumbers'); $this->assertEquals('Documents\Bar', $mapping['targetDocument']); $this->assertTrue($cm->getCollectionCapped()); @@ -70,11 +78,11 @@ public function testClassMetadataInstanceSerialization() public function testOwningSideAndInverseSide() { $cm = new ClassMetadata(User::class); - $cm->mapOneReference(array('fieldName' => 'account', 'targetDocument' => Account::class, 'inversedBy' => 'user')); + $cm->mapOneReference(['fieldName' => 'account', 'targetDocument' => Account::class, 'inversedBy' => 'user']); $this->assertTrue($cm->fieldMappings['account']['isOwningSide']); $cm = new ClassMetadata(Account::class); - $cm->mapOneReference(array('fieldName' => 'user', 'targetDocument' => Account::class, 'mappedBy' => 'account')); + $cm->mapOneReference(['fieldName' => 'user', 'targetDocument' => Account::class, 'mappedBy' => 'account']); $this->assertTrue($cm->fieldMappings['user']['isInverseSide']); } @@ -83,16 +91,16 @@ public function testFieldIsNullable() $cm = new ClassMetadata('Documents\CmsUser'); // Explicit Nullable - $cm->mapField(array('fieldName' => 'status', 'nullable' => true, 'type' => 'string', 'length' => 50)); + $cm->mapField(['fieldName' => 'status', 'nullable' => true, 'type' => 'string', 'length' => 50]); $this->assertTrue($cm->isNullable('status')); // Explicit Not Nullable - $cm->mapField(array('fieldName' => 'username', 'nullable' => false, 'type' => 'string', 'length' => 50)); + $cm->mapField(['fieldName' => 'username', 'nullable' => false, 'type' => 'string', 'length' => 50]); $this->assertFalse($cm->isNullable('username')); // Implicit Not Nullable - $cm->mapField(array('fieldName' => 'name', 'type' => 'string', 'length' => 50)); - $this->assertFalse($cm->isNullable('name'), "By default a field should not be nullable."); + $cm->mapField(['fieldName' => 'name', 'type' => 'string', 'length' => 50]); + $this->assertFalse($cm->isNullable('name'), 'By default a field should not be nullable.'); } /** @@ -100,25 +108,26 @@ public function testFieldIsNullable() */ public function testMapAssocationInGlobalNamespace() { - require_once __DIR__."/Documents/GlobalNamespaceDocument.php"; + require_once __DIR__ . '/Documents/GlobalNamespaceDocument.php'; $cm = new ClassMetadata('DoctrineGlobal_Article'); - $cm->mapManyEmbedded(array( + $cm->mapManyEmbedded([ 'fieldName' => 'author', 'targetDocument' => 'DoctrineGlobal_User', - )); + ]); - $this->assertEquals("DoctrineGlobal_User", $cm->fieldMappings['author']['targetDocument']); + $this->assertEquals('DoctrineGlobal_User', $cm->fieldMappings['author']['targetDocument']); } public function testMapManyToManyJoinTableDefaults() { $cm = new ClassMetadata('Documents\CmsUser'); $cm->mapManyEmbedded( - array( + [ 'fieldName' => 'groups', - 'targetDocument' => 'CmsGroup' - )); + 'targetDocument' => 'CmsGroup', + ] + ); $assoc = $cm->fieldMappings['groups']; $this->assertInternalType('array', $assoc); @@ -129,13 +138,13 @@ public function testMapManyToManyJoinTableDefaults() */ public function testSetDiscriminatorMapInGlobalNamespace() { - require_once __DIR__."/Documents/GlobalNamespaceDocument.php"; + require_once __DIR__ . '/Documents/GlobalNamespaceDocument.php'; $cm = new ClassMetadata('DoctrineGlobal_User'); - $cm->setDiscriminatorMap(array('descr' => 'DoctrineGlobal_Article', 'foo' => 'DoctrineGlobal_User')); + $cm->setDiscriminatorMap(['descr' => 'DoctrineGlobal_Article', 'foo' => 'DoctrineGlobal_User']); - $this->assertEquals("DoctrineGlobal_Article", $cm->discriminatorMap['descr']); - $this->assertEquals("DoctrineGlobal_User", $cm->discriminatorMap['foo']); + $this->assertEquals('DoctrineGlobal_Article', $cm->discriminatorMap['descr']); + $this->assertEquals('DoctrineGlobal_User', $cm->discriminatorMap['foo']); } /** @@ -143,19 +152,19 @@ public function testSetDiscriminatorMapInGlobalNamespace() */ public function testSetSubClassesInGlobalNamespace() { - require_once __DIR__."/Documents/GlobalNamespaceDocument.php"; + require_once __DIR__ . '/Documents/GlobalNamespaceDocument.php'; $cm = new ClassMetadata('DoctrineGlobal_User'); - $cm->setSubclasses(array('DoctrineGlobal_Article')); + $cm->setSubclasses(['DoctrineGlobal_Article']); - $this->assertEquals("DoctrineGlobal_Article", $cm->subClasses[0]); + $this->assertEquals('DoctrineGlobal_Article', $cm->subClasses[0]); } public function testDuplicateFieldMapping() { $cm = new ClassMetadata('Documents\CmsUser'); - $a1 = array('reference' => true, 'type' => 'many', 'fieldName' => 'name', 'targetDocument' => 'stdClass'); - $a2 = array('type' => 'string', 'fieldName' => 'name'); + $a1 = ['reference' => true, 'type' => 'many', 'fieldName' => 'name', 'targetDocument' => 'stdClass']; + $a2 = ['type' => 'string', 'fieldName' => 'name']; $cm->mapField($a1); $cm->mapField($a2); @@ -166,9 +175,9 @@ public function testDuplicateFieldMapping() public function testDuplicateColumnName_DiscriminatorColumn_ThrowsMappingException() { $cm = new ClassMetadata('Documents\CmsUser'); - $cm->mapField(array('fieldName' => 'name')); + $cm->mapField(['fieldName' => 'name']); - $this->expectException(\Doctrine\ODM\MongoDB\Mapping\MappingException::class); + $this->expectException(MappingException::class); $cm->setDiscriminatorField('name'); } @@ -177,15 +186,15 @@ public function testDuplicateFieldName_DiscriminatorColumn2_ThrowsMappingExcepti $cm = new ClassMetadata('Documents\CmsUser'); $cm->setDiscriminatorField('name'); - $this->expectException(\Doctrine\ODM\MongoDB\Mapping\MappingException::class); - $cm->mapField(array('fieldName' => 'name')); + $this->expectException(MappingException::class); + $cm->mapField(['fieldName' => 'name']); } public function testDuplicateFieldAndAssocationMapping1() { $cm = new ClassMetadata('Documents\CmsUser'); - $cm->mapField(array('fieldName' => 'name')); - $cm->mapOneEmbedded(array('fieldName' => 'name', 'targetDocument' => 'CmsUser')); + $cm->mapField(['fieldName' => 'name']); + $cm->mapOneEmbedded(['fieldName' => 'name', 'targetDocument' => 'CmsUser']); $this->assertEquals('one', $cm->fieldMappings['name']['type']); } @@ -193,8 +202,8 @@ public function testDuplicateFieldAndAssocationMapping1() public function testDuplicateFieldAndAssocationMapping2() { $cm = new ClassMetadata('Documents\CmsUser'); - $cm->mapOneEmbedded(array('fieldName' => 'name', 'targetDocument' => 'CmsUser')); - $cm->mapField(array('fieldName' => 'name', 'columnName' => 'name', 'type' => 'string')); + $cm->mapOneEmbedded(['fieldName' => 'name', 'targetDocument' => 'CmsUser']); + $cm->mapField(['fieldName' => 'name', 'columnName' => 'name', 'type' => 'string']); $this->assertEquals('string', $cm->fieldMappings['name']['type']); } @@ -205,11 +214,10 @@ public function testDuplicateFieldAndAssocationMapping2() public function testMapNotExistingFieldThrowsException() { $cm = new ClassMetadata('Documents\CmsUser'); - $cm->mapField(array('fieldName' => 'namee', 'columnName' => 'name', 'type' => 'string')); + $cm->mapField(['fieldName' => 'namee', 'columnName' => 'name', 'type' => 'string']); } /** - * @param ClassMetadata $cm * @dataProvider dataProviderMetadataClasses */ public function testEmbeddedDocumentWithDiscriminator(ClassMetadata $cm) @@ -251,44 +259,47 @@ public function testDefaultDiscriminatorField() $cm = new ClassMetadata(get_class($object)); - $cm->mapField(array( + $cm->mapField([ 'fieldName' => 'assoc', 'reference' => true, 'type' => 'one', - )); + ]); - $cm->mapField(array( + $cm->mapField([ 'fieldName' => 'assocWithTargetDocument', 'reference' => true, 'type' => 'one', 'targetDocument' => 'stdClass', - )); + ]); - $cm->mapField(array( + $cm->mapField([ 'fieldName' => 'assocWithDiscriminatorField', 'reference' => true, 'type' => 'one', 'discriminatorField' => 'type', - )); + ]); $mapping = $cm->getFieldMapping('assoc'); $this->assertEquals( - ClassMetadata::DEFAULT_DISCRIMINATOR_FIELD, $mapping['discriminatorField'], + ClassMetadata::DEFAULT_DISCRIMINATOR_FIELD, + $mapping['discriminatorField'], 'Default discriminator field is set for associations without targetDocument and discriminatorField options' ); $mapping = $cm->getFieldMapping('assocWithTargetDocument'); $this->assertArrayNotHasKey( - 'discriminatorField', $mapping, + 'discriminatorField', + $mapping, 'Default discriminator field is not set for associations with targetDocument option' ); $mapping = $cm->getFieldMapping('assocWithDiscriminatorField'); $this->assertEquals( - 'type', $mapping['discriminatorField'], + 'type', + $mapping['discriminatorField'], 'Default discriminator field is not set for associations with discriminatorField option' ); } @@ -401,11 +412,11 @@ public function testEmbeddedAssociationsAlwaysCascade() public function testEmbedWithCascadeThrowsMappingException() { $class = new ClassMetadata(__NAMESPACE__ . '\EmbedWithCascadeTest'); - $class->mapOneEmbedded(array( + $class->mapOneEmbedded([ 'fieldName' => 'address', 'targetDocument' => 'Documents\Address', 'cascade' => 'all', - )); + ]); } /** @@ -455,12 +466,12 @@ public function testSimpleReferenceRequiresTargetDocument() { $cm = new ClassMetadata('stdClass'); - $cm->mapField(array( + $cm->mapField([ 'fieldName' => 'assoc', 'reference' => true, 'type' => 'one', 'storeAs' => ClassMetadata::REFERENCE_STORE_AS_ID, - )); + ]); } /** @@ -471,12 +482,12 @@ public function testSimpleAsStringReferenceRequiresTargetDocument() { $cm = new ClassMetadata('stdClass'); - $cm->mapField(array( + $cm->mapField([ 'fieldName' => 'assoc', 'reference' => true, 'type' => 'one', 'storeAs' => ClassMetadata::REFERENCE_STORE_AS_ID, - )); + ]); } /** @@ -487,12 +498,12 @@ public function testStoreAsIdReferenceRequiresTargetDocument() { $cm = new ClassMetadata('stdClass'); - $cm->mapField(array( + $cm->mapField([ 'fieldName' => 'assoc', 'reference' => true, 'type' => 'one', 'storeAs' => ClassMetadata::REFERENCE_STORE_AS_ID, - )); + ]); } /** @@ -508,12 +519,12 @@ public function testAtomicCollectionUpdateUsageInEmbeddedDocument() $cm = new ClassMetadata(get_class($object)); $cm->isEmbeddedDocument = true; - $cm->mapField(array( + $cm->mapField([ 'fieldName' => 'many', 'reference' => true, 'type' => 'many', 'strategy' => ClassMetadata::STORAGE_STRATEGY_ATOMIC_SET, - )); + ]); } public function testDefaultStorageStrategyOfEmbeddedDocumentFields() @@ -525,10 +536,10 @@ public function testDefaultStorageStrategyOfEmbeddedDocumentFields() $cm = new ClassMetadata(get_class($object)); $cm->isEmbeddedDocument = true; - $mapping = $cm->mapField(array( + $mapping = $cm->mapField([ 'fieldName' => 'many', - 'type' => 'many' - )); + 'type' => 'many', + ]); self::assertEquals(CollectionHelper::DEFAULT_STRATEGY, $mapping['strategy']); } @@ -539,11 +550,11 @@ public function testDefaultStorageStrategyOfEmbeddedDocumentFields() */ public function testOwningAndInversedRefsNeedTargetDocument($config) { - $config = array_merge($config, array( + $config = array_merge($config, [ 'fieldName' => 'many', 'reference' => true, 'strategy' => ClassMetadata::STORAGE_STRATEGY_ATOMIC_SET, - )); + ]); $cm = new ClassMetadata('stdClass'); $cm->isEmbeddedDocument = true; @@ -552,30 +563,28 @@ public function testOwningAndInversedRefsNeedTargetDocument($config) public function provideOwningAndInversedRefsNeedTargetDocument() { - return array( - array(array('type' => 'one', 'mappedBy' => 'post')), - array(array('type' => 'one', 'inversedBy' => 'post')), - array(array('type' => 'many', 'mappedBy' => 'post')), - array(array('type' => 'many', 'inversedBy' => 'post')), - ); + return [ + [['type' => 'one', 'mappedBy' => 'post']], + [['type' => 'one', 'inversedBy' => 'post']], + [['type' => 'many', 'mappedBy' => 'post']], + [['type' => 'many', 'inversedBy' => 'post']], + ]; } public function testAddInheritedAssociationMapping() { $cm = new ClassMetadata('stdClass'); - $mapping = array( + $mapping = [ 'fieldName' => 'assoc', 'reference' => true, 'type' => 'one', 'storeAs' => ClassMetadata::REFERENCE_STORE_AS_ID, - ); + ]; $cm->addInheritedAssociationMapping($mapping); - $expected = array( - 'assoc' => $mapping, - ); + $expected = ['assoc' => $mapping]; $this->assertEquals($expected, $cm->associationMappings); } @@ -588,10 +597,10 @@ public function testIdFieldsTypeMustNotBeOverridden() { $cm = new ClassMetadata('stdClass'); $cm->setIdentifier('id'); - $cm->mapField(array( + $cm->mapField([ 'fieldName' => 'id', - 'type' => 'string' - )); + 'type' => 'string', + ]); } /** @@ -601,34 +610,34 @@ public function testIdFieldsTypeMustNotBeOverridden() public function testReferenceManySortMustNotBeUsedWithNonSetCollectionStrategy() { $cm = new ClassMetadata('stdClass'); - $cm->mapField(array( + $cm->mapField([ 'fieldName' => 'ref', 'reference' => true, 'strategy' => ClassMetadata::STORAGE_STRATEGY_PUSH_ALL, 'type' => 'many', - 'sort' => array('foo' => 1) - )); + 'sort' => ['foo' => 1], + ]); } public function testSetShardKeyForClassWithoutInheritance() { $cm = new ClassMetadata('stdClass'); - $cm->setShardKey(array('id' => 'asc')); + $cm->setShardKey(['id' => 'asc']); $shardKey = $cm->getShardKey(); - $this->assertEquals(array('id' => 1), $shardKey['keys']); + $this->assertEquals(['id' => 1], $shardKey['keys']); } public function testSetShardKeyForClassWithSingleCollectionInheritance() { $cm = new ClassMetadata('stdClass'); $cm->inheritanceType = ClassMetadata::INHERITANCE_TYPE_SINGLE_COLLECTION; - $cm->setShardKey(array('id' => 'asc')); + $cm->setShardKey(['id' => 'asc']); $shardKey = $cm->getShardKey(); - $this->assertEquals(array('id' => 1), $shardKey['keys']); + $this->assertEquals(['id' => 1], $shardKey['keys']); } /** @@ -638,21 +647,21 @@ public function testSetShardKeyForClassWithSingleCollectionInheritance() public function testSetShardKeyForClassWithSingleCollectionInheritanceWhichAlreadyHasIt() { $cm = new ClassMetadata('stdClass'); - $cm->setShardKey(array('id' => 'asc')); + $cm->setShardKey(['id' => 'asc']); $cm->inheritanceType = ClassMetadata::INHERITANCE_TYPE_SINGLE_COLLECTION; - $cm->setShardKey(array('foo' => 'asc')); + $cm->setShardKey(['foo' => 'asc']); } public function testSetShardKeyForClassWithCollPerClassInheritance() { $cm = new ClassMetadata('stdClass'); $cm->inheritanceType = ClassMetadata::INHERITANCE_TYPE_COLLECTION_PER_CLASS; - $cm->setShardKey(array('id' => 'asc')); + $cm->setShardKey(['id' => 'asc']); $shardKey = $cm->getShardKey(); - $this->assertEquals(array('id' => 1), $shardKey['keys']); + $this->assertEquals(['id' => 1], $shardKey['keys']); } public function testIsNotShardedIfThereIsNoShardKey() @@ -665,7 +674,7 @@ public function testIsNotShardedIfThereIsNoShardKey() public function testIsShardedIfThereIsAShardKey() { $cm = new ClassMetadata('stdClass'); - $cm->setShardKey(array('id' => 'asc')); + $cm->setShardKey(['id' => 'asc']); $this->assertTrue($cm->isSharded()); } @@ -678,7 +687,7 @@ public function testEmbeddedDocumentCantHaveShardKey() { $cm = new ClassMetadata('stdClass'); $cm->isEmbeddedDocument = true; - $cm->setShardKey(array('id' => 'asc')); + $cm->setShardKey(['id' => 'asc']); } /** @@ -697,7 +706,7 @@ public function testNoIncrementFieldsAllowedInShardKey() 'type' => 'int', 'strategy' => ClassMetadata::STORAGE_STRATEGY_INCREMENT, ]); - $cm->setShardKey(array('inc' => 1)); + $cm->setShardKey(['inc' => 1]); } /** @@ -713,9 +722,9 @@ public function testNoCollectionsInShardKey() $cm = new ClassMetadata(get_class($object)); $cm->mapField([ 'fieldName' => 'collection', - 'type' => 'collection' + 'type' => 'collection', ]); - $cm->setShardKey(array('collection' => 1)); + $cm->setShardKey(['collection' => 1]); } /** @@ -730,7 +739,7 @@ public function testNoEmbedManyInShardKey() $cm = new ClassMetadata(get_class($object)); $cm->mapManyEmbedded(['fieldName' => 'embedMany']); - $cm->setShardKey(array('embedMany' => 1)); + $cm->setShardKey(['embedMany' => 1]); } /** @@ -745,7 +754,7 @@ public function testNoReferenceManyInShardKey() $cm = new ClassMetadata(get_class($object)); $cm->mapManyEmbedded(['fieldName' => 'referenceMany']); - $cm->setShardKey(array('referenceMany' => 1)); + $cm->setShardKey(['referenceMany' => 1]); } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Mapping/Documents/GlobalNamespaceDocument.php b/tests/Doctrine/ODM/MongoDB/Tests/Mapping/Documents/GlobalNamespaceDocument.php index ecdb96eb07..bc636d1ece 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Mapping/Documents/GlobalNamespaceDocument.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Mapping/Documents/GlobalNamespaceDocument.php @@ -1,5 +1,7 @@ driver); + unset($this->driver); } public function testDriver() { - $classMetadata = new ClassMetadata('TestDocuments\User'); $this->driver->loadMetadataForClass('TestDocuments\User', $classMetadata); - $this->assertEquals(array( + $this->assertEquals([ 'fieldName' => 'id', 'id' => true, 'name' => '_id', @@ -45,10 +46,10 @@ public function testDriver() 'isCascadeRemove' => false, 'isInverseSide' => false, 'isOwningSide' => true, - 'nullable' => false - ), $classMetadata->fieldMappings['id']); + 'nullable' => false, + ], $classMetadata->fieldMappings['id']); - $this->assertEquals(array( + $this->assertEquals([ 'fieldName' => 'username', 'name' => 'username', 'type' => 'string', @@ -63,16 +64,16 @@ public function testDriver() 'unique' => true, 'sparse' => true, 'strategy' => ClassMetadata::STORAGE_STRATEGY_SET, - ), $classMetadata->fieldMappings['username']); + ], $classMetadata->fieldMappings['username']); - $this->assertEquals(array( - array( - 'keys' => array('username' => 1), - 'options' => array('unique' => true, 'sparse' => true) - ) - ), $classMetadata->getIndexes()); + $this->assertEquals([ + [ + 'keys' => ['username' => 1], + 'options' => ['unique' => true, 'sparse' => true], + ], + ], $classMetadata->getIndexes()); - $this->assertEquals(array( + $this->assertEquals([ 'fieldName' => 'createdAt', 'name' => 'createdAt', 'type' => 'date', @@ -85,9 +86,9 @@ public function testDriver() 'isOwningSide' => true, 'nullable' => false, 'strategy' => ClassMetadata::STORAGE_STRATEGY_SET, - ), $classMetadata->fieldMappings['createdAt']); + ], $classMetadata->fieldMappings['createdAt']); - $this->assertEquals(array( + $this->assertEquals([ 'fieldName' => 'tags', 'name' => 'tags', 'type' => 'collection', @@ -100,9 +101,9 @@ public function testDriver() 'isOwningSide' => true, 'nullable' => false, 'strategy' => ClassMetadata::STORAGE_STRATEGY_SET, - ), $classMetadata->fieldMappings['tags']); + ], $classMetadata->fieldMappings['tags']); - $this->assertEquals(array( + $this->assertEquals([ 'association' => 3, 'fieldName' => 'address', 'name' => 'address', @@ -119,9 +120,9 @@ public function testDriver() 'isOwningSide' => true, 'nullable' => false, 'strategy' => ClassMetadata::STORAGE_STRATEGY_SET, - ), $classMetadata->fieldMappings['address']); + ], $classMetadata->fieldMappings['address']); - $this->assertEquals(array( + $this->assertEquals([ 'association' => 4, 'fieldName' => 'phonenumbers', 'name' => 'phonenumbers', @@ -138,9 +139,9 @@ public function testDriver() 'isOwningSide' => true, 'nullable' => false, 'strategy' => ClassMetadata::STORAGE_STRATEGY_PUSH_ALL, - ), $classMetadata->fieldMappings['phonenumbers']); + ], $classMetadata->fieldMappings['phonenumbers']); - $this->assertEquals(array( + $this->assertEquals([ 'association' => 1, 'fieldName' => 'profile', 'name' => 'profile', @@ -149,7 +150,7 @@ public function testDriver() 'storeAs' => ClassMetadata::REFERENCE_STORE_AS_ID, 'targetDocument' => 'Documents\Profile', 'collectionClass' => null, - 'cascade' => array('remove', 'persist', 'refresh', 'merge', 'detach'), + 'cascade' => ['remove', 'persist', 'refresh', 'merge', 'detach'], 'isCascadeDetach' => true, 'isCascadeMerge' => true, 'isCascadePersist' => true, @@ -166,9 +167,9 @@ public function testDriver() 'skip' => null, 'orphanRemoval' => true, 'prime' => [], - ), $classMetadata->fieldMappings['profile']); + ], $classMetadata->fieldMappings['profile']); - $this->assertEquals(array( + $this->assertEquals([ 'association' => 1, 'fieldName' => 'account', 'name' => 'account', @@ -177,7 +178,7 @@ public function testDriver() 'storeAs' => ClassMetadata::REFERENCE_STORE_AS_DB_REF, 'targetDocument' => 'Documents\Account', 'collectionClass' => null, - 'cascade' => array('remove', 'persist', 'refresh', 'merge', 'detach'), + 'cascade' => ['remove', 'persist', 'refresh', 'merge', 'detach'], 'isCascadeDetach' => true, 'isCascadeMerge' => true, 'isCascadePersist' => true, @@ -194,9 +195,9 @@ public function testDriver() 'skip' => null, 'orphanRemoval' => false, 'prime' => [], - ), $classMetadata->fieldMappings['account']); + ], $classMetadata->fieldMappings['account']); - $this->assertEquals(array( + $this->assertEquals([ 'association' => 2, 'fieldName' => 'groups', 'name' => 'groups', @@ -205,7 +206,7 @@ public function testDriver() 'storeAs' => ClassMetadata::REFERENCE_STORE_AS_DB_REF, 'targetDocument' => 'Documents\Group', 'collectionClass' => null, - 'cascade' => array('remove', 'persist', 'refresh', 'merge', 'detach'), + 'cascade' => ['remove', 'persist', 'refresh', 'merge', 'detach'], 'isCascadeDetach' => true, 'isCascadeMerge' => true, 'isCascadePersist' => true, @@ -222,27 +223,27 @@ public function testDriver() 'skip' => null, 'orphanRemoval' => false, 'prime' => [], - ), $classMetadata->fieldMappings['groups']); + ], $classMetadata->fieldMappings['groups']); $this->assertEquals( - array( - 'postPersist' => array('doStuffOnPostPersist', 'doOtherStuffOnPostPersist'), - 'prePersist' => array('doStuffOnPrePersist'), - ), + [ + 'postPersist' => ['doStuffOnPostPersist', 'doOtherStuffOnPostPersist'], + 'prePersist' => ['doStuffOnPrePersist'], + ], $classMetadata->lifecycleCallbacks ); $this->assertEquals( - array( - "doStuffOnAlsoLoad" => array("unmappedField"), - ), + [ + 'doStuffOnAlsoLoad' => ['unmappedField'], + ], $classMetadata->alsoLoadMethods ); $classMetadata = new ClassMetadata('TestDocuments\EmbeddedDocument'); $this->driver->loadMetadataForClass('TestDocuments\EmbeddedDocument', $classMetadata); - $this->assertEquals(array( + $this->assertEquals([ 'fieldName' => 'name', 'name' => 'name', 'type' => 'string', @@ -255,12 +256,12 @@ public function testDriver() 'isOwningSide' => true, 'nullable' => false, 'strategy' => ClassMetadata::STORAGE_STRATEGY_SET, - ), $classMetadata->fieldMappings['name']); + ], $classMetadata->fieldMappings['name']); $classMetadata = new ClassMetadata('TestDocuments\QueryResultDocument'); $this->driver->loadMetadataForClass('TestDocuments\QueryResultDocument', $classMetadata); - $this->assertEquals(array( + $this->assertEquals([ 'fieldName' => 'name', 'name' => 'name', 'type' => 'string', @@ -273,9 +274,9 @@ public function testDriver() 'isOwningSide' => true, 'nullable' => false, 'strategy' => ClassMetadata::STORAGE_STRATEGY_SET, - ), $classMetadata->fieldMappings['name']); + ], $classMetadata->fieldMappings['name']); - $this->assertEquals(array( + $this->assertEquals([ 'fieldName' => 'count', 'name' => 'count', 'type' => 'integer', @@ -288,7 +289,7 @@ public function testDriver() 'isOwningSide' => true, 'nullable' => false, 'strategy' => ClassMetadata::STORAGE_STRATEGY_SET, - ), $classMetadata->fieldMappings['count']); + ], $classMetadata->fieldMappings['count']); } public function testPartialFilterExpressions() diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Mapping/Driver/XmlDriverTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Mapping/Driver/XmlDriverTest.php index fbcceb1a21..d3945fe205 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Mapping/Driver/XmlDriverTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Mapping/Driver/XmlDriverTest.php @@ -1,9 +1,11 @@ driver->loadMetadataForClass('TestDocuments\UserCustomIdGenerator', $classMetadata); - $this->assertEquals(array( + $this->assertEquals([ 'fieldName' => 'id', 'strategy' => 'custom', - 'options' => array( + 'options' => [ 'class' => 'TestDocuments\CustomIdGenerator', - 'someOption' => 'some-option' - ), + 'someOption' => 'some-option', + ], 'id' => true, 'name' => '_id', 'type' => 'custom_id', @@ -33,8 +35,8 @@ public function testDriverShouldReturnOptionsForCustomIdGenerator() 'isCascadeRemove' => false, 'isInverseSide' => false, 'isOwningSide' => true, - 'nullable' => false - ), $classMetadata->fieldMappings['id']); + 'nullable' => false, + ], $classMetadata->fieldMappings['id']); } public function testDriverShouldParseNonStringAttributes() diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Mapping/Driver/fixtures/EmbeddedDocument.php b/tests/Doctrine/ODM/MongoDB/Tests/Mapping/Driver/fixtures/EmbeddedDocument.php index 5c4934fef3..23985adb6b 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Mapping/Driver/fixtures/EmbeddedDocument.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Mapping/Driver/fixtures/EmbeddedDocument.php @@ -1,5 +1,7 @@ phonenumbers = new \Doctrine\Common\Collections\ArrayCollection(); - $this->groups = array(); + $this->phonenumbers = new ArrayCollection(); + $this->groups = []; $this->createdAt = new \DateTime(); } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Mapping/ShardKeyInheritanceMappingTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Mapping/ShardKeyInheritanceMappingTest.php index 7476829970..df8d8f7696 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Mapping/ShardKeyInheritanceMappingTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Mapping/ShardKeyInheritanceMappingTest.php @@ -1,5 +1,7 @@ factory->getMetadataFor(ShardedSubclass::class); $this->assertTrue($class->isSharded()); - $this->assertEquals(array('keys' => array('_id' => 1), 'options' => array()), $class->getShardKey()); + $this->assertEquals(['keys' => ['_id' => 1], 'options' => []], $class->getShardKey()); } public function testShardKeySingleCollectionInheritance() @@ -33,7 +35,7 @@ public function testShardKeySingleCollectionInheritance() $class = $this->factory->getMetadataFor(ShardedSingleCollInheritance2::class); $this->assertTrue($class->isSharded()); - $this->assertEquals(array('keys' => array('_id' => 1), 'options' => array()), $class->getShardKey()); + $this->assertEquals(['keys' => ['_id' => 1], 'options' => []], $class->getShardKey()); } /** @@ -49,7 +51,7 @@ public function testShardKeyCollectionPerClassInheritance() $class = $this->factory->getMetadataFor(ShardedCollectionPerClass2::class); $this->assertTrue($class->isSharded()); - $this->assertEquals(array('keys' => array('_id' => 1), 'options' => array()), $class->getShardKey()); + $this->assertEquals(['keys' => ['_id' => 1], 'options' => []], $class->getShardKey()); } public function testShardKeyCollectionPerClassInheritanceOverriding() @@ -57,7 +59,7 @@ public function testShardKeyCollectionPerClassInheritanceOverriding() $class = $this->factory->getMetadataFor(ShardedCollectionPerClass3::class); $this->assertTrue($class->isSharded()); - $this->assertEquals(array('keys' => array('_id' => 'hashed'), 'options' => array()), $class->getShardKey()); + $this->assertEquals(['keys' => ['_id' => 'hashed'], 'options' => []], $class->getShardKey()); } } @@ -94,14 +96,16 @@ class ShardedSingleCollInheritance1 * @ODM\Document */ class ShardedSingleCollInheritance2 extends ShardedSingleCollInheritance1 -{} +{ +} /** * @ODM\Document * @ODM\ShardKey(keys={"_id"="hashed"}) */ class ShardedSingleCollInheritance3 extends ShardedSingleCollInheritance1 -{} +{ +} /** * @ODM\Document @@ -118,11 +122,13 @@ class ShardedCollectionPerClass1 * @ODM\Document */ class ShardedCollectionPerClass2 extends ShardedCollectionPerClass1 -{} +{ +} /** * @ODM\Document * @ODM\ShardKey(keys={"_id"="hashed"}) */ class ShardedCollectionPerClass3 extends ShardedCollectionPerClass1 -{} +{ +} diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Mapping/Symfony/AbstractDriverTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Mapping/Symfony/AbstractDriverTest.php index b028eab87d..a1c4a5b4f4 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Mapping/Symfony/AbstractDriverTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Mapping/Symfony/AbstractDriverTest.php @@ -1,8 +1,16 @@ getDriver(array( + $driver = $this->getDriver([ 'MyNamespace\MySubnamespace\DocumentFoo' => 'foo', 'MyNamespace\MySubnamespace\Document' => $this->dir, - )); + ]); - touch($filename = $this->dir.'/Foo'.$this->getFileExtension()); + touch($filename = $this->dir . '/Foo' . $this->getFileExtension()); $this->assertEquals($filename, $driver->getLocator()->findMappingFile('MyNamespace\MySubnamespace\Document\Foo')); } public function testFindMappingFileInSubnamespace() { - $driver = $this->getDriver(array( + $driver = $this->getDriver([ 'MyNamespace\MySubnamespace\Document' => $this->dir, - )); + ]); - touch($filename = $this->dir.'/Foo.Bar'.$this->getFileExtension()); + touch($filename = $this->dir . '/Foo.Bar' . $this->getFileExtension()); $this->assertEquals($filename, $driver->getLocator()->findMappingFile('MyNamespace\MySubnamespace\Document\Foo\Bar')); } public function testFindMappingFileNamespacedFoundFileNotFound() { - $this->expectException(\Doctrine\Common\Persistence\Mapping\MappingException::class); - $this->expectExceptionMessage("No mapping file found named"); + $this->expectException(MappingException::class); + $this->expectExceptionMessage('No mapping file found named'); - $driver = $this->getDriver(array( + $driver = $this->getDriver([ 'MyNamespace\MySubnamespace\Document' => $this->dir, - )); + ]); $driver->getLocator()->findMappingFile('MyNamespace\MySubnamespace\Document\Foo'); } public function testFindMappingNamespaceNotFound() { - $this->expectException(\Doctrine\Common\Persistence\Mapping\MappingException::class); - $this->expectExceptionMessage("No mapping file found named 'Foo".$this->getFileExtension()."' for class 'MyOtherNamespace\MySubnamespace\Document\Foo'."); + $this->expectException(MappingException::class); + $this->expectExceptionMessage("No mapping file found named 'Foo" . $this->getFileExtension() . "' for class 'MyOtherNamespace\MySubnamespace\Document\Foo'."); - $driver = $this->getDriver(array( + $driver = $this->getDriver([ 'MyNamespace\MySubnamespace\Document' => $this->dir, - )); + ]); $driver->getLocator()->findMappingFile('MyOtherNamespace\MySubnamespace\Document\Foo'); } protected function setUp() { - $this->dir = sys_get_temp_dir().'/abstract_driver_test'; + $this->dir = sys_get_temp_dir() . '/abstract_driver_test'; @mkdir($this->dir, 0775, true); } @@ -66,9 +74,9 @@ protected function tearDown() foreach ($iterator as $path) { if ($path->isDir()) { - @rmdir($path); + @rmdir((string) $path); } else { - @unlink($path); + @unlink((string) $path); } } @@ -76,7 +84,7 @@ protected function tearDown() } abstract protected function getFileExtension(); - abstract protected function getDriver(array $paths = array()); + abstract protected function getDriver(array $paths = []); private function setField($obj, $field, $value) { @@ -85,7 +93,7 @@ private function setField($obj, $field, $value) $ref->setValue($obj, $value); } - private function invoke($obj, $method, array $args = array()) + private function invoke($obj, $method, array $args = []) { $ref = new \ReflectionMethod($obj, $method); $ref->setAccessible(true); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Mapping/Symfony/XmlDriverTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Mapping/Symfony/XmlDriverTest.php index dd0fd0c3b2..6b1d04b9bf 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Mapping/Symfony/XmlDriverTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Mapping/Symfony/XmlDriverTest.php @@ -1,8 +1,11 @@ assertTrue($class->isSharded()); $shardKey = $class->getShardKey(); - $this->assertSame(array('unique' => true, 'numInitialChunks' => 4096), $shardKey['options']); - $this->assertSame(array('_id' => 1), $shardKey['keys']); + $this->assertSame(['unique' => true, 'numInitialChunks' => 4096], $shardKey['options']); + $this->assertSame(['_id' => 1], $shardKey['keys']); } public function testGetAssociationCollectionClass() diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Mocks/ClassMetadataMock.php b/tests/Doctrine/ODM/MongoDB/Tests/Mocks/ClassMetadataMock.php index 0232758414..609da45e9e 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Mocks/ClassMetadataMock.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Mocks/ClassMetadataMock.php @@ -1,7 +1,11 @@ inserts[] = $document; $id = $this->identityColumnValueCounter++; - $this->postInsertIds[$id] = array($id, $document); + $this->postInsertIds[$id] = [$id, $document]; return $id; } @@ -28,7 +32,7 @@ public function addInsert($document) { $this->inserts[] = $document; $id = $this->identityColumnValueCounter++; - $this->postInsertIds[$id] = array($id, $document); + $this->postInsertIds[$id] = [$id, $document]; return $id; } @@ -36,19 +40,19 @@ public function addUpsert($document) { $this->upserts[] = $document; $id = $this->identityColumnValueCounter++; - $this->postInsertIds[$id] = array($id, $document); + $this->postInsertIds[$id] = [$id, $document]; return $id; } - public function executeInserts(array $options = array()) + public function executeInserts(array $options = []) { } - public function executeUpserts(array $options = array()) + public function executeUpserts(array $options = []) { } - public function update($document, array $options = array()) + public function update($document, array $options = []) { $this->updates[] = $document; } @@ -58,7 +62,7 @@ public function exists($document) $this->existsCalled = true; } - public function delete($document, array $options = array()) + public function delete($document, array $options = []) { $this->deletes[] = $document; } @@ -87,9 +91,9 @@ public function reset() { $this->existsCalled = false; $this->identityColumnValueCounter = 1; - $this->inserts = array(); - $this->updates = array(); - $this->deletes = array(); + $this->inserts = []; + $this->updates = []; + $this->deletes = []; } public function isExistsCalled() diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Mocks/ExceptionThrowingListenerMock.php b/tests/Doctrine/ODM/MongoDB/Tests/Mocks/ExceptionThrowingListenerMock.php index 7a3f8724c5..4f3a72a29f 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Mocks/ExceptionThrowingListenerMock.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Mocks/ExceptionThrowingListenerMock.php @@ -1,18 +1,17 @@ _persisterMock[$documentName] ?? parent::getDocumentPersister($documentName); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/MongoCollectionTest.php b/tests/Doctrine/ODM/MongoDB/Tests/MongoCollectionTest.php index a4906d8d9b..d406668a59 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/MongoCollectionTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/MongoCollectionTest.php @@ -1,12 +1,14 @@ dm->getDocumentCollection('Documents\File'); - $this->assertNull($mongoCollection->findOne(array('_id' => 'definitelynotanid'))); + $this->assertNull($mongoCollection->findOne(['_id' => 'definitelynotanid'])); } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Performance/HydrationPerformanceTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Performance/HydrationPerformanceTest.php index e050339140..9b44957018 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Performance/HydrationPerformanceTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Performance/HydrationPerformanceTest.php @@ -1,13 +1,20 @@ status = 'user'; $user->username = 'user' . $i; $user->name = 'Mr.Smith-' . $i; $this->dm->persist($user); - if (($i % $batchSize) == 0) { + if (($i % $batchSize) === 0) { $this->dm->flush(); $this->dm->clear(); } @@ -31,16 +38,14 @@ public function testHydrationPerformance() gc_collect_cycles(); - echo "Memory usage before: " . (memory_get_usage() / 1024) . " KB" . PHP_EOL; + echo 'Memory usage before: ' . (memory_get_usage() / 1024) . ' KB' . PHP_EOL; - $users = $this->dm->getRepository('Documents\CmsUser')->findAll(); - foreach ($users as $user) { - } + $this->dm->getRepository('Documents\CmsUser')->findAll(); $this->dm->clear(); gc_collect_cycles(); - echo "Memory usage after: " . (memory_get_usage() / 1024) . " KB" . PHP_EOL; + echo 'Memory usage after: ' . (memory_get_usage() / 1024) . ' KB' . PHP_EOL; $e = microtime(true); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Performance/InsertPerformanceTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Performance/InsertPerformanceTest.php index c559fe9d76..9f72a97834 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Performance/InsertPerformanceTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Performance/InsertPerformanceTest.php @@ -1,13 +1,20 @@ status = 'user'; $user->username = 'user' . $i; $user->name = 'Mr.Smith-' . $i; $this->dm->persist($user); - if (($i % $batchSize) == 0) { + if (($i % $batchSize) === 0) { $this->dm->flush(); $this->dm->clear(); } } gc_collect_cycles(); - echo "Memory usage after: " . (memory_get_usage() / 1024) . " KB" . PHP_EOL; + echo 'Memory usage after: ' . (memory_get_usage() / 1024) . ' KB' . PHP_EOL; $e = microtime(true); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Performance/MemoryUsageTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Performance/MemoryUsageTest.php index 3b782e622b..dcdddc8f4a 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Performance/MemoryUsageTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Performance/MemoryUsageTest.php @@ -1,21 +1,34 @@ phonenumber = '12345'; @@ -46,7 +59,7 @@ public function testMemoryUsage() private function formatMemory($size) { - $unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb'); + $unit = ['b', 'kb', 'mb', 'gb', 'tb', 'pb']; return round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . ' ' . $unit[$i]; } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Performance/UnitOfWorkPerformanceTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Performance/UnitOfWorkPerformanceTest.php index 2884dd777c..fe28370e05 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Performance/UnitOfWorkPerformanceTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Performance/UnitOfWorkPerformanceTest.php @@ -1,22 +1,28 @@ status = 'user'; $user->username = 'user' . $i; $user->name = 'Mr.Smith-' . $i; @@ -35,6 +41,6 @@ public function testComputeChanges() $this->dm->flush(); $e = microtime(true); - echo 'Compute ChangeSet '.$n.' objects in ' . ($e - $s) . ' seconds' . PHP_EOL; + echo 'Compute ChangeSet ' . $n . ' objects in ' . ($e - $s) . ' seconds' . PHP_EOL; } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/PersistentCollection/CollNoReturnType.php b/tests/Doctrine/ODM/MongoDB/Tests/PersistentCollection/CollNoReturnType.php index e622f60a2e..f74ec815b1 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/PersistentCollection/CollNoReturnType.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/PersistentCollection/CollNoReturnType.php @@ -1,10 +1,11 @@ -generator = new DefaultPersistentCollectionGenerator( - $this->dm->getConfiguration()->getPersistentCollectionDir(), - $this->dm->getConfiguration()->getPersistentCollectionNamespace() - ); - } - - public function testNoReturnTypes() - { - $class = $this->generator->loadClass(CollNoReturnType::class, Configuration::AUTOGENERATE_EVAL); - $coll = new $class(new CollNoReturnType(), $this->dm, $this->uow); - $this->assertInstanceOf(CollNoReturnType::class, $coll); - } - - public function testWithReturnType() - { - $class = $this->generator->loadClass(CollWithReturnType::class, Configuration::AUTOGENERATE_EVAL); - $coll = new $class(new CollWithReturnType(), $this->dm, $this->uow); - $this->assertInstanceOf(CollWithReturnType::class, $coll); - } - - public function testWithNullableReturnType() - { - if (PHP_VERSION_ID < 70100) { - $this->markTestSkipped(sprintf('%s requires at least PHP 7.1', __METHOD__)); - } - - $class = $this->generator->loadClass(CollWithNullableReturnType::class, Configuration::AUTOGENERATE_EVAL); - $coll = new $class(new CollWithNullableReturnType(), $this->dm, $this->uow); - $this->assertInstanceOf(CollWithNullableReturnType::class, $coll); - } -} +generator = new DefaultPersistentCollectionGenerator( + $this->dm->getConfiguration()->getPersistentCollectionDir(), + $this->dm->getConfiguration()->getPersistentCollectionNamespace() + ); + } + + public function testNoReturnTypes() + { + $class = $this->generator->loadClass(CollNoReturnType::class, Configuration::AUTOGENERATE_EVAL); + $coll = new $class(new CollNoReturnType(), $this->dm, $this->uow); + $this->assertInstanceOf(CollNoReturnType::class, $coll); + } + + public function testWithReturnType() + { + $class = $this->generator->loadClass(CollWithReturnType::class, Configuration::AUTOGENERATE_EVAL); + $coll = new $class(new CollWithReturnType(), $this->dm, $this->uow); + $this->assertInstanceOf(CollWithReturnType::class, $coll); + } + + public function testWithNullableReturnType() + { + if (PHP_VERSION_ID < 70100) { + $this->markTestSkipped(sprintf('%s requires at least PHP 7.1', __METHOD__)); + } + + $class = $this->generator->loadClass(CollWithNullableReturnType::class, Configuration::AUTOGENERATE_EVAL); + $coll = new $class(new CollWithNullableReturnType(), $this->dm, $this->uow); + $this->assertInstanceOf(CollWithNullableReturnType::class, $coll); + } +} diff --git a/tests/Doctrine/ODM/MongoDB/Tests/PersistentCollectionTest.php b/tests/Doctrine/ODM/MongoDB/Tests/PersistentCollectionTest.php index 04ffb55374..7f6c0d510d 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/PersistentCollectionTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/PersistentCollectionTest.php @@ -1,16 +1,24 @@ getMockCollection(); $collection->expects($this->once()) ->method('slice') @@ -35,7 +43,7 @@ public function testExceptionForGetTypeClassWithoutDocumentManager() /** @var PersistentCollection $unserialized */ $unserialized = unserialize($serialized); - $unserialized->setOwner($owner, array('targetDocument' => '\stdClass')); + $unserialized->setOwner($owner, ['targetDocument' => '\stdClass']); $unserialized->getTypeClass(); } @@ -63,7 +71,7 @@ public function testGetTypeClassWorksAfterUnserialization() /** @var PersistentCollection $unserialized */ $unserialized = unserialize($serialized); - $unserialized->setOwner(new \Documents\User(), $this->dm->getClassMetadata('Documents\\User')->getFieldMapping('phonebooks')); + $unserialized->setOwner(new User(), $this->dm->getClassMetadata('Documents\\User')->getFieldMapping('phonebooks')); $unserialized->setDocumentManager($this->dm); $this->assertInstanceOf(ClassMetadata::class, $unserialized->getTypeClass()); } @@ -71,7 +79,6 @@ public function testGetTypeClassWorksAfterUnserialization() /** * @param array $expected * @param array $snapshot - * @param \Closure $callback * * @dataProvider dataGetDeletedDocuments */ @@ -93,44 +100,58 @@ public static function dataGetDeletedDocuments() $one = new \stdClass(); $two = new \stdClass(); - return array( - 'sameItems' => array( - array(), - array($one), - function ($collection) {} - ), - 'added' => array( - array(), - array($one), - function ($collection) use ($two) { $collection->add($two); } - ), - 'removed' => array( - array($one), - array($one, $two), - function ($collection) use ($one) { $collection->removeElement($one); } - ), - 'replaced' => array( - array($one), - array($one), - function ($collection) use ($one, $two) { $collection->removeElement($one); $collection->add($two); } - ), - 'removed2' => array( - array($two), - array($one, $two), - function ($collection) use ($two) { $collection->removeElement($two); } - ), - 'orderChanged' => array( - array(), - array($one, $two), - function ($collection) use ($one, $two) { $collection->removeElement($one); $collection->removeElement($two); $collection->add($two); $collection->add($one); } - ), - ); + return [ + 'sameItems' => [ + [], + [$one], + function ($collection) { + }, + ], + 'added' => [ + [], + [$one], + function ($collection) use ($two) { + $collection->add($two); + }, + ], + 'removed' => [ + [$one], + [$one, $two], + function ($collection) use ($one) { + $collection->removeElement($one); + }, + ], + 'replaced' => [ + [$one], + [$one], + function ($collection) use ($one, $two) { + $collection->removeElement($one); + $collection->add($two); + }, + ], + 'removed2' => [ + [$two], + [$one, $two], + function ($collection) use ($two) { + $collection->removeElement($two); + }, + ], + 'orderChanged' => [ + [], + [$one, $two], + function ($collection) use ($one, $two) { + $collection->removeElement($one); + $collection->removeElement($two); + $collection->add($two); + $collection->add($one); + }, + ], + ]; } /** * @param array $expected * @param array $snapshot - * @param \Closure $callback * * @dataProvider dataGetInsertedDocuments */ @@ -152,28 +173,39 @@ public static function dataGetInsertedDocuments() $one = new \stdClass(); $two = new \stdClass(); - return array( - 'sameItems' => array( - array(), - array($one), - function ($collection) {} - ), - 'added' => array( - array($two), - array($one), - function ($collection) use ($two) { $collection->add($two); } - ), - 'replaced' => array( - array($two), - array($one), - function ($collection) use ($one, $two) { $collection->removeElement($one); $collection->add($two); } - ), - 'orderChanged' => array( - array(), - array($one, $two), - function ($collection) use ($one, $two) { $collection->removeElement($one); $collection->removeElement($two); $collection->add($two); $collection->add($one); } - ), - ); + return [ + 'sameItems' => [ + [], + [$one], + function ($collection) { + }, + ], + 'added' => [ + [$two], + [$one], + function ($collection) use ($two) { + $collection->add($two); + }, + ], + 'replaced' => [ + [$two], + [$one], + function ($collection) use ($one, $two) { + $collection->removeElement($one); + $collection->add($two); + }, + ], + 'orderChanged' => [ + [], + [$one, $two], + function ($collection) use ($one, $two) { + $collection->removeElement($one); + $collection->removeElement($two); + $collection->add($two); + $collection->add($one); + }, + ], + ]; } public function testOffsetExistsIsForwarded() @@ -243,7 +275,7 @@ public function testIsEmptyUsesCountWhenCollectionIsNotInitialized() } /** - * @return \Doctrine\ODM\MongoDB\DocumentManager + * @return DocumentManager */ private function getMockDocumentManager() { @@ -251,7 +283,7 @@ private function getMockDocumentManager() } /** - * @return \Doctrine\ODM\MongoDB\UnitOfWork + * @return UnitOfWork */ private function getMockUnitOfWork() { @@ -259,7 +291,7 @@ private function getMockUnitOfWork() } /** - * @return \Doctrine\Common\Collections\Collection + * @return Collection */ private function getMockCollection() { diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Persisters/DocumentPersisterFilterTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Persisters/DocumentPersisterFilterTest.php index af674bc945..ef92e6d797 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Persisters/DocumentPersisterFilterTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Persisters/DocumentPersisterFilterTest.php @@ -1,8 +1,12 @@ setParameter('field', 'username'); $testFilter->setParameter('value', 'Tim'); - $preparedQuery = array('username' => 'Toby'); + $preparedQuery = ['username' => 'Toby']; - $expectedCriteria = array('$and' => array( - array('username' => 'Toby'), - array('username' => 'Tim'), - )); + $expectedCriteria = [ + '$and' => [ + ['username' => 'Toby'], + ['username' => 'Tim'], + ], + ]; $this->assertSame($expectedCriteria, $persister->addFilterToPreparedQuery($preparedQuery)); } public function testFilterCrieriaShouldAndWithMappingCriteriaOwningSide() { - $blogPost = new \Documents\BlogPost('Roger'); - $blogPost->addComment(new \Documents\Comment('comment by normal user', new \DateTime(), false)); - $blogPost->addComment(new \Documents\Comment('comment by admin', new \DateTime(), true)); + $blogPost = new BlogPost('Roger'); + $blogPost->addComment(new Comment('comment by normal user', new \DateTime(), false)); + $blogPost->addComment(new Comment('comment by admin', new \DateTime(), true)); $this->dm->persist($blogPost); $this->dm->flush(); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Persisters/DocumentPersisterGetShardKeyQueryTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Persisters/DocumentPersisterGetShardKeyQueryTest.php index 70f416c9c0..1d31ed15ee 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Persisters/DocumentPersisterGetShardKeyQueryTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Persisters/DocumentPersisterGetShardKeyQueryTest.php @@ -1,10 +1,17 @@ setAccessible(true); $this->assertSame( - array('int' => $o->int, 'string' => $o->string, 'bool' => $o->bool, 'float' => $o->float), + ['int' => $o->int, 'string' => $o->string, 'bool' => $o->bool, 'float' => $o->float], $method->invoke($persister, $o) ); } @@ -42,13 +49,13 @@ public function testGetShardKeyQueryObjects() $method->setAccessible(true); $shardKeyQuery = $method->invoke($persister, $o); - $this->assertInstanceOf(\MongoDB\BSON\ObjectId::class, $shardKeyQuery['oid']); + $this->assertInstanceOf(ObjectId::class, $shardKeyQuery['oid']); $this->assertSame($o->oid, (string) $shardKeyQuery['oid']); - $this->assertInstanceOf(\MongoDB\BSON\Binary::class, $shardKeyQuery['bin']); + $this->assertInstanceOf(Binary::class, $shardKeyQuery['bin']); $this->assertSame($o->bin, $shardKeyQuery['bin']->getData()); - $this->assertInstanceOf(\MongoDB\BSON\UTCDateTime::class, $shardKeyQuery['date']); + $this->assertInstanceOf(UTCDateTime::class, $shardKeyQuery['date']); $this->assertEquals($o->date->getTimestamp(), $shardKeyQuery['date']->toDateTime()->getTimestamp()); $this->assertSame( @@ -60,7 +67,7 @@ public function testGetShardKeyQueryObjects() public function testShardById() { $o = new ShardedById(); - $o->identifier = new \MongoDB\BSON\ObjectId(); + $o->identifier = new ObjectId(); /** @var DocumentPersister $persister */ $persister = $this->uow->getDocumentPersister(get_class($o)); @@ -69,15 +76,15 @@ public function testShardById() $method->setAccessible(true); $shardKeyQuery = $method->invoke($persister, $o); - $this->assertSame(array('_id' => $o->identifier), $shardKeyQuery); + $this->assertSame(['_id' => $o->identifier], $shardKeyQuery); } public function testShardByReference() { $o = new ShardedByReferenceOne(); - $userId = new \MongoDB\BSON\ObjectId(); - $o->reference = new \Documents\User(); + $userId = new ObjectId(); + $o->reference = new User(); $o->reference->setId($userId); $this->dm->persist($o->reference); @@ -89,7 +96,7 @@ public function testShardByReference() $method->setAccessible(true); $shardKeyQuery = $method->invoke($persister, $o); - $this->assertSame(array('reference.$id' => $userId), $shardKeyQuery); + $this->assertSame(['reference.$id' => $userId], $shardKeyQuery); } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Persisters/PersistenceBuilderTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Persisters/PersistenceBuilderTest.php index 53c80c587b..92d1daec0f 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Persisters/PersistenceBuilderTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Persisters/PersistenceBuilderTest.php @@ -1,15 +1,21 @@ uow->computeChangeSets(); /** - * @var \Doctrine\ODM\MongoDB\Query\Builder $qb + * @var Builder $qb */ $qb = $this->dm->createQueryBuilder('Documents\Functional\SameCollection1'); $qb->updateOne() @@ -60,11 +66,11 @@ public function testFindWithOrOnCollectionWithDiscriminatorMap() $sameCollection1 = new SameCollection1(); $sameCollection2a = new SameCollection2(); $sameCollection2b = new SameCollection2(); - $ids = array( + $ids = [ '4f28aa84acee413889000001', '4f28aa84acee41388900002a', - '4f28aa84acee41388900002b' - ); + '4f28aa84acee41388900002b', + ]; $sameCollection1->id = $ids[0]; $sameCollection1->name = 'First entry in SameCollection1'; @@ -87,7 +93,7 @@ public function testFindWithOrOnCollectionWithDiscriminatorMap() $this->uow->computeChangeSets(); /** - * @var \Doctrine\ODM\MongoDB\Query\Builder $qb + * @var Builder $qb */ $qb = $this->dm->createQueryBuilder(SameCollection2::class); $qb @@ -136,12 +142,12 @@ public function testPrepareInsertDataWithCreatedReferenceOne() $this->dm->persist($comment); $this->uow->computeChangeSets(); - $expectedData = array( - 'article' => array( - '$id' => new \MongoDB\BSON\ObjectId($article->id), - '$ref' => 'CmsArticle' - ) - ); + $expectedData = [ + 'article' => [ + '$id' => new ObjectId($article->id), + '$ref' => 'CmsArticle', + ], + ]; $this->assertDocumentInsertData($expectedData, $this->pb->prepareInsertData($comment)); } @@ -160,12 +166,12 @@ public function testPrepareInsertDataWithFetchedReferenceOne() $this->dm->persist($comment); $this->uow->computeChangeSets(); - $expectedData = array( - 'article' => array( - '$id' => new \MongoDB\BSON\ObjectId($article->id), - '$ref' => 'CmsArticle' - ) - ); + $expectedData = [ + 'article' => [ + '$id' => new ObjectId($article->id), + '$ref' => 'CmsArticle', + ], + ]; $this->assertDocumentInsertData($expectedData, $this->pb->prepareInsertData($comment)); } @@ -186,17 +192,17 @@ public function testPrepareUpsertData() $this->dm->persist($comment); $this->uow->computeChangeSets(); - $expectedData = array( - '$set' => array( + $expectedData = [ + '$set' => [ 'topic' => 'test', 'text' => 'text', - 'article' => array( - '$id' => new \MongoDB\BSON\ObjectId($article->id), - '$ref' => 'CmsArticle' - ), - '_id' => new \MongoDB\BSON\ObjectId($comment->id), - ) - ); + 'article' => [ + '$id' => new ObjectId($article->id), + '$ref' => 'CmsArticle', + ], + '_id' => new ObjectId($comment->id), + ], + ]; $this->assertEquals($expectedData, $this->pb->prepareUpsertData($comment)); } @@ -218,22 +224,22 @@ public function testPrepareInsertData($document, array $expectedData) */ public function getDocumentsAndExpectedData() { - return array( - array(new ConfigurableProduct('Test Product'), array('name' => 'Test Product')), - array(new Currency('USD', 1), array('name' => 'USD', 'multiplier' => 1)), - ); + return [ + [new ConfigurableProduct('Test Product'), ['name' => 'Test Product']], + [new Currency('USD', 1), ['name' => 'USD', 'multiplier' => 1]], + ]; } - private function assertDocumentInsertData(array $expectedData, array $preparedData = null) + private function assertDocumentInsertData(array $expectedData, ?array $preparedData = null) { foreach ($preparedData as $key => $value) { if ($key === '_id') { - $this->assertInstanceOf(\MongoDB\BSON\ObjectId::class, $value); + $this->assertInstanceOf(ObjectId::class, $value); continue; } $this->assertEquals($expectedData[$key], $value); } - if ( ! isset($preparedData['_id'])) { + if (! isset($preparedData['_id'])) { $this->fail('insert data should always contain id'); } unset($preparedData['_id']); @@ -260,11 +266,11 @@ public function testAdvancedQueriesOnReferenceWithDiscriminatorMap() $commentId = (string) $comment->id; /** - * @var \Doctrine\ODM\MongoDB\Query\Builder $qb + * @var Builder $qb */ $qb = $this->dm->createQueryBuilder('Documents\CmsComment'); $qb - ->field('article.id')->in(array($articleId)); + ->field('article.id')->in([$articleId]); $query = $qb->getQuery(); $results = $query->execute(); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Query/BuilderTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Query/BuilderTest.php index 81ccf10d91..936156b186 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Query/BuilderTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Query/BuilderTest.php @@ -1,5 +1,7 @@ field('featureFull')->references($f) ->getQuery()->debug(); - $this->assertEquals([ 'featureFull.$id' => new \MongoDB\BSON\ObjectId($f->id) ], $q1['query']); + $this->assertEquals([ 'featureFull.$id' => new ObjectId($f->id) ], $q1['query']); $q2 = $this->dm->createQueryBuilder(ParentClass::class) ->field('featureSimple')->references($f) ->getQuery()->debug(); - $this->assertEquals([ 'featureSimple' => new \MongoDB\BSON\ObjectId($f->id) ], $q2['query']); + $this->assertEquals([ 'featureSimple' => new ObjectId($f->id) ], $q2['query']); $q3 = $this->dm->createQueryBuilder(ParentClass::class) ->field('featurePartial')->references($f) @@ -49,7 +51,7 @@ public function testReferencesGoesThroughDiscriminatorMap() $this->assertEquals( [ - 'featurePartial.$id' => new \MongoDB\BSON\ObjectId($f->id), + 'featurePartial.$id' => new ObjectId($f->id), 'featurePartial.$ref' => 'Feature', ], $q3['query'] @@ -93,13 +95,13 @@ public function testIncludesReferenceToGoesThroughDiscriminatorMap() ->field('featureFullMany')->includesReferenceTo($f) ->getQuery()->debug(); - $this->assertEquals([ 'featureFullMany' => [ '$elemMatch' => [ '$id' => new \MongoDB\BSON\ObjectId($f->id) ] ] ], $q1['query']); + $this->assertEquals([ 'featureFullMany' => [ '$elemMatch' => [ '$id' => new ObjectId($f->id) ] ] ], $q1['query']); $q2 = $this->dm->createQueryBuilder(ParentClass::class) ->field('featureSimpleMany')->includesReferenceTo($f) ->getQuery()->debug(); - $this->assertEquals([ 'featureSimpleMany' => new \MongoDB\BSON\ObjectId($f->id) ], $q2['query']); + $this->assertEquals([ 'featureSimpleMany' => new ObjectId($f->id) ], $q2['query']); $q3 = $this->dm->createQueryBuilder(ParentClass::class) ->field('featurePartialMany')->includesReferenceTo($f) @@ -109,10 +111,10 @@ public function testIncludesReferenceToGoesThroughDiscriminatorMap() [ 'featurePartialMany' => [ '$elemMatch' => [ - '$id' => new \MongoDB\BSON\ObjectId($f->id), + '$id' => new ObjectId($f->id), '$ref' => 'Feature', - ] - ] + ], + ], ], $q3['query'] ); @@ -295,10 +297,12 @@ public function testThatOrAcceptsAnotherQuery() $qb->addOr($qb->expr()->field('firstName')->equals('Kris')); $qb->addOr($qb->expr()->field('firstName')->equals('Chris')); - $this->assertEquals(['$or' => [ + $this->assertEquals([ + '$or' => [ ['firstName' => 'Kris'], - ['firstName' => 'Chris'] - ]], $qb->getQueryArray()); + ['firstName' => 'Chris'], + ], + ], $qb->getQueryArray()); } public function testThatAndAcceptsAnotherQuery() @@ -321,19 +325,23 @@ public function testThatNorAcceptsAnotherQuery() $qb->addNor($qb->expr()->field('firstName')->equals('Kris')); $qb->addNor($qb->expr()->field('firstName')->equals('Chris')); - $this->assertEquals(['$nor' => [ + $this->assertEquals([ + '$nor' => [ ['firstName' => 'Kris'], - ['firstName' => 'Chris'] - ]], $qb->getQueryArray()); + ['firstName' => 'Chris'], + ], + ], $qb->getQueryArray()); } public function testAddElemMatch() { $qb = $this->getTestQueryBuilder(); $qb->field('phonenumbers')->elemMatch($qb->expr()->field('phonenumber')->equals('6155139185')); - $expected = ['phonenumbers' => [ - '$elemMatch' => ['phonenumber' => '6155139185'] - ]]; + $expected = [ + 'phonenumbers' => [ + '$elemMatch' => ['phonenumber' => '6155139185'], + ], + ]; $this->assertEquals($expected, $qb->getQueryArray()); } @@ -344,9 +352,9 @@ public function testAddNot() $expected = [ 'username' => [ '$not' => [ - '$in' => ['boo'] - ] - ] + '$in' => ['boo'], + ], + ], ]; $this->assertEquals($expected, $qb->getQueryArray()); } @@ -355,9 +363,7 @@ public function testFindQuery() { $qb = $this->getTestQueryBuilder() ->where("function() { return this.username == 'boo' }"); - $expected = [ - '$where' => "function() { return this.username == 'boo' }" - ]; + $expected = ['$where' => "function() { return this.username == 'boo' }"]; $this->assertEquals($expected, $qb->getQueryArray()); } @@ -369,9 +375,7 @@ public function testUpsertUpdateQuery() ->field('username')->set('jwage'); $expected = [ - '$set' => [ - 'username' => 'jwage' - ] + '$set' => ['username' => 'jwage'], ]; $this->assertEquals($expected, $qb->getNewObj()); $this->assertTrue($qb->debug('upsert')); @@ -384,9 +388,7 @@ public function testMultipleUpdateQuery() ->field('username')->set('jwage'); $expected = [ - '$set' => [ - 'username' => 'jwage' - ] + '$set' => ['username' => 'jwage'], ]; $this->assertEquals($expected, $qb->getNewObj()); $this->assertTrue($qb->debug('multiple')); @@ -400,14 +402,12 @@ public function testComplexUpdateQuery() ->set('jwage') ->equals('boo'); - $expected = [ - 'username' => 'boo' - ]; + $expected = ['username' => 'boo']; $this->assertEquals($expected, $qb->getQueryArray()); - $expected = ['$set' => [ - 'username' => 'jwage' - ]]; + $expected = [ + '$set' => ['username' => 'jwage'], + ]; $this->assertEquals($expected, $qb->getNewObj()); } @@ -418,14 +418,12 @@ public function testIncUpdateQuery() ->field('hits')->inc(5) ->field('username')->equals('boo'); - $expected = [ - 'username' => 'boo' - ]; + $expected = ['username' => 'boo']; $this->assertEquals($expected, $qb->getQueryArray()); - $expected = ['$inc' => [ - 'hits' => 5 - ]]; + $expected = [ + '$inc' => ['hits' => 5], + ]; $this->assertEquals($expected, $qb->getNewObj()); } @@ -436,14 +434,12 @@ public function testUnsetField() ->field('hits')->unsetField() ->field('username')->equals('boo'); - $expected = [ - 'username' => 'boo' - ]; + $expected = ['username' => 'boo']; $this->assertEquals($expected, $qb->getQueryArray()); - $expected = ['$unset' => [ - 'hits' => 1 - ]]; + $expected = [ + '$unset' => ['hits' => 1], + ]; $this->assertEquals($expected, $qb->getNewObj()); } @@ -456,14 +452,14 @@ public function testSetOnInsert() ->field('username')->equals('boo') ->field('createDate')->setOnInsert($createDate); - $expected = [ - 'username' => 'boo' - ]; + $expected = ['username' => 'boo']; $this->assertEquals($expected, $qb->getQueryArray()); - $expected = ['$setOnInsert' => [ + $expected = [ + '$setOnInsert' => [ 'createDate' => (Type::getType('date'))->convertToDatabaseValue($createDate), - ]]; + ], + ]; $this->assertEquals($expected, $qb->getNewObj()); } @@ -478,7 +474,7 @@ public function testDateRange() 'createdAt' => [ '$gte' => Type::getType('date')->convertToDatabaseValue($start), '$lt' => Type::getType('date')->convertToDatabaseValue($end), - ] + ], ]; $this->assertEquals($expected, $qb->getQueryArray()); } @@ -809,14 +805,14 @@ public function testCurrentDateUpdateQuery($type) ->field('lastUpdated')->currentDate($type) ->field('username')->equals('boo'); - $expected = [ - 'username' => 'boo' - ]; + $expected = ['username' => 'boo']; $this->assertEquals($expected, $qb->getQueryArray()); - $expected = ['$currentDate' => [ - 'lastUpdated' => ['$type' => $type] - ]]; + $expected = [ + '$currentDate' => [ + 'lastUpdated' => ['$type' => $type], + ], + ]; $this->assertEquals($expected, $qb->getNewObj()); } @@ -824,7 +820,7 @@ public static function provideCurrentDateOptions() { return [ ['date'], - ['timestamp'] + ['timestamp'], ]; } @@ -845,14 +841,14 @@ public function testBitAndUpdateQuery() ->field('flags')->bitAnd(15) ->field('username')->equals('boo'); - $expected = [ - 'username' => 'boo' - ]; + $expected = ['username' => 'boo']; $this->assertEquals($expected, $qb->getQueryArray()); - $expected = ['$bit' => [ - 'flags' => ['and' => 15] - ]]; + $expected = [ + '$bit' => [ + 'flags' => ['and' => 15], + ], + ]; $this->assertEquals($expected, $qb->getNewObj()); } @@ -863,14 +859,14 @@ public function testBitOrUpdateQuery() ->field('flags')->bitOr(15) ->field('username')->equals('boo'); - $expected = [ - 'username' => 'boo' - ]; + $expected = ['username' => 'boo']; $this->assertEquals($expected, $qb->getQueryArray()); - $expected = ['$bit' => [ - 'flags' => ['or' => 15] - ]]; + $expected = [ + '$bit' => [ + 'flags' => ['or' => 15], + ], + ]; $this->assertEquals($expected, $qb->getNewObj()); } @@ -881,14 +877,14 @@ public function testBitXorUpdateQuery() ->field('flags')->bitXor(15) ->field('username')->equals('boo'); - $expected = [ - 'username' => 'boo' - ]; + $expected = ['username' => 'boo']; $this->assertEquals($expected, $qb->getQueryArray()); - $expected = ['$bit' => [ - 'flags' => ['xor' => 15] - ]]; + $expected = [ + '$bit' => [ + 'flags' => ['xor' => 15], + ], + ]; $this->assertEquals($expected, $qb->getNewObj()); } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Query/CriteriaMergerTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Query/CriteriaMergerTest.php index 685d4c4911..d4e286049c 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Query/CriteriaMergerTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Query/CriteriaMergerTest.php @@ -1,9 +1,12 @@ assertSame($merged, call_user_func_array(array(new CriteriaMerger(), 'merge'), $args)); + $this->assertSame($merged, call_user_func_array([new CriteriaMerger(), 'merge'], $args)); } public function provideMerge() { - return array( - 'no args' => array( - array(), - array(), - ), - 'one arg returned as-is' => array( - array(array('x' => 1)), - array('x' => 1), - ), - 'empty criteria arrays are ignored' => array( - array(array('x' => 1), array()), - array('x' => 1), - ), - 'two identical args' => array( - array(array('x' => 1), array('x' => 1)), - array('$and' => array(array('x' => 1), array('x' => 1))), - ), - 'two different args' => array( - array(array('x' => 1), array('y' => 1)), - array('$and' => array(array('x' => 1), array('y' => 1))), - ), - 'two conflicting args' => array( - array(array('x' => 1), array('x' => 2)), - array('$and' => array(array('x' => 1), array('x' => 2))), - ), - 'existing $and criteria gets nested' => array( - array(array('$and' => array(array('x' => 1))), array('x' => 1)), - array('$and' => array(array('$and' => array(array('x' => 1))), array('x' => 1))), - ), - ); + return [ + 'no args' => [ + [], + [], + ], + 'one arg returned as-is' => [ + [['x' => 1]], + ['x' => 1], + ], + 'empty criteria arrays are ignored' => [ + [['x' => 1], []], + ['x' => 1], + ], + 'two identical args' => [ + [['x' => 1], ['x' => 1]], + ['$and' => [['x' => 1], ['x' => 1]]], + ], + 'two different args' => [ + [['x' => 1], ['y' => 1]], + ['$and' => [['x' => 1], ['y' => 1]]], + ], + 'two conflicting args' => [ + [['x' => 1], ['x' => 2]], + ['$and' => [['x' => 1], ['x' => 2]]], + ], + 'existing $and criteria gets nested' => [ + [['$and' => [['x' => 1]]], ['x' => 1]], + ['$and' => [['$and' => [['x' => 1]]], ['x' => 1]]], + ], + ]; } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Query/ExprTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Query/ExprTest.php index bbe2f59774..833e947575 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Query/ExprTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Query/ExprTest.php @@ -1,15 +1,19 @@ select('id'); $query = $qb->getQuery(); - $this->assertEquals(array('_id' => 1), $query->debug('select')); + $this->assertEquals(['_id' => 1], $query->debug('select')); } public function testInIsPrepared() { - $ids = array('4f28aa84acee41388900000a'); + $ids = ['4f28aa84acee41388900000a']; $qb = $this->dm->createQueryBuilder('Documents\User') ->field('groups.id')->in($ids) @@ -30,13 +34,13 @@ public function testInIsPrepared() $query = $qb->getQuery(); $debug = $query->debug('query'); - $this->assertInstanceOf(\MongoDB\BSON\ObjectId::class, $debug['groups.$id']['$in'][0]); + $this->assertInstanceOf(ObjectId::class, $debug['groups.$id']['$in'][0]); $this->assertEquals($ids[0], (string) $debug['groups.$id']['$in'][0]); } public function testAllIsPrepared() { - $ids = array('4f28aa84acee41388900000a'); + $ids = ['4f28aa84acee41388900000a']; $qb = $this->dm->createQueryBuilder('Documents\User') ->field('groups.id')->all($ids) @@ -44,7 +48,7 @@ public function testAllIsPrepared() $query = $qb->getQuery(); $debug = $query->debug('query'); - $this->assertInstanceOf(\MongoDB\BSON\ObjectId::class, $debug['groups.$id']['$all'][0]); + $this->assertInstanceOf(ObjectId::class, $debug['groups.$id']['$all'][0]); $this->assertEquals($ids[0], (string) $debug['groups.$id']['$all'][0]); } @@ -58,13 +62,13 @@ public function testNotEqualIsPrepared() $query = $qb->getQuery(); $debug = $query->debug('query'); - $this->assertInstanceOf(\MongoDB\BSON\ObjectId::class, $debug['groups.$id']['$ne']); + $this->assertInstanceOf(ObjectId::class, $debug['groups.$id']['$ne']); $this->assertEquals($id, (string) $debug['groups.$id']['$ne']); } public function testNotInIsPrepared() { - $ids = array('4f28aa84acee41388900000a'); + $ids = ['4f28aa84acee41388900000a']; $qb = $this->dm->createQueryBuilder('Documents\User') ->field('groups.id')->notIn($ids) @@ -72,13 +76,13 @@ public function testNotInIsPrepared() $query = $qb->getQuery(); $debug = $query->debug('query'); - $this->assertInstanceOf(\MongoDB\BSON\ObjectId::class, $debug['groups.$id']['$nin'][0]); + $this->assertInstanceOf(ObjectId::class, $debug['groups.$id']['$nin'][0]); $this->assertEquals($ids[0], (string) $debug['groups.$id']['$nin'][0]); } public function testAndIsPrepared() { - $ids = array('4f28aa84acee41388900000a'); + $ids = ['4f28aa84acee41388900000a']; $qb = $this->dm->createQueryBuilder('Documents\User'); $qb @@ -87,13 +91,13 @@ public function testAndIsPrepared() $query = $qb->getQuery(); $debug = $query->debug('query'); - $this->assertInstanceOf(\MongoDB\BSON\ObjectId::class, $debug['$and'][0]['groups.$id']['$in'][0]); + $this->assertInstanceOf(ObjectId::class, $debug['$and'][0]['groups.$id']['$in'][0]); $this->assertEquals($ids[0], (string) $debug['$and'][0]['groups.$id']['$in'][0]); } public function testOrIsPrepared() { - $ids = array('4f28aa84acee41388900000a'); + $ids = ['4f28aa84acee41388900000a']; $qb = $this->dm->createQueryBuilder('Documents\User'); $qb @@ -102,16 +106,16 @@ public function testOrIsPrepared() $query = $qb->getQuery(); $debug = $query->debug('query'); - $this->assertInstanceOf(\MongoDB\BSON\ObjectId::class, $debug['$or'][0]['groups.$id']['$in'][0]); + $this->assertInstanceOf(ObjectId::class, $debug['$or'][0]['groups.$id']['$in'][0]); $this->assertEquals($ids[0], (string) $debug['$or'][0]['groups.$id']['$in'][0]); } public function testMultipleQueryOperatorsArePrepared() { - $all = array('4f28aa84acee41388900000a'); - $in = array('4f28aa84acee41388900000b'); + $all = ['4f28aa84acee41388900000a']; + $in = ['4f28aa84acee41388900000b']; $ne = '4f28aa84acee41388900000c'; - $nin = array('4f28aa84acee41388900000d'); + $nin = ['4f28aa84acee41388900000d']; $qb = $this->dm->createQueryBuilder('Documents\User') ->field('groups.id')->all($all) @@ -122,13 +126,13 @@ public function testMultipleQueryOperatorsArePrepared() $query = $qb->getQuery(); $debug = $query->debug('query'); - $this->assertInstanceOf(\MongoDB\BSON\ObjectId::class, $debug['groups.$id']['$all'][0]); + $this->assertInstanceOf(ObjectId::class, $debug['groups.$id']['$all'][0]); $this->assertEquals($all[0], (string) $debug['groups.$id']['$all'][0]); - $this->assertInstanceOf(\MongoDB\BSON\ObjectId::class, $debug['groups.$id']['$in'][0]); + $this->assertInstanceOf(ObjectId::class, $debug['groups.$id']['$in'][0]); $this->assertEquals($in[0], (string) $debug['groups.$id']['$in'][0]); - $this->assertInstanceOf(\MongoDB\BSON\ObjectId::class, $debug['groups.$id']['$ne']); + $this->assertInstanceOf(ObjectId::class, $debug['groups.$id']['$ne']); $this->assertEquals($ne, (string) $debug['groups.$id']['$ne']); - $this->assertInstanceOf(\MongoDB\BSON\ObjectId::class, $debug['groups.$id']['$nin'][0]); + $this->assertInstanceOf(ObjectId::class, $debug['groups.$id']['$nin'][0]); $this->assertEquals($nin[0], (string) $debug['groups.$id']['$nin'][0]); } @@ -138,7 +142,7 @@ public function testPrepareNestedDocuments() ->field('address.subAddress.subAddress.subAddress.test')->equals('test'); $query = $qb->getQuery(); $debug = $query->debug('query'); - $this->assertEquals(array('address.subAddress.subAddress.subAddress.testFieldName' => 'test'), $debug); + $this->assertEquals(['address.subAddress.subAddress.subAddress.testFieldName' => 'test'], $debug); } public function testPreparePositionalOperator() @@ -146,10 +150,10 @@ public function testPreparePositionalOperator() $qb = $this->dm->createQueryBuilder('Documents\User') ->updateOne() ->field('phonenumbers.$.phonenumber')->equals('foo') - ->field('phonenumbers.$')->set(array('phonenumber' => 'bar')); + ->field('phonenumbers.$')->set(['phonenumber' => 'bar']); - $this->assertEquals(array('phonenumbers.$.phonenumber' => 'foo'), $qb->getQueryArray()); - $this->assertEquals(array('$set' => array('phonenumbers.$' => array('phonenumber' => 'bar'))), $qb->getNewObj()); + $this->assertEquals(['phonenumbers.$.phonenumber' => 'foo'], $qb->getQueryArray()); + $this->assertEquals(['$set' => ['phonenumbers.$' => ['phonenumber' => 'bar']]], $qb->getNewObj()); } public function testSortIsPrepared() @@ -158,22 +162,22 @@ public function testSortIsPrepared() ->sort('id', 'desc'); $query = $qb->getQuery(); $query = $query->getQuery(); - $this->assertEquals(array('_id' => -1), $query['sort']); + $this->assertEquals(['_id' => -1], $query['sort']); $qb = $this->dm->createQueryBuilder('Documents\User') ->sort('address.subAddress.subAddress.subAddress.test', 'asc'); $query = $qb->getQuery(); $query = $query->getQuery(); - $this->assertEquals(array('address.subAddress.subAddress.subAddress.testFieldName' => 1), $query['sort']); + $this->assertEquals(['address.subAddress.subAddress.subAddress.testFieldName' => 1], $query['sort']); } public function testNestedWithOperator() { $qb = $this->dm->createQueryBuilder('Documents\User') - ->field('address.subAddress.subAddress.subAddress.test')->notIn(array('test')); + ->field('address.subAddress.subAddress.subAddress.test')->notIn(['test']); $query = $qb->getQuery(); $query = $query->getQuery(); - $this->assertEquals(array('address.subAddress.subAddress.subAddress.testFieldName' => array('$nin' => array('test'))), $query['query']); + $this->assertEquals(['address.subAddress.subAddress.subAddress.testFieldName' => ['$nin' => ['test']]], $query['query']); } public function testNewObjectIsPrepared() @@ -183,7 +187,7 @@ public function testNewObjectIsPrepared() ->field('address.subAddress.subAddress.subAddress.test')->popFirst(); $query = $qb->getQuery(); $query = $query->getQuery(); - $this->assertEquals(array('$pop' => array('address.subAddress.subAddress.subAddress.testFieldName' => 1)), $query['newObj']); + $this->assertEquals(['$pop' => ['address.subAddress.subAddress.subAddress.testFieldName' => 1]], $query['newObj']); } public function testReferencesUsesMinimalKeys() @@ -193,12 +197,12 @@ public function testReferencesUsesMinimalKeys() $documentPersister = $this->createMock(DocumentPersister::class); $class = $this->createMock(ClassMetadata::class); - $expected = array('foo.$id' => '1234'); + $expected = ['foo.$id' => '1234']; $dm ->expects($this->once()) ->method('createReference') - ->will($this->returnValue(array('$ref' => 'coll', '$id' => '1234', '$db' => 'db'))); + ->will($this->returnValue(['$ref' => 'coll', '$id' => '1234', '$db' => 'db'])); $dm ->expects($this->once()) ->method('getUnitOfWork') @@ -218,7 +222,7 @@ public function testReferencesUsesMinimalKeys() $class ->expects($this->once()) ->method('getFieldMapping') - ->will($this->returnValue(array('targetDocument' => 'Foo', 'name' => 'foo', 'storeAs' => ClassMetadata::REFERENCE_STORE_AS_DB_REF_WITH_DB))); + ->will($this->returnValue(['targetDocument' => 'Foo', 'name' => 'foo', 'storeAs' => ClassMetadata::REFERENCE_STORE_AS_DB_REF_WITH_DB])); $expr = $this->createExpr($dm, $class); $expr->field('bar')->references(new \stdClass()); @@ -233,12 +237,12 @@ public function testReferencesUsesAllKeys() $documentPersister = $this->createMock(DocumentPersister::class); $class = $this->createMock(ClassMetadata::class); - $expected = array('foo.$ref' => 'coll', 'foo.$id' => '1234', 'foo.$db' => 'db'); + $expected = ['foo.$ref' => 'coll', 'foo.$id' => '1234', 'foo.$db' => 'db']; $dm ->expects($this->once()) ->method('createReference') - ->will($this->returnValue(array('$ref' => 'coll', '$id' => '1234', '$db' => 'db'))); + ->will($this->returnValue(['$ref' => 'coll', '$id' => '1234', '$db' => 'db'])); $dm ->expects($this->once()) ->method('getUnitOfWork') @@ -258,7 +262,7 @@ public function testReferencesUsesAllKeys() $class ->expects($this->once()) ->method('getFieldMapping') - ->will($this->returnValue(array('name' => 'foo', 'storeAs' => ClassMetadata::REFERENCE_STORE_AS_DB_REF_WITH_DB))); + ->will($this->returnValue(['name' => 'foo', 'storeAs' => ClassMetadata::REFERENCE_STORE_AS_DB_REF_WITH_DB])); $expr = $this->createExpr($dm, $class); $expr->field('bar')->references(new \stdClass()); @@ -273,12 +277,12 @@ public function testReferencesUsesSomeKeys() $documentPersister = $this->createMock(DocumentPersister::class); $class = $this->createMock(ClassMetadata::class); - $expected = array('foo.$ref' => 'coll', 'foo.$id' => '1234'); + $expected = ['foo.$ref' => 'coll', 'foo.$id' => '1234']; $dm ->expects($this->once()) ->method('createReference') - ->will($this->returnValue(array('$ref' => 'coll', '$id' => '1234'))); + ->will($this->returnValue(['$ref' => 'coll', '$id' => '1234'])); $dm ->expects($this->once()) ->method('getUnitOfWork') @@ -298,7 +302,7 @@ public function testReferencesUsesSomeKeys() $class ->expects($this->once()) ->method('getFieldMapping') - ->will($this->returnValue(array('storeAs' => ClassMetadata::REFERENCE_STORE_AS_DB_REF, 'name' => 'foo'))); + ->will($this->returnValue(['storeAs' => ClassMetadata::REFERENCE_STORE_AS_DB_REF, 'name' => 'foo'])); $expr = $this->createExpr($dm, $class); $expr->field('bar')->references(new \stdClass()); @@ -548,11 +552,13 @@ public function testPushWithExpression() ->sort('x', 1); $expectedNewObj = [ - '$push' => ['a' => [ + '$push' => [ + 'a' => [ '$each' => [['x' => 1], ['x' => 2]], '$slice' => -2, '$sort' => ['x' => 1], - ]], + ], + ], ]; $this->assertSame($expr, $expr->field('a')->push($innerExpr)); @@ -569,11 +575,13 @@ public function testPushWithExpressionShouldEnsureEachOperatorAppearsFirst() ->each([['x' => 1], ['x' => 2]]); $expectedNewObj = [ - '$push' => ['a' => [ + '$push' => [ + 'a' => [ '$each' => [['x' => 1], ['x' => 2]], '$sort' => ['x' => 1], '$slice' => -2, - ]], + ], + ], ]; $this->assertSame($expr, $expr->field('a')->push($innerExpr)); @@ -589,10 +597,12 @@ public function testPushWithPosition() ->position(0); $expectedNewObj = [ - '$push' => ['a' => [ + '$push' => [ + 'a' => [ '$each' => [20, 30], '$position' => 0, - ]], + ], + ], ]; $this->assertSame($expr, $expr->field('a')->push($innerExpr)); @@ -743,9 +753,9 @@ public function testNotInWillStripKeysToYieldBsonArray() $this->assertEquals(['$nin' => ['value1', 'value2']], $expr->getQuery()); } - private function createExpr(DocumentManager $dm = null, ClassMetadata $class = null): Expr + private function createExpr(?DocumentManager $dm = null, ?ClassMetadata $class = null): Expr { - if (!$dm) { + if (! $dm) { $dm = $this->createMock(DocumentManager::class); $uow = $this->createMock(UnitOfWork::class); $documentPersister = $this->createMock(DocumentPersister::class); @@ -766,7 +776,7 @@ private function createExpr(DocumentManager $dm = null, ClassMetadata $class = n ->will($this->returnArgument(0)); } - if (!$class) { + if (! $class) { $class = new ClassMetadata(User::class); } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Query/Filter/BsonFilterTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Query/Filter/BsonFilterTest.php index 65c0aba9d3..f0efe8524a 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Query/Filter/BsonFilterTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Query/Filter/BsonFilterTest.php @@ -1,29 +1,33 @@ -dm); - $filter->getParameter('doesnotexist'); - } - - public function testSetParameter() - { - $filter = new Filter($this->dm); - $filter->setParameter('username', 'Tim'); - $this->assertEquals('Tim', $filter->getParameter('username')); - } - - public function testGetNullParameter() - { - $filter = new Filter($this->dm); - $filter->setParameter('foo', null); - $this->assertNull($filter->getParameter('foo')); - } -} +dm); + $filter->getParameter('doesnotexist'); + } + + public function testSetParameter() + { + $filter = new Filter($this->dm); + $filter->setParameter('username', 'Tim'); + $this->assertEquals('Tim', $filter->getParameter('username')); + } + + public function testGetNullParameter() + { + $filter = new Filter($this->dm); + $filter->setParameter('foo', null); + $this->assertNull($filter->getParameter('foo')); + } +} diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Query/Filter/Filter.php b/tests/Doctrine/ODM/MongoDB/Tests/Query/Filter/Filter.php index 8dce330fb5..360286fccc 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Query/Filter/Filter.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Query/Filter/Filter.php @@ -1,5 +1,7 @@ name == $this->parameters['class']) - ? array($this->parameters['field'] => $this->parameters['value']) - : array(); + return ($class->name === $this->parameters['class']) + ? [$this->parameters['field'] => $this->parameters['value']] + : []; } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Query/FilterCollectionTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Query/FilterCollectionTest.php index 98c7e0b4c3..7718193dad 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Query/FilterCollectionTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Query/FilterCollectionTest.php @@ -1,8 +1,12 @@ setParameter('field', 'username'); $testFilter->setParameter('value', 'Tim'); - $this->assertSame(array('username' => 'Tim'), $filterCollection->getFilterCriteria($class)); + $this->assertSame(['username' => 'Tim'], $filterCollection->getFilterCriteria($class)); } public function testGetFilterCriteriaMergesCriteria() @@ -91,10 +95,12 @@ public function testGetFilterCriteriaMergesCriteria() $testFilter->setParameter('field', 'username'); $testFilter->setParameter('value', 'John'); - $expectedCriteria = array('$and' => array( - array('username' => 'Tim'), - array('username' => 'John'), - )); + $expectedCriteria = [ + '$and' => [ + ['username' => 'Tim'], + ['username' => 'John'], + ], + ]; $this->assertSame($expectedCriteria, $filterCollection->getFilterCriteria($class)); } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Query/QueryExpressionVisitorTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Query/QueryExpressionVisitorTest.php index dd0a48d913..2765db3e31 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Query/QueryExpressionVisitorTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Query/QueryExpressionVisitorTest.php @@ -1,13 +1,16 @@ eq('field', 'value'), array('field' => 'value')), - array($builder->contains('field', 'value'), array('field' => new \MongoDB\BSON\Regex('value', ''))), - array($builder->gt('field', 'value'), array('field' => array('$gt' => 'value'))), - array($builder->gte('field', 'value'), array('field' => array('$gte' => 'value'))), - array($builder->in('field', array(1, 2)), array('field' => array('$in' => array(1, 2)))), - array($builder->isNull('field'), array('field' => null)), - array($builder->lt('field', 'value'), array('field' => array('$lt' => 'value'))), - array($builder->lte('field', 'value'), array('field' => array('$lte' => 'value'))), - array($builder->neq('field', 'value'), array('field' => array('$ne' => 'value'))), - array($builder->notIn('field', array(1, 2)), array('field' => array('$nin' => array(1, 2)))), - ); + return [ + [$builder->eq('field', 'value'), ['field' => 'value']], + [$builder->contains('field', 'value'), ['field' => new Regex('value', '')]], + [$builder->gt('field', 'value'), ['field' => ['$gt' => 'value']]], + [$builder->gte('field', 'value'), ['field' => ['$gte' => 'value']]], + [$builder->in('field', [1, 2]), ['field' => ['$in' => [1, 2]]]], + [$builder->isNull('field'), ['field' => null]], + [$builder->lt('field', 'value'), ['field' => ['$lt' => 'value']]], + [$builder->lte('field', 'value'), ['field' => ['$lte' => 'value']]], + [$builder->neq('field', 'value'), ['field' => ['$ne' => 'value']]], + [$builder->notIn('field', [1, 2]), ['field' => ['$nin' => [1, 2]]]], + ]; } /** @@ -69,11 +72,13 @@ public function testWalkCompositeExpression() $builder->eq('b', 3) ); - $expectedQuery = array('$and' => array( - array('a' => 1), - array('a' => array('$ne' => 2)), - array('b' => 3), - )); + $expectedQuery = [ + '$and' => [ + ['a' => 1], + ['a' => ['$ne' => 2]], + ['b' => 3], + ], + ]; $expr = $this->visitor->dispatch($compositeExpr); @@ -86,7 +91,7 @@ public function testWalkCompositeExpression() */ public function testWalkCompositeExpressionShouldThrowExceptionForUnsupportedComposite() { - $compositeExpr = new CompositeExpression('invalidComposite', array()); + $compositeExpr = new CompositeExpression('invalidComposite', []); $expr = $this->visitor->dispatch($compositeExpr); } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/QueryLogger.php b/tests/Doctrine/ODM/MongoDB/Tests/QueryLogger.php index 1cf73057c5..e2db203788 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/QueryLogger.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/QueryLogger.php @@ -1,10 +1,14 @@ queries = array(); + $this->queries = []; } /** * Returns the number of logged queries. * * @see php.net/countable.count - * @return integer + * @return int */ public function count() { diff --git a/tests/Doctrine/ODM/MongoDB/Tests/QueryTest.php b/tests/Doctrine/ODM/MongoDB/Tests/QueryTest.php index 175e5c7dc2..d602b436a1 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/QueryTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/QueryTest.php @@ -1,22 +1,26 @@ dm->createQueryBuilder(__NAMESPACE__.'\Person') + $qb = $this->dm->createQueryBuilder(__NAMESPACE__ . '\Person') ->exclude('comments') ->select('comments') ->selectSlice('comments', 0, 10); @@ -37,18 +41,20 @@ public function testThatOrAcceptsAnotherQuery() $this->dm->persist($chris); $this->dm->flush(); - $class = __NAMESPACE__.'\Person'; - $expression1 = array('firstName' => 'Kris'); - $expression2 = array('firstName' => 'Chris'); + $class = __NAMESPACE__ . '\Person'; + $expression1 = ['firstName' => 'Kris']; + $expression2 = ['firstName' => 'Chris']; $qb = $this->dm->createQueryBuilder($class); $qb->addOr($qb->expr()->field('firstName')->equals('Kris')); $qb->addOr($qb->expr()->field('firstName')->equals('Chris')); - $this->assertEquals(array('$or' => array( - array('firstName' => 'Kris'), - array('firstName' => 'Chris') - )), $qb->getQueryArray()); + $this->assertEquals([ + '$or' => [ + ['firstName' => 'Kris'], + ['firstName' => 'Chris'], + ], + ], $qb->getQueryArray()); $query = $qb->getQuery(); $users = $query->execute(); @@ -69,15 +75,15 @@ public function testReferences() $kris->bestFriend = $jon; $this->dm->flush(); - $qb = $this->dm->createQueryBuilder(__NAMESPACE__.'\Person'); + $qb = $this->dm->createQueryBuilder(__NAMESPACE__ . '\Person'); $qb->field('bestFriend')->references($jon); $queryArray = $qb->getQueryArray(); - $this->assertEquals(array( + $this->assertEquals([ 'bestFriend.$ref' => 'people', - 'bestFriend.$id' => new \MongoDB\BSON\ObjectId($jon->id), + 'bestFriend.$id' => new ObjectId($jon->id), 'bestFriend.$db' => DOCTRINE_MONGODB_DATABASE, - ), $queryArray); + ], $queryArray); $query = $qb->getQuery(); @@ -97,13 +103,13 @@ public function testReferencesStoreAsId() $kris->bestFriendSimple = $jon; $this->dm->flush(); - $qb = $this->dm->createQueryBuilder(__NAMESPACE__.'\Person'); + $qb = $this->dm->createQueryBuilder(__NAMESPACE__ . '\Person'); $qb->field('bestFriendSimple')->references($jon); $queryArray = $qb->getQueryArray(); - $this->assertEquals(array( - 'bestFriendSimple' => new \MongoDB\BSON\ObjectId($jon->id), - ), $queryArray); + $this->assertEquals([ + 'bestFriendSimple' => new ObjectId($jon->id), + ], $queryArray); $query = $qb->getQuery(); @@ -123,14 +129,14 @@ public function testReferencesStoreAsDbRef() $kris->bestFriendPartial = $jon; $this->dm->flush(); - $qb = $this->dm->createQueryBuilder(__NAMESPACE__.'\Person'); + $qb = $this->dm->createQueryBuilder(__NAMESPACE__ . '\Person'); $qb->field('bestFriendPartial')->references($jon); $queryArray = $qb->getQueryArray(); - $this->assertEquals(array( + $this->assertEquals([ 'bestFriendPartial.$ref' => 'people', - 'bestFriendPartial.$id' => new \MongoDB\BSON\ObjectId($jon->id), - ), $queryArray); + 'bestFriendPartial.$id' => new ObjectId($jon->id), + ], $queryArray); $query = $qb->getQuery(); @@ -150,19 +156,19 @@ public function testIncludesReferenceToWithStoreAsDbRefWithDb() $jon->friends[] = $kris; $this->dm->flush(); - $qb = $this->dm->createQueryBuilder(__NAMESPACE__.'\Person'); + $qb = $this->dm->createQueryBuilder(__NAMESPACE__ . '\Person'); $qb->field('friends')->includesReferenceTo($kris); $queryArray = $qb->getQueryArray(); - $this->assertEquals(array( - 'friends' => array( - '$elemMatch' => array( + $this->assertEquals([ + 'friends' => [ + '$elemMatch' => [ '$ref' => 'people', - '$id' => new \MongoDB\BSON\ObjectId($kris->id), + '$id' => new ObjectId($kris->id), '$db' => DOCTRINE_MONGODB_DATABASE, - ), - ), - ), $queryArray); + ], + ], + ], $queryArray); $query = $qb->getQuery(); @@ -185,13 +191,13 @@ public function testIncludesReferenceToWithStoreAsId() $jon->friendsSimple[] = $jachim; $this->dm->flush(); - $qb = $this->dm->createQueryBuilder(__NAMESPACE__.'\Person'); + $qb = $this->dm->createQueryBuilder(__NAMESPACE__ . '\Person'); $qb->field('friendsSimple')->includesReferenceTo($kris); $queryArray = $qb->getQueryArray(); - $this->assertEquals(array( - 'friendsSimple' => new \MongoDB\BSON\ObjectId($kris->id) - ), $queryArray); + $this->assertEquals([ + 'friendsSimple' => new ObjectId($kris->id), + ], $queryArray); $query = $qb->getQuery(); @@ -211,18 +217,18 @@ public function testIncludesReferenceToWithStoreAsDbRef() $jon->friendsPartial[] = $kris; $this->dm->flush(); - $qb = $this->dm->createQueryBuilder(__NAMESPACE__.'\Person'); + $qb = $this->dm->createQueryBuilder(__NAMESPACE__ . '\Person'); $qb->field('friendsPartial')->includesReferenceTo($kris); $queryArray = $qb->getQueryArray(); - $this->assertEquals(array( - 'friendsPartial' => array( - '$elemMatch' => array( + $this->assertEquals([ + 'friendsPartial' => [ + '$elemMatch' => [ '$ref' => 'people', - '$id' => new \MongoDB\BSON\ObjectId($kris->id) - ), - ), - ), $queryArray); + '$id' => new ObjectId($kris->id), + ], + ], + ], $queryArray); $query = $qb->getQuery(); @@ -232,13 +238,13 @@ public function testIncludesReferenceToWithStoreAsDbRef() public function testQueryIdIn() { - $user = new \Documents\User(); + $user = new User(); $user->setUsername('jwage'); $this->dm->persist($user); $this->dm->flush(); - $identifier = new \MongoDB\BSON\ObjectId($user->getId()); - $ids = array($identifier); + $identifier = new ObjectId($user->getId()); + $ids = [$identifier]; $qb = $this->dm->createQueryBuilder('Documents\User') ->field('_id')->in($ids); @@ -254,7 +260,7 @@ public function testEmbeddedSet() ->field('testInt')->set('0') ->field('intfields.intone')->set('1') ->field('intfields.inttwo')->set('2'); - $this->assertEquals(array('testInt' => 0, 'intfields' => array('intone' => 1, 'inttwo' => 2)), $qb->getNewObj()); + $this->assertEquals(['testInt' => 0, 'intfields' => ['intone' => 1, 'inttwo' => 2]], $qb->getNewObj()); } public function testElemMatch() @@ -265,28 +271,27 @@ public function testElemMatch() $embeddedQb = $this->dm->createQueryBuilder('Documents\Phonenumber'); $qb->field('phonenumbers')->elemMatch($embeddedQb->expr() - ->field('lastCalledBy.id')->equals($refId) - ); + ->field('lastCalledBy.id')->equals($refId)); $query = $qb->getQuery(); - $expectedQuery = array('phonenumbers' => array('$elemMatch' => array('lastCalledBy.$id' => new \MongoDB\BSON\ObjectId($refId)))); + $expectedQuery = ['phonenumbers' => ['$elemMatch' => ['lastCalledBy.$id' => new ObjectId($refId)]]]; $this->assertEquals($expectedQuery, $query->debug('query')); } public function testQueryWithMultipleEmbeddedDocuments() { - $qb = $this->dm->createQueryBuilder(__NAMESPACE__.'\EmbedTest') + $qb = $this->dm->createQueryBuilder(__NAMESPACE__ . '\EmbedTest') ->find() ->field('embeddedOne.embeddedOne.embeddedMany.embeddedOne.name')->equals('Foo'); $query = $qb->getQuery(); - $this->assertEquals(array('eO.eO.e1.eO.n' => 'Foo'), $query->debug('query')); + $this->assertEquals(['eO.eO.e1.eO.n' => 'Foo'], $query->debug('query')); } public function testQueryWithMultipleEmbeddedDocumentsAndReference() { - $identifier = new \MongoDB\BSON\ObjectId(); + $identifier = new ObjectId(); - $qb = $this->dm->createQueryBuilder(__NAMESPACE__.'\EmbedTest') + $qb = $this->dm->createQueryBuilder(__NAMESPACE__ . '\EmbedTest') ->find() ->field('embeddedOne.embeddedOne.embeddedMany.embeddedOne.pet.owner.id')->equals((string) $identifier); $query = $qb->getQuery(); @@ -298,14 +303,14 @@ public function testQueryWithMultipleEmbeddedDocumentsAndReference() public function testSelectVsSingleCollectionInheritance() { - $p = new \Documents\SubProject('SubProject'); + $p = new SubProject('SubProject'); $this->dm->persist($p); $this->dm->flush(); $this->dm->clear(); $test = $this->dm->createQueryBuilder() ->find('Documents\Project') - ->select(array('name')) + ->select(['name']) ->field('id')->equals($p->getId()) ->getQuery()->getSingleResult(); $this->assertNotNull($test); @@ -315,14 +320,14 @@ public function testSelectVsSingleCollectionInheritance() public function testEmptySelectVsSingleCollectionInheritance() { - $p = new \Documents\SubProject('SubProject'); + $p = new SubProject('SubProject'); $this->dm->persist($p); $this->dm->flush(); $this->dm->clear(); $test = $this->dm->createQueryBuilder() ->find('Documents\Project') - ->select(array()) + ->select([]) ->field('id')->equals($p->getId()) ->getQuery()->getSingleResult(); $this->assertNotNull($test); @@ -332,30 +337,30 @@ public function testEmptySelectVsSingleCollectionInheritance() public function testDiscriminatorFieldNotAddedWithoutHydration() { - $p = new \Documents\SubProject('SubProject'); + $p = new SubProject('SubProject'); $this->dm->persist($p); $this->dm->flush(); $this->dm->clear(); $test = $this->dm->createQueryBuilder() ->find('Documents\Project')->hydrate(false) - ->select(array('name')) + ->select(['name']) ->field('id')->equals($p->getId()) ->getQuery()->getSingleResult(); $this->assertNotNull($test); - $this->assertEquals(array('_id', 'name'), array_keys($test)); + $this->assertEquals(['_id', 'name'], array_keys($test)); } public function testExcludeVsSingleCollectionInheritance() { - $p = new \Documents\SubProject('SubProject'); + $p = new SubProject('SubProject'); $this->dm->persist($p); $this->dm->flush(); $this->dm->clear(); $test = $this->dm->createQueryBuilder() ->find('Documents\SubProject') - ->exclude(array('name', 'issues')) + ->exclude(['name', 'issues']) ->field('id')->equals($p->getId()) ->getQuery()->getSingleResult(); $this->assertNotNull($test); @@ -499,13 +504,13 @@ class Person public $bestFriendPartial; /** @ODM\ReferenceMany(storeAs="dbRefWithDb") */ - public $friends = array(); + public $friends = []; /** @ODM\ReferenceMany(storeAs="id", targetDocument="Doctrine\ODM\MongoDB\Tests\Person") */ - public $friendsSimple = array(); + public $friendsSimple = []; /** @ODM\ReferenceMany */ - public $friendsPartial = array(); + public $friendsPartial = []; /** @ODM\EmbedOne(targetDocument="Pet") */ public $pet; diff --git a/tests/Doctrine/ODM/MongoDB/Tests/RepositoryFactoryTest.php b/tests/Doctrine/ODM/MongoDB/Tests/RepositoryFactoryTest.php index e848d909b0..edd75f95db 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/RepositoryFactoryTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/RepositoryFactoryTest.php @@ -1,5 +1,7 @@ setConfiguration($this->dm->getConfiguration()); $cmf->setDocumentManager($this->dm); - $map = array(); + $map = []; foreach ($cmf->getAllMetadata() as $cm) { $this->documentCollections[$cm->name] = $this->getMockCollection(); @@ -91,39 +105,39 @@ public function testEnsureIndexes() public function testEnsureDocumentIndexes() { foreach ($this->documentCollections as $class => $collection) { - if ($class === \Documents\CmsArticle::class) { + if ($class === CmsArticle::class) { $collection->expects($this->once())->method('createIndex'); } else { $collection->expects($this->never())->method('createIndex'); } } - $this->schemaManager->ensureDocumentIndexes(\Documents\CmsArticle::class); + $this->schemaManager->ensureDocumentIndexes(CmsArticle::class); } public function testEnsureDocumentIndexesWithTwoLevelInheritance() { - $collection = $this->documentCollections[\Documents\CmsProduct::class]; + $collection = $this->documentCollections[CmsProduct::class]; $collection->expects($this->once())->method('createIndex'); - $this->schemaManager->ensureDocumentIndexes(\Documents\CmsProduct::class); + $this->schemaManager->ensureDocumentIndexes(CmsProduct::class); } public function testEnsureDocumentIndexesWithTimeout() { - $collection = $this->documentCollections[\Documents\CmsArticle::class]; + $collection = $this->documentCollections[CmsArticle::class]; $collection->expects($this->once()) ->method('createIndex') - ->with($this->anything(), $this->callback(function($o) { + ->with($this->anything(), $this->callback(function ($o) { return isset($o['timeout']) && $o['timeout'] === 10000; })); - $this->schemaManager->ensureDocumentIndexes(\Documents\CmsArticle::class, 10000); + $this->schemaManager->ensureDocumentIndexes(CmsArticle::class, 10000); } public function testUpdateDocumentIndexesShouldCreateMappedIndexes() { - $collection = $this->documentCollections[\Documents\CmsArticle::class]; + $collection = $this->documentCollections[CmsArticle::class]; $collection->expects($this->once()) ->method('listIndexes') ->will($this->returnValue(new IndexInfoIteratorIterator(new \ArrayIterator([])))); @@ -132,17 +146,18 @@ public function testUpdateDocumentIndexesShouldCreateMappedIndexes() $collection->expects($this->never()) ->method('dropIndex'); - $this->schemaManager->updateDocumentIndexes(\Documents\CmsArticle::class); + $this->schemaManager->updateDocumentIndexes(CmsArticle::class); } public function testUpdateDocumentIndexesShouldDeleteUnmappedIndexesBeforeCreatingMappedIndexes() { - $collection = $this->documentCollections[\Documents\CmsArticle::class]; + $collection = $this->documentCollections[CmsArticle::class]; $indexes = [[ 'v' => 1, - 'key' => array('topic' => -1), - 'name' => 'topic_-1' - ]]; + 'key' => ['topic' => -1], + 'name' => 'topic_-1', + ], + ]; $collection->expects($this->once()) ->method('listIndexes') ->will($this->returnValue(new IndexInfoIteratorIterator(new \ArrayIterator($indexes)))); @@ -151,7 +166,7 @@ public function testUpdateDocumentIndexesShouldDeleteUnmappedIndexesBeforeCreati $collection->expects($this->once()) ->method('dropIndex'); - $this->schemaManager->updateDocumentIndexes(\Documents\CmsArticle::class); + $this->schemaManager->updateDocumentIndexes(CmsArticle::class); } public function testDeleteIndexes() @@ -170,24 +185,24 @@ public function testDeleteIndexes() public function testDeleteDocumentIndexes() { foreach ($this->documentCollections as $class => $collection) { - if ($class === \Documents\CmsArticle::class) { + if ($class === CmsArticle::class) { $collection->expects($this->once())->method('dropIndexes'); } else { $collection->expects($this->never())->method('dropIndexes'); } } - $this->schemaManager->deleteDocumentIndexes(\Documents\CmsArticle::class); + $this->schemaManager->deleteDocumentIndexes(CmsArticle::class); } public function testCreateDocumentCollection() { - $cm = $this->classMetadatas[\Documents\CmsArticle::class]; + $cm = $this->classMetadatas[CmsArticle::class]; $cm->collectionCapped = true; $cm->collectionSize = 1048576; $cm->collectionMax = 32; - $database = $this->documentDatabases[\Documents\CmsArticle::class]; + $database = $this->documentDatabases[CmsArticle::class]; $database->expects($this->once()) ->method('createCollection') ->with( @@ -195,12 +210,12 @@ public function testCreateDocumentCollection() [ 'capped' => true, 'size' => 1048576, - 'max' => 32 + 'max' => 32, ] ) ; - $this->schemaManager->createDocumentCollection(\Documents\CmsArticle::class); + $this->schemaManager->createDocumentCollection(CmsArticle::class); } public function testCreateCollections() @@ -234,7 +249,7 @@ public function testDropCollections() public function testDropDocumentCollection() { foreach ($this->documentCollections as $class => $collection) { - if ($class === \Documents\CmsArticle::class) { + if ($class === CmsArticle::class) { $collection->expects($this->once()) ->method('drop') ->with(); @@ -243,20 +258,20 @@ public function testDropDocumentCollection() } } - $this->schemaManager->dropDocumentCollection(\Documents\CmsArticle::class); + $this->schemaManager->dropDocumentCollection(CmsArticle::class); } public function testDropDocumentDatabase() { foreach ($this->documentDatabases as $class => $database) { - if ($class === \Documents\CmsArticle::class) { + if ($class === CmsArticle::class) { $database->expects($this->once())->method('drop'); } else { $database->expects($this->never())->method('drop'); } } - $this->dm->getSchemaManager()->dropDocumentDatabase(\Documents\CmsArticle::class); + $this->dm->getSchemaManager()->dropDocumentDatabase(CmsArticle::class); } public function testDropDatabases() @@ -278,7 +293,7 @@ public function testDropDatabases() public function testIsMongoIndexEquivalentToDocumentIndex($expected, $mongoIndex, $documentIndex) { $defaultMongoIndex = [ - 'key' => ['foo' => 1, 'bar' => -1] + 'key' => ['foo' => 1, 'bar' => -1], ]; $defaultDocumentIndex = [ 'keys' => ['foo' => 1, 'bar' => -1], @@ -445,7 +460,7 @@ public function dataIsMongoIndexEquivalentToDocumentIndex() 'expected' => true, 'mongoIndex' => ['partialFilterExpression' => []], 'documentIndex' => [], - ] + ], ]; } @@ -454,7 +469,7 @@ public function testEnsureDocumentSharding() $this->markTestSkipped('Sharding support is still WIP'); $dbName = DOCTRINE_MONGODB_DATABASE; - $classMetadata = $this->dm->getClassMetadata(\Documents\Sharded\ShardedUser::class); + $classMetadata = $this->dm->getClassMetadata(ShardedUser::class); $collectionName = $classMetadata->getCollection(); $dbMock = $this->getMockDatabase(); $dbMock->method('getName')->willReturn($dbName); @@ -462,18 +477,18 @@ public function testEnsureDocumentSharding() $connMock = $this->getMockClient(); $connMock->method('selectDatabase')->with('admin')->willReturn($adminDBMock); $this->dm->connection = $connMock; - $this->dm->documentDatabases = array($classMetadata->getName() => $dbMock); + $this->dm->documentDatabases = [$classMetadata->getName() => $dbMock]; $adminDBMock ->expects($this->at(0)) ->method('command') - ->with(array('enableSharding' => $dbName)) - ->willReturn(array('ok' => 1)); + ->with(['enableSharding' => $dbName]) + ->willReturn(['ok' => 1]); $adminDBMock ->expects($this->at(1)) ->method('command') - ->with(array('shardCollection' => $dbName . '.' . $collectionName, 'key' => array('_id' => 'hashed'))) - ->willReturn(array('ok' => 1)); + ->with(['shardCollection' => $dbName . '.' . $collectionName, 'key' => ['_id' => 'hashed']]) + ->willReturn(['ok' => 1]); $this->schemaManager->ensureDocumentSharding($classMetadata->getName()); } @@ -487,7 +502,7 @@ public function testEnsureDocumentShardingThrowsExceptionIfThereWasAnError() $this->markTestSkipped('Sharding support is still WIP'); $dbName = DOCTRINE_MONGODB_DATABASE; - $classMetadata = $this->dm->getClassMetadata(\Documents\Sharded\ShardedUser::class); + $classMetadata = $this->dm->getClassMetadata(ShardedUser::class); $collectionName = $classMetadata->getCollection(); $dbMock = $this->getMockDatabase(); $dbMock->method('getName')->willReturn($dbName); @@ -495,18 +510,18 @@ public function testEnsureDocumentShardingThrowsExceptionIfThereWasAnError() $connMock = $this->getMockClient(); $connMock->method('selectDatabase')->with('admin')->willReturn($adminDBMock); $this->dm->connection = $connMock; - $this->dm->documentDatabases = array($classMetadata->getName() => $dbMock); + $this->dm->documentDatabases = [$classMetadata->getName() => $dbMock]; $adminDBMock ->expects($this->at(0)) ->method('command') - ->with(array('enableSharding' => $dbName)) - ->willReturn(array('ok' => 1)); + ->with(['enableSharding' => $dbName]) + ->willReturn(['ok' => 1]); $adminDBMock ->expects($this->at(1)) ->method('command') - ->with(array('shardCollection' => $dbName . '.' . $collectionName, 'key' => array('_id' => 'hashed'))) - ->willReturn(array('ok' => 0, 'code' => 666, 'errmsg' => 'Scary error')); + ->with(['shardCollection' => $dbName . '.' . $collectionName, 'key' => ['_id' => 'hashed']]) + ->willReturn(['ok' => 0, 'code' => 666, 'errmsg' => 'Scary error']); $this->schemaManager->ensureDocumentSharding($classMetadata->getName()); } @@ -516,7 +531,7 @@ public function testEnsureDocumentShardingIgnoresAlreadyShardedError() $this->markTestSkipped('Sharding support is still WIP'); $dbName = DOCTRINE_MONGODB_DATABASE; - $classMetadata = $this->dm->getClassMetadata(\Documents\Sharded\ShardedUser::class); + $classMetadata = $this->dm->getClassMetadata(ShardedUser::class); $collectionName = $classMetadata->getCollection(); $dbMock = $this->getMockDatabase(); $dbMock->method('getName')->willReturn($dbName); @@ -524,18 +539,18 @@ public function testEnsureDocumentShardingIgnoresAlreadyShardedError() $connMock = $this->getMockClient(); $connMock->method('selectDatabase')->with('admin')->willReturn($adminDBMock); $this->dm->connection = $connMock; - $this->dm->documentDatabases = array($classMetadata->getName() => $dbMock); + $this->dm->documentDatabases = [$classMetadata->getName() => $dbMock]; $adminDBMock ->expects($this->at(0)) ->method('command') - ->with(array('enableSharding' => $dbName)) - ->willReturn(array('ok' => 1)); + ->with(['enableSharding' => $dbName]) + ->willReturn(['ok' => 1]); $adminDBMock ->expects($this->at(1)) ->method('command') - ->with(array('shardCollection' => $dbName . '.' . $collectionName, 'key' => array('_id' => 'hashed'))) - ->willReturn(array('ok' => 0, 'code' => 20, 'errmsg' => 'already sharded')); + ->with(['shardCollection' => $dbName . '.' . $collectionName, 'key' => ['_id' => 'hashed']]) + ->willReturn(['ok' => 0, 'code' => 20, 'errmsg' => 'already sharded']); $this->schemaManager->ensureDocumentSharding($classMetadata->getName()); } @@ -548,16 +563,16 @@ public function testEnableShardingForDb() $adminDBMock ->expects($this->once()) ->method('command') - ->with(array('enableSharding' => 'db')) - ->willReturn(array('ok' => 1)); + ->with(['enableSharding' => 'db']) + ->willReturn(['ok' => 1]); $connMock = $this->getMockClient(); $connMock->method('selectDatabase')->with('admin')->willReturn($adminDBMock); $this->dm->connection = $connMock; $dbMock = $this->getMockDatabase(); $dbMock->method('getName')->willReturn('db'); - $this->dm->documentDatabases = array(\Documents\Sharded\ShardedUser::class => $dbMock); + $this->dm->documentDatabases = [ShardedUser::class => $dbMock]; - $this->schemaManager->enableShardingForDbByDocumentName(\Documents\Sharded\ShardedUser::class); + $this->schemaManager->enableShardingForDbByDocumentName(ShardedUser::class); } /** @@ -572,16 +587,16 @@ public function testEnableShardingForDbThrowsExceptionInCaseOfError() $adminDBMock ->expects($this->once()) ->method('command') - ->with(array('enableSharding' => 'db')) - ->willReturn(array('ok' => 0, 'code' => 666, 'errmsg' => 'Scary error')); + ->with(['enableSharding' => 'db']) + ->willReturn(['ok' => 0, 'code' => 666, 'errmsg' => 'Scary error']); $connMock = $this->getMockClient(); $connMock->method('selectDatabase')->with('admin')->willReturn($adminDBMock); $this->dm->connection = $connMock; $dbMock = $this->getMockDatabase(); $dbMock->method('getName')->willReturn('db'); - $this->dm->documentDatabases = array(\Documents\Sharded\ShardedUser::class => $dbMock); + $this->dm->documentDatabases = [ShardedUser::class => $dbMock]; - $this->schemaManager->enableShardingForDbByDocumentName(\Documents\Sharded\ShardedUser::class); + $this->schemaManager->enableShardingForDbByDocumentName(ShardedUser::class); } public function testEnableShardingForDbIgnoresAlreadyShardedError() @@ -592,16 +607,16 @@ public function testEnableShardingForDbIgnoresAlreadyShardedError() $adminDBMock ->expects($this->once()) ->method('command') - ->with(array('enableSharding' => 'db')) - ->willReturn(array('ok' => 0, 'code' => 23, 'errmsg' => 'already enabled')); + ->with(['enableSharding' => 'db']) + ->willReturn(['ok' => 0, 'code' => 23, 'errmsg' => 'already enabled']); $connMock = $this->getMockClient(); $connMock->method('selectDatabase')->with('admin')->willReturn($adminDBMock); $this->dm->connection = $connMock; $dbMock = $this->getMockDatabase(); $dbMock->method('getName')->willReturn('db'); - $this->dm->documentDatabases = array(\Documents\Sharded\ShardedUser::class => $dbMock); + $this->dm->documentDatabases = [ShardedUser::class => $dbMock]; - $this->schemaManager->enableShardingForDbByDocumentName(\Documents\Sharded\ShardedUser::class); + $this->schemaManager->enableShardingForDbByDocumentName(ShardedUser::class); } private function getMockCollection() diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Tools/GH1299/BaseUser.php b/tests/Doctrine/ODM/MongoDB/Tests/Tools/GH1299/BaseUser.php index 4306e5ae71..88e26ead73 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Tools/GH1299/BaseUser.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Tools/GH1299/BaseUser.php @@ -1,5 +1,7 @@ street; } - + public function setStreet($street) { $this->street = $street; diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Tools/GH297/AddressTrait.php b/tests/Doctrine/ODM/MongoDB/Tests/Tools/GH297/AddressTrait.php index 0c0a990c1d..2585303f0d 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Tools/GH297/AddressTrait.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Tools/GH297/AddressTrait.php @@ -1,20 +1,22 @@ address; } - public function setAddress(Address $address) + public function setAddress(Address $address) { $this->address = $address; } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Tools/GH297/Admin.php b/tests/Doctrine/ODM/MongoDB/Tests/Tools/GH297/Admin.php index 8791448237..fedea6f7ac 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Tools/GH297/Admin.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Tools/GH297/Admin.php @@ -1,5 +1,7 @@ id; } - + public function getName() { return $this->name; } - + public function setName($name) { $this->name = $name; diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Tools/ResolveTargetDocumentListenerTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Tools/ResolveTargetDocumentListenerTest.php index 0f267bd050..95422f954b 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Tools/ResolveTargetDocumentListenerTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Tools/ResolveTargetDocumentListenerTest.php @@ -1,15 +1,19 @@ listener->addResolveTargetDocument( 'Doctrine\ODM\MongoDB\Tests\Tools\ResolveTargetInterface', 'Doctrine\ODM\MongoDB\Tests\Tools\ResolveTargetDocument', - array() + [] ); $this->listener->addResolveTargetDocument( 'Doctrine\ODM\MongoDB\Tests\Tools\TargetInterface', 'Doctrine\ODM\MongoDB\Tests\Tools\TargetDocument', - array() + [] ); $evm->addEventListener(Events::loadClassMetadata, $this->listener); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Types/DateTypeTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Types/DateTypeTest.php index a7cc8e8c07..2e27cc13aa 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Types/DateTypeTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Types/DateTypeTest.php @@ -1,9 +1,16 @@ getDateTime($timestamp); $this->assertEquals($timestamp, $dateTime->format('U.u')); - $mongoDate = new \MongoDB\BSON\UTCDateTime(100000000001); + $mongoDate = new UTCDateTime(100000000001); $dateTime = $type->getDateTime($mongoDate); $this->assertEquals($timestamp, $dateTime->format('U.u')); } @@ -26,12 +33,12 @@ public function testConvertToDatabaseValue() $this->assertNull($type->convertToDatabaseValue(null), 'null is not converted'); - $mongoDate = new \MongoDB\BSON\UTCDateTime(); + $mongoDate = new UTCDateTime(); $this->assertSame($mongoDate, $type->convertToDatabaseValue($mongoDate), 'MongoDate objects are not converted'); $timestamp = 100000000.123; - $dateTime = \DateTime::createFromFormat('U.u', $timestamp); - $mongoDate = new \MongoDB\BSON\UTCDateTime(100000000123); + $dateTime = \DateTime::createFromFormat('U.u', (string) $timestamp); + $mongoDate = new UTCDateTime(100000000123); $this->assertEquals($mongoDate, $type->convertToDatabaseValue($dateTime), 'DateTime objects are converted to MongoDate objects'); $this->assertEquals($mongoDate, $type->convertToDatabaseValue($timestamp), 'Numeric timestamps are converted to MongoDate objects'); $this->assertEquals($mongoDate, $type->convertToDatabaseValue('' . $timestamp), 'String dates are converted to MongoDate objects'); @@ -44,9 +51,9 @@ public function testConvertDateTimeImmutable() $type = Type::getType(Type::DATE); $timestamp = 100000000.123; - $mongoDate = new \MongoDB\BSON\UTCDateTime(100000000123); + $mongoDate = new UTCDateTime(100000000123); - $dateTimeImmutable = \DateTimeImmutable::createFromFormat('U.u', $timestamp); + $dateTimeImmutable = \DateTimeImmutable::createFromFormat('U.u', (string) $timestamp); $this->assertEquals($mongoDate, $type->convertToDatabaseValue($dateTimeImmutable), 'DateTimeImmutable objects are converted to MongoDate objects'); } @@ -55,7 +62,7 @@ public function testConvertOldDate() $type = Type::getType(Type::DATE); $date = new \DateTime('1900-01-01 00:00:00.123', new \DateTimeZone('UTC')); - $timestamp = "-2208988800.123"; + $timestamp = '-2208988800.123'; $this->assertEquals($type->convertToDatabaseValue($timestamp), $type->convertToDatabaseValue($date)); } @@ -71,13 +78,13 @@ public function testConvertToDatabaseValueWithInvalidValues($value) public function provideInvalidDateValues() { - return array( - 'array' => array(array()), - 'string' => array('whatever'), - 'bool' => array(false), - 'object' => array(new \stdClass()), - 'invalid string' => array('foo'), - ); + return [ + 'array' => [[]], + 'string' => ['whatever'], + 'bool' => [false], + 'object' => [new \stdClass()], + 'invalid string' => ['foo'], + ]; } /** @@ -107,7 +114,7 @@ public function testClosureToPHP($input, $output) $type = Type::getType(Type::DATE); $return = null; - call_user_func(function($value) use ($type, &$return) { + call_user_func(function ($value) use ($type, &$return) { eval($type->closureToPHP()); }, $input); @@ -118,16 +125,16 @@ public function testClosureToPHP($input, $output) public function provideDatabaseToPHPValues() { $yesterday = strtotime('yesterday'); - $mongoDate = new \MongoDB\BSON\UTCDateTime($yesterday * 1000); + $mongoDate = new UTCDateTime($yesterday * 1000); $dateTime = new \DateTime('@' . $yesterday); - return array( - array($dateTime, $dateTime), - array($mongoDate, $dateTime), - array($yesterday, $dateTime), - array(date('c', $yesterday), $dateTime), - array(new \MongoDB\BSON\UTCDateTime(100000000123), \DateTime::createFromFormat('U.u', '100000000.123')), - ); + return [ + [$dateTime, $dateTime], + [$mongoDate, $dateTime], + [$yesterday, $dateTime], + [date('c', $yesterday), $dateTime], + [new UTCDateTime(100000000123), \DateTime::createFromFormat('U.u', '100000000.123')], + ]; } /** @@ -136,7 +143,7 @@ public function provideDatabaseToPHPValues() public function test32bit1900Date() { if (PHP_INT_SIZE !== 4) { - $this->markTestSkipped("Platform is not 32-bit"); + $this->markTestSkipped('Platform is not 32-bit'); } $type = Type::getType(Type::DATE); @@ -146,14 +153,14 @@ public function test32bit1900Date() public function test64bit1900Date() { if (PHP_INT_SIZE !== 8) { - $this->markTestSkipped("Platform is not 64-bit"); + $this->markTestSkipped('Platform is not 64-bit'); } $type = Type::getType(Type::DATE); $return = $type->convertToDatabaseValue('1900-01-01'); - $this->assertInstanceOf(\MongoDB\BSON\UTCDateTime::class, $return); - $this->assertEquals(new \MongoDB\BSON\UTCDateTime(strtotime('1900-01-01') * 1000), $return); + $this->assertInstanceOf(UTCDateTime::class, $return); + $this->assertEquals(new UTCDateTime(strtotime('1900-01-01') * 1000), $return); } private function assertTimestampEquals(\DateTime $expected, \DateTime $actual) diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Types/IdTypeTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Types/IdTypeTest.php index 5ab85f6dea..f4a1579cde 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Types/IdTypeTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Types/IdTypeTest.php @@ -1,15 +1,18 @@ assertNull($type->convertToDatabaseValue(null), 'null is not converted'); @@ -24,17 +27,16 @@ public function testConvertToDatabaseValueShouldGenerateObjectIds($value) { $type = Type::getType('id'); - $this->assertInstanceOf(\MongoDB\BSON\ObjectId::class, $type->convertToDatabaseValue($value)); + $this->assertInstanceOf(ObjectId::class, $type->convertToDatabaseValue($value)); } public function provideInvalidObjectIdConstructorArguments() { - return array( - 'integer' => array(1), - 'float' => array(3.14), - 'string' => array('string'), - 'bool' => array(true), - 'object' => array(array('x' => 1, 'y' => 2)), - ); + return [ + 'integer' => [1], + 'float' => [3.14], + 'string' => ['string'], + 'bool' => [true], + ]; } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Types/InvalidValueExceptionTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Types/InvalidValueExceptionTest.php index 668a7e0862..8e9f444da9 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Types/InvalidValueExceptionTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Types/InvalidValueExceptionTest.php @@ -1,5 +1,7 @@ array(Type::getType(Type::ID), "507f1f77bcf86cd799439011"), - 'intId' => array(Type::getType(Type::INTID), 1), - 'customId' => array(Type::getType(Type::CUSTOMID), (object) array('foo' => 'bar')), - 'bool' => array(Type::getType(Type::BOOL), true), - 'boolean' => array(Type::getType(Type::BOOLEAN), false), - 'int' => array(Type::getType(Type::INT), 69), - 'integer' => array(Type::getType(Type::INTEGER), 42), - 'float' => array(Type::getType(Type::FLOAT), 3.14), - 'string' => array(Type::getType(Type::STRING), 'ohai'), - 'minKey' => array(Type::getType(Type::KEY), 0), - 'maxKey' => array(Type::getType(Type::KEY), 1), - 'timestamp' => array(Type::getType(Type::TIMESTAMP), time()), - 'binData' => array(Type::getType(Type::BINDATA), 'foobarbaz'), - 'binDataFunc' => array(Type::getType(Type::BINDATAFUNC), 'foobarbaz'), - 'binDataByteArray' => array(Type::getType(Type::BINDATABYTEARRAY), 'foobarbaz'), - 'binDataUuid' => array(Type::getType(Type::BINDATAUUID), "testtesttesttest"), - 'binDataUuidRFC4122' => array(Type::getType(Type::BINDATAUUIDRFC4122), str_repeat('a', 16)), - 'binDataMD5' => array(Type::getType(Type::BINDATAMD5), md5('ODM')), - 'binDataCustom' => array(Type::getType(Type::BINDATACUSTOM), 'foobarbaz'), - 'hash' => array(Type::getType(Type::HASH), array('foo' => 'bar')), - 'collection' => array(Type::getType(Type::COLLECTION), array('foo', 'bar')), - 'objectId' => array(Type::getType(Type::OBJECTID), "507f1f77bcf86cd799439011"), - 'raw' => array(Type::getType(Type::RAW), (object) array('foo' => 'bar')), - ); + return [ + 'id' => [Type::getType(Type::ID), '507f1f77bcf86cd799439011'], + 'intId' => [Type::getType(Type::INTID), 1], + 'customId' => [Type::getType(Type::CUSTOMID), (object) ['foo' => 'bar']], + 'bool' => [Type::getType(Type::BOOL), true], + 'boolean' => [Type::getType(Type::BOOLEAN), false], + 'int' => [Type::getType(Type::INT), 69], + 'integer' => [Type::getType(Type::INTEGER), 42], + 'float' => [Type::getType(Type::FLOAT), 3.14], + 'string' => [Type::getType(Type::STRING), 'ohai'], + 'minKey' => [Type::getType(Type::KEY), 0], + 'maxKey' => [Type::getType(Type::KEY), 1], + 'timestamp' => [Type::getType(Type::TIMESTAMP), time()], + 'binData' => [Type::getType(Type::BINDATA), 'foobarbaz'], + 'binDataFunc' => [Type::getType(Type::BINDATAFUNC), 'foobarbaz'], + 'binDataByteArray' => [Type::getType(Type::BINDATABYTEARRAY), 'foobarbaz'], + 'binDataUuid' => [Type::getType(Type::BINDATAUUID), 'testtesttesttest'], + 'binDataUuidRFC4122' => [Type::getType(Type::BINDATAUUIDRFC4122), str_repeat('a', 16)], + 'binDataMD5' => [Type::getType(Type::BINDATAMD5), md5('ODM')], + 'binDataCustom' => [Type::getType(Type::BINDATACUSTOM), 'foobarbaz'], + 'hash' => [Type::getType(Type::HASH), ['foo' => 'bar']], + 'collection' => [Type::getType(Type::COLLECTION), ['foo', 'bar']], + 'objectId' => [Type::getType(Type::OBJECTID), '507f1f77bcf86cd799439011'], + 'raw' => [Type::getType(Type::RAW), (object) ['foo' => 'bar']], + ]; } /** @@ -53,19 +65,19 @@ public function testConversionIsIdempotent(Type $type, $test) public function provideTypesForIdempotent() { - return array( - 'id' => array(Type::getType(Type::ID), new \MongoDB\BSON\ObjectId()), - 'date' => array(Type::getType(Type::DATE), new \MongoDB\BSON\UTCDateTime()), - 'timestamp' => array(Type::getType(Type::TIMESTAMP), new \MongoDB\BSON\Timestamp(0, time())), - 'binData' => array(Type::getType(Type::BINDATA), new \MongoDB\BSON\Binary('foobarbaz', \MongoDB\BSON\Binary::TYPE_GENERIC)), - 'binDataFunc' => array(Type::getType(Type::BINDATAFUNC), new \MongoDB\BSON\Binary('foobarbaz', \MongoDB\BSON\Binary::TYPE_FUNCTION)), - 'binDataByteArray' => array(Type::getType(Type::BINDATABYTEARRAY), new \MongoDB\BSON\Binary('foobarbaz', \MongoDB\BSON\Binary::TYPE_OLD_BINARY)), - 'binDataUuid' => array(Type::getType(Type::BINDATAUUID), new \MongoDB\BSON\Binary("testtesttesttest", \MongoDB\BSON\Binary::TYPE_OLD_UUID)), - 'binDataUuidRFC4122' => array(Type::getType(Type::BINDATAUUIDRFC4122), new \MongoDB\BSON\Binary(str_repeat('a', 16), \MongoDB\BSON\Binary::TYPE_UUID)), - 'binDataMD5' => array(Type::getType(Type::BINDATAMD5), new \MongoDB\BSON\Binary(md5('ODM'), \MongoDB\BSON\Binary::TYPE_MD5)), - 'binDataCustom' => array(Type::getType(Type::BINDATACUSTOM), new \MongoDB\BSON\Binary('foobarbaz', \MongoDB\BSON\Binary::TYPE_USER_DEFINED)), - 'objectId' => array(Type::getType(Type::OBJECTID), new \MongoDB\BSON\ObjectId()), - ); + return [ + 'id' => [Type::getType(Type::ID), new ObjectId()], + 'date' => [Type::getType(Type::DATE), new UTCDateTime()], + 'timestamp' => [Type::getType(Type::TIMESTAMP), new Timestamp(0, time())], + 'binData' => [Type::getType(Type::BINDATA), new Binary('foobarbaz', Binary::TYPE_GENERIC)], + 'binDataFunc' => [Type::getType(Type::BINDATAFUNC), new Binary('foobarbaz', Binary::TYPE_FUNCTION)], + 'binDataByteArray' => [Type::getType(Type::BINDATABYTEARRAY), new Binary('foobarbaz', Binary::TYPE_OLD_BINARY)], + 'binDataUuid' => [Type::getType(Type::BINDATAUUID), new Binary('testtesttesttest', Binary::TYPE_OLD_UUID)], + 'binDataUuidRFC4122' => [Type::getType(Type::BINDATAUUIDRFC4122), new Binary(str_repeat('a', 16), Binary::TYPE_UUID)], + 'binDataMD5' => [Type::getType(Type::BINDATAMD5), new Binary(md5('ODM'), Binary::TYPE_MD5)], + 'binDataCustom' => [Type::getType(Type::BINDATACUSTOM), new Binary('foobarbaz', Binary::TYPE_USER_DEFINED)], + 'objectId' => [Type::getType(Type::OBJECTID), new ObjectId()], + ]; } public function testConvertDatePreservesMilliseconds() @@ -74,7 +86,7 @@ public function testConvertDatePreservesMilliseconds() $expectedDate = clone $date; $cleanMicroseconds = (int) $date->format('v') * 1000; - $expectedDate->modify($date->format('H:i:s') . '.' . str_pad($cleanMicroseconds, 6, '0', STR_PAD_LEFT)); + $expectedDate->modify($date->format('H:i:s') . '.' . str_pad((string) $cleanMicroseconds, 6, '0', STR_PAD_LEFT)); $type = Type::getType(Type::DATE); $this->assertEquals($expectedDate, $type->convertToPHPValue($type->convertToDatabaseValue($date))); @@ -84,6 +96,6 @@ public function testConvertImmutableDate() { $date = new \DateTimeImmutable('now'); - $this->assertInstanceOf(\MongoDB\BSON\UTCDateTime::class, Type::convertPHPToDatabaseValue($date)); + $this->assertInstanceOf(UTCDateTime::class, Type::convertPHPToDatabaseValue($date)); } } diff --git a/tests/Doctrine/ODM/MongoDB/Tests/UnitOfWorkTest.php b/tests/Doctrine/ODM/MongoDB/Tests/UnitOfWorkTest.php index 819831c770..9b4d21e6c1 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/UnitOfWorkTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/UnitOfWorkTest.php @@ -1,19 +1,34 @@ dm->getClassMetadata('Documents\ForumUser'); $user = new ForumUser(); - $user->id = new \MongoDB\BSON\ObjectId(); + $user->id = new ObjectId(); $this->assertFalse($this->uow->isScheduledForInsert($user)); $this->assertFalse($this->uow->isScheduledForUpsert($user)); $this->uow->scheduleForUpsert($class, $user); @@ -49,17 +64,17 @@ public function testGetScheduledDocumentUpserts() { $class = $this->dm->getClassMetadata('Documents\ForumUser'); $user = new ForumUser(); - $user->id = new \MongoDB\BSON\ObjectId(); + $user->id = new ObjectId(); $this->assertEmpty($this->uow->getScheduledDocumentUpserts()); $this->uow->scheduleForUpsert($class, $user); - $this->assertEquals(array(spl_object_hash($user) => $user), $this->uow->getScheduledDocumentUpserts()); + $this->assertEquals([spl_object_hash($user) => $user], $this->uow->getScheduledDocumentUpserts()); } public function testScheduleForEmbeddedUpsert() { $class = $this->dm->getClassMetadata('Documents\ForumUser'); $test = new EmbeddedUpsertDocument(); - $test->id = (string) new \MongoDB\BSON\ObjectId(); + $test->id = (string) new ObjectId(); $this->assertFalse($this->uow->isScheduledForInsert($test)); $this->assertFalse($this->uow->isScheduledForUpsert($test)); $this->uow->persist($test); @@ -208,7 +223,7 @@ public function testChangeTrackingNotify() $entity->setTransient('newtransientvalue'); $this->assertTrue($this->uow->isScheduledForDirtyCheck($entity)); - $this->assertEquals(array('data' => array('thedata', 'newdata')), $this->uow->getDocumentChangeSet($entity)); + $this->assertEquals(['data' => ['thedata', 'newdata']], $this->uow->getDocumentChangeSet($entity)); $item = new NotifyChangedRelatedItem(); $item->setId(1); @@ -241,11 +256,11 @@ public function testChangeTrackingNotify() public function testGetDocumentStateWithAssignedIdentity() { $pb = $this->getMockPersistenceBuilder(); - $class = $this->dm->getClassMetadata("Documents\CmsPhonenumber"); + $class = $this->dm->getClassMetadata('Documents\CmsPhonenumber'); $persister = $this->getMockDocumentPersister($pb, $class); $this->uow->setDocumentPersister('Documents\CmsPhonenumber', $persister); - $ph = new \Documents\CmsPhonenumber(); + $ph = new CmsPhonenumber(); $ph->phonenumber = '12345'; $this->assertEquals(UnitOfWork::STATE_NEW, $this->uow->getDocumentState($ph)); @@ -254,10 +269,10 @@ public function testGetDocumentStateWithAssignedIdentity() $persister->reset(); // if the document is already managed the exists() check should be skipped - $this->uow->registerManaged($ph, '12345', array()); + $this->uow->registerManaged($ph, '12345', []); $this->assertEquals(UnitOfWork::STATE_MANAGED, $this->uow->getDocumentState($ph)); $this->assertFalse($persister->isExistsCalled()); - $ph2 = new \Documents\CmsPhonenumber(); + $ph2 = new CmsPhonenumber(); $ph2->phonenumber = '12345'; $this->assertEquals(UnitOfWork::STATE_DETACHED, $this->uow->getDocumentState($ph2)); $this->assertFalse($persister->isExistsCalled()); @@ -271,7 +286,7 @@ public function testThrowsOnPersistOfMappedSuperclass() $documentManager = $this->getDocumentManager(); $documentManager->setClassMetadata('Documents\Address', $this->getClassMetadata('Documents\Address', 'MappedSuperclass')); $unitOfWork = $this->getUnitOfWork($documentManager); - $unitOfWork->persist(new \Documents\Address()); + $unitOfWork->persist(new Address()); } public function testParentAssociations() @@ -283,11 +298,11 @@ public function testParentAssociations() $documentManager = $this->getDocumentManager(); $unitOfWork = $this->getUnitOfWork($documentManager); - $unitOfWork->setParentAssociation($b, array('name' => 'b'), $a, 'b'); - $unitOfWork->setParentAssociation($c, array('name' => 'c'), $b, 'b.c'); - $unitOfWork->setParentAssociation($d, array('name' => 'd'), $c, 'b.c.d'); + $unitOfWork->setParentAssociation($b, ['name' => 'b'], $a, 'b'); + $unitOfWork->setParentAssociation($c, ['name' => 'c'], $b, 'b.c'); + $unitOfWork->setParentAssociation($d, ['name' => 'd'], $c, 'b.c.d'); - $this->assertEquals(array(array('name' => 'd'), $c, 'b.c.d'), $unitOfWork->getParentAssociation($d)); + $this->assertEquals([['name' => 'd'], $c, 'b.c.d'], $unitOfWork->getParentAssociation($d)); } /** @@ -296,9 +311,9 @@ public function testParentAssociations() public function testPreUpdateTriggeredWithEmptyChangeset() { $this->dm->getEventManager()->addEventSubscriber( - new \Doctrine\ODM\MongoDB\Tests\Mocks\PreUpdateListenerMock() + new PreUpdateListenerMock() ); - $user = new \Documents\ForumUser(); + $user = new ForumUser(); $user->username = '12345'; $this->dm->persist($user); @@ -311,7 +326,7 @@ public function testPreUpdateTriggeredWithEmptyChangeset() public function testNotSaved() { - $test = new \Documents\Functional\NotSaved(); + $test = new NotSaved(); $test->name = 'test'; $test->notSaved = 'Jon'; $this->dm->persist($test); @@ -327,7 +342,7 @@ public function testNotSaved() public function testScheduleForUpdateWithArrays($origData, $updateData, $shouldInUpdate) { $pb = $this->getMockPersistenceBuilder(); - $class = $this->dm->getClassMetadata("Doctrine\ODM\MongoDB\Tests\ArrayTest"); + $class = $this->dm->getClassMetadata('Doctrine\ODM\MongoDB\Tests\ArrayTest'); $persister = $this->getMockDocumentPersister($pb, $class); $this->uow->setDocumentPersister('Doctrine\ODM\MongoDB\Tests\ArrayTest', $persister); @@ -348,53 +363,53 @@ public function testScheduleForUpdateWithArrays($origData, $updateData, $shouldI public function getScheduleForUpdateWithArraysTests() { - return array( - array( + return [ + [ null, - array('bar' => 'foo'), - true - ), - array( - array('foo' => 'bar'), + ['bar' => 'foo'], + true, + ], + [ + ['foo' => 'bar'], null, - true - ), - array( - array('foo' => 'bar'), - array('bar' => 'foo'), - true - ), - array( - array('foo' => 'bar'), - array('foo' => 'foo'), - true - ), - array( - array('foo' => 'bar'), - array('foo' => 'bar'), - false - ), - array( - array('foo' => 'bar'), - array('foo' => true), - true - ), - array( - array('foo' => 'bar'), - array('foo' => 99), - true - ), - array( - array('foo' => 99), - array('foo' => true), - true - ), - array( - array('foo' => true), - array('foo' => true), - false - ), - ); + true, + ], + [ + ['foo' => 'bar'], + ['bar' => 'foo'], + true, + ], + [ + ['foo' => 'bar'], + ['foo' => 'foo'], + true, + ], + [ + ['foo' => 'bar'], + ['foo' => 'bar'], + false, + ], + [ + ['foo' => 'bar'], + ['foo' => true], + true, + ], + [ + ['foo' => 'bar'], + ['foo' => 99], + true, + ], + [ + ['foo' => 99], + ['foo' => true], + true, + ], + [ + ['foo' => true], + ['foo' => true], + false, + ], + ]; } public function testRegisterManagedEmbeddedDocumentWithMappedIdAndNullValue() @@ -402,7 +417,7 @@ public function testRegisterManagedEmbeddedDocumentWithMappedIdAndNullValue() $document = new EmbeddedDocumentWithId(); $oid = spl_object_hash($document); - $this->uow->registerManaged($document, null, array()); + $this->uow->registerManaged($document, null, []); $this->assertEquals($oid, $this->uow->getDocumentIdentifier($document)); } @@ -412,7 +427,7 @@ public function testRegisterManagedEmbeddedDocumentWithoutMappedId() $document = new EmbeddedDocumentWithoutId(); $oid = spl_object_hash($document); - $this->uow->registerManaged($document, null, array()); + $this->uow->registerManaged($document, null, []); $this->assertEquals($oid, $this->uow->getDocumentIdentifier($document)); } @@ -422,7 +437,7 @@ public function testRegisterManagedEmbeddedDocumentWithMappedIdStrategyNoneAndNu $document = new EmbeddedDocumentWithIdStrategyNone(); $oid = spl_object_hash($document); - $this->uow->registerManaged($document, null, array()); + $this->uow->registerManaged($document, null, []); $this->assertEquals($oid, $this->uow->getDocumentIdentifier($document)); } @@ -492,8 +507,8 @@ public function testPersistRemovedEmbeddedDocument() public function testPersistingEmbeddedDocumentWithoutIdentifier() { - $address = new \Documents\Address(); - $user = new \Documents\User(); + $address = new Address(); + $user = new User(); $user->setAddress($address); $this->assertEquals(UnitOfWork::STATE_NEW, $this->uow->getDocumentState($address)); @@ -515,8 +530,8 @@ public function testPersistingEmbeddedDocumentWithoutIdentifier() public function testEmbeddedDocumentChangeSets() { - $address = new \Documents\Address(); - $user = new \Documents\User(); + $address = new Address(); + $user = new User(); $user->setAddress($address); $this->uow->persist($user); @@ -539,16 +554,12 @@ public function testEmbeddedDocumentChangeSets() public function testGetClassNameForAssociation() { - $mapping = array( + $mapping = [ 'discriminatorField' => 'type', - 'discriminatorMap' => array( - 'forum_user' => 'Documents\ForumUser', - ), + 'discriminatorMap' => ['forum_user' => 'Documents\ForumUser'], 'targetDocument' => 'Documents\User', - ); - $data = array( - 'type' => 'forum_user', - ); + ]; + $data = ['type' => 'forum_user']; $this->assertEquals('Documents\ForumUser', $this->uow->getClassNameForAssociation($mapping, $data)); } @@ -558,18 +569,12 @@ public function testGetClassNameForAssociationWithClassMetadataDiscriminatorMap( $dm = $this->getMockDocumentManager(); $uow = new UnitOfWork($dm, $this->getMockEventManager(), $this->getMockHydratorFactory()); - $mapping = array( - 'targetDocument' => 'Documents\User', - ); - $data = array( - 'type' => 'forum_user', - ); + $mapping = ['targetDocument' => 'Documents\User']; + $data = ['type' => 'forum_user']; $userClassMetadata = new ClassMetadata('Documents\ForumUser'); $userClassMetadata->discriminatorField = 'type'; - $userClassMetadata->discriminatorMap = array( - 'forum_user' => 'Documents\ForumUser', - ); + $userClassMetadata->discriminatorMap = ['forum_user' => 'Documents\ForumUser']; $dm->expects($this->once()) ->method('getClassMetadata') @@ -581,17 +586,15 @@ public function testGetClassNameForAssociationWithClassMetadataDiscriminatorMap( public function testGetClassNameForAssociationReturnsTargetDocumentWithNullData() { - $mapping = array( - 'targetDocument' => 'Documents\User', - ); + $mapping = ['targetDocument' => 'Documents\User']; $this->assertEquals('Documents\User', $this->uow->getClassNameForAssociation($mapping, null)); } public function testRecomputeChangesetForUninitializedProxyDoesNotCreateChangeset() { - $user = new \Documents\ForumUser(); + $user = new ForumUser(); $user->username = '12345'; - $user->setAvatar(new \Documents\ForumAvatar()); + $user->setAvatar(new ForumAvatar()); $this->dm->persist($user); $this->dm->flush(); @@ -608,20 +611,20 @@ public function testRecomputeChangesetForUninitializedProxyDoesNotCreateChangese $this->uow->recomputeSingleDocumentChangeSet($classMetadata, $user->getAvatar()); - $this->assertEquals(array(), $this->uow->getDocumentChangeSet($user->getAvatar())); + $this->assertEquals([], $this->uow->getDocumentChangeSet($user->getAvatar())); } public function testCommitsInProgressIsUpdatedOnException() { $this->dm->getEventManager()->addEventSubscriber( - new \Doctrine\ODM\MongoDB\Tests\Mocks\ExceptionThrowingListenerMock() + new ExceptionThrowingListenerMock() ); - $user = new \Documents\ForumUser(); + $user = new ForumUser(); $user->username = '12345'; $this->dm->persist($user); - $this->expectException(\Exception::class); + $this->expectException(\Throwable::class); $this->expectExceptionMessage('This should not happen'); $this->dm->flush(); @@ -642,7 +645,7 @@ protected function getUnitOfWork(DocumentManager $dm) /** * Gets mock HydratorFactory instance * - * @return \Doctrine\ODM\MongoDB\Hydrator\HydratorFactory + * @return HydratorFactory */ private function getMockHydratorFactory() { @@ -652,7 +655,7 @@ private function getMockHydratorFactory() /** * Gets mock EventManager instance * - * @return \Doctrine\Common\EventManager + * @return EventManager */ private function getMockEventManager() { @@ -696,9 +699,9 @@ public function __construct($name) * @ODM\Document * @ODM\ChangeTrackingPolicy("NOTIFY") */ -class NotifyChangedDocument implements \Doctrine\Common\NotifyPropertyChanged +class NotifyChangedDocument implements NotifyPropertyChanged { - private $_listeners = array(); + private $_listeners = []; /** @ODM\Id(type="int_id", strategy="none") */ private $id; @@ -711,7 +714,7 @@ class NotifyChangedDocument implements \Doctrine\Common\NotifyPropertyChanged private $transient; // not persisted - public function __construct() + public function __construct() { $this->items = new ArrayCollection(); } @@ -733,7 +736,7 @@ public function getData() public function setData($data) { - if ($data != $this->data) { + if ($data !== $this->data) { $this->_onPropertyChanged('data', $this->data, $data); $this->data = $data; } @@ -746,7 +749,7 @@ public function getItems() public function setTransient($value) { - if ($value != $this->transient) { + if ($value !== $this->transient) { $this->_onPropertyChanged('transient', $this->transient, $value); $this->transient = $value; } diff --git a/tests/Documents/Account.php b/tests/Documents/Account.php index 76da9a02db..2229b1218d 100644 --- a/tests/Documents/Account.php +++ b/tests/Documents/Account.php @@ -1,5 +1,7 @@ tags)) - { + if (! in_array($tag, $this->tags)) { return; } unset($this->tags[array_search($tag, $this->tags)]); diff --git a/tests/Documents/Bars/Bar.php b/tests/Documents/Bars/Bar.php index 4ca0753eb2..a173f8f333 100644 --- a/tests/Documents/Bars/Bar.php +++ b/tests/Documents/Bars/Bar.php @@ -1,5 +1,7 @@ locations; } - + public function setLocations($locations) { $this->locations = $locations; diff --git a/tests/Documents/Bars/Location.php b/tests/Documents/Bars/Location.php index b561bfeca8..292b5133c1 100644 --- a/tests/Documents/Bars/Location.php +++ b/tests/Documents/Bars/Location.php @@ -1,5 +1,7 @@ name = $name; - } - - public function getId() - { - return $this->id; - } - - public function setName($name) - { - $this->name = $name; - } - - public function getName() - { - return $this->name; - } - - public function addChild(BaseCategory $child) - { - $this->children[] = $child; - } - - public function getChildren() - { - return $this->children; - } + protected $children = []; + + public function __construct($name = null) + { + $this->name = $name; + } + + public function getId() + { + return $this->id; + } + + public function setName($name) + { + $this->name = $name; + } + + public function getName() + { + return $this->name; + } + + public function addChild(BaseCategory $child) + { + $this->children[] = $child; + } + + public function getChildren() + { + return $this->children; + } } diff --git a/tests/Documents/BaseCategoryRepository.php b/tests/Documents/BaseCategoryRepository.php index 3522b847ae..67a8e8e699 100644 --- a/tests/Documents/BaseCategoryRepository.php +++ b/tests/Documents/BaseCategoryRepository.php @@ -1,7 +1,11 @@ comments[] = $comment; } - public function setUser(User $user = null) + public function setUser(?User $user = null) { $this->user = $user; } diff --git a/tests/Documents/BlogTagAggregation.php b/tests/Documents/BlogTagAggregation.php index 8c715ac5f6..b4edfcdbeb 100644 --- a/tests/Documents/BlogTagAggregation.php +++ b/tests/Documents/BlogTagAggregation.php @@ -1,5 +1,7 @@ name = $name; - $this->children = new \Doctrine\Common\Collections\ArrayCollection(); + $this->children = new ArrayCollection(); } public function addChild(BrowseNode $child) diff --git a/tests/Documents/Cart.php b/tests/Documents/Cart.php index 1ef1d6ea88..68502569a8 100644 --- a/tests/Documents/Cart.php +++ b/tests/Documents/Cart.php @@ -1,5 +1,7 @@ id; } - - public function getUser() { + + public function getUser() + { return $this->user; } - public function getCountry() { + public function getCountry() + { return $this->country; } - public function getZipCode() { + public function getZipCode() + { return $this->zip; } - public function getCity() { + public function getCity() + { return $this->city; } - - public function setUser(CmsUser $user) { + + public function setUser(CmsUser $user) + { if ($this->user !== $user) { $this->user = $user; $user->setAddress($this); diff --git a/tests/Documents/CmsArticle.php b/tests/Documents/CmsArticle.php index e96f37f299..9567ff3165 100644 --- a/tests/Documents/CmsArticle.php +++ b/tests/Documents/CmsArticle.php @@ -1,5 +1,7 @@ user = $author; } - public function addComment(CmsComment $comment) { + public function addComment(CmsComment $comment) + { $this->comments[] = $comment; $comment->setArticle($this); } diff --git a/tests/Documents/CmsComment.php b/tests/Documents/CmsComment.php index ad7bde8d5b..72498abcf9 100644 --- a/tests/Documents/CmsComment.php +++ b/tests/Documents/CmsComment.php @@ -1,5 +1,7 @@ article = $article; } - public function __toString() { - return __CLASS__."[id=".$this->id."]"; + public function __toString() + { + return __CLASS__ . '[id=' . $this->id . ']'; } } diff --git a/tests/Documents/CmsContent.php b/tests/Documents/CmsContent.php index 5bc758b772..2038beddd8 100644 --- a/tests/Documents/CmsContent.php +++ b/tests/Documents/CmsContent.php @@ -1,5 +1,7 @@ name = $name; } - public function getName() { + public function getName() + { return $this->name; } - public function addUser(CmsUser $user) { + public function addUser(CmsUser $user) + { $this->users[] = $user; } - public function getUsers() { + public function getUsers() + { return $this->users; } } diff --git a/tests/Documents/CmsPage.php b/tests/Documents/CmsPage.php index 6948b5c1e2..37bf95356c 100644 --- a/tests/Documents/CmsPage.php +++ b/tests/Documents/CmsPage.php @@ -1,5 +1,7 @@ user = $user; } - - public function getUser() { + + public function getUser() + { return $this->user; } } diff --git a/tests/Documents/CmsProduct.php b/tests/Documents/CmsProduct.php index 828dbc5813..8e32c66d27 100644 --- a/tests/Documents/CmsProduct.php +++ b/tests/Documents/CmsProduct.php @@ -1,5 +1,7 @@ phonenumbers = new ArrayCollection; - $this->articles = new ArrayCollection; - $this->groups = new ArrayCollection; + + public function __construct() + { + $this->phonenumbers = new ArrayCollection(); + $this->articles = new ArrayCollection(); + $this->groups = new ArrayCollection(); } - public function getId() { + public function getId() + { return $this->id; } - public function getStatus() { + public function getStatus() + { return $this->status; } - public function getUsername() { + public function getUsername() + { return $this->username; } - public function getName() { + public function getName() + { return $this->name; } /** * Adds a phonenumber to the user. * - * @param CmsPhonenumber $phone */ - public function addPhonenumber(CmsPhonenumber $phone) { + public function addPhonenumber(CmsPhonenumber $phone) + { $this->phonenumbers[] = $phone; $phone->setUser($this); } - public function getPhonenumbers() { + public function getPhonenumbers() + { return $this->phonenumbers; } - public function addArticle(CmsArticle $article) { + public function addArticle(CmsArticle $article) + { $this->articles[] = $article; $article->setAuthor($this); } - public function addGroup(CmsGroup $group) { + public function addGroup(CmsGroup $group) + { $this->groups[] = $group; $group->addUser($this); } - public function getGroups() { + public function getGroups() + { return $this->groups; } - public function removePhonenumber($index) { + public function removePhonenumber($index) + { if (isset($this->phonenumbers[$index])) { $ph = $this->phonenumbers[$index]; unset($this->phonenumbers[$index]); @@ -109,10 +121,14 @@ public function removePhonenumber($index) { } return false; } - - public function getAddress() { return $this->address; } - - public function setAddress(CmsAddress $address) { + + public function getAddress() + { + return $this->address; + } + + public function setAddress(CmsAddress $address) + { if ($this->address !== $address) { $this->address = $address; $address->setUser($this); diff --git a/tests/Documents/Comment.php b/tests/Documents/Comment.php index 72efbf2155..e241777331 100644 --- a/tests/Documents/Comment.php +++ b/tests/Documents/Comment.php @@ -1,9 +1,11 @@ text; } - } diff --git a/tests/Documents/CommentRepository.php b/tests/Documents/CommentRepository.php index 57c776c061..0c8f98c75f 100644 --- a/tests/Documents/CommentRepository.php +++ b/tests/Documents/CommentRepository.php @@ -1,5 +1,7 @@ name = $name; - $this->projects = null === $projects ? new ArrayCollection() : $projects; + $this->projects = $projects === null ? new ArrayCollection() : $projects; } public function getId() diff --git a/tests/Documents/Ecommerce/ConfigurableProduct.php b/tests/Documents/Ecommerce/ConfigurableProduct.php index 874d22a57d..b898152287 100644 --- a/tests/Documents/Ecommerce/ConfigurableProduct.php +++ b/tests/Documents/Ecommerce/ConfigurableProduct.php @@ -1,8 +1,14 @@ setName($name); } @@ -61,12 +67,11 @@ public function getOptions() /** * @param string|Option $name - * @param float|null $price - * @param StockItem|null $item + * @param float|null $price */ - public function addOption($name, $price = null, StockItem $item = null) + public function addOption($name, $price = null, ?StockItem $item = null) { - if ( ! $name instanceof Option) { + if (! $name instanceof Option) { $name = (string) $name; if (empty($name)) { throw new \InvalidArgumentException('option name cannot be empty'); @@ -74,7 +79,7 @@ public function addOption($name, $price = null, StockItem $item = null) $name = new Option($name, $price, $item); unset($price, $item); } - if (null !== $this->_findOption($name->getName()) + if ($this->_findOption($name->getName()) !== null || in_array($name->getStockItem(), $this->_getStockItems(), true)) { throw new \InvalidArgumentException('cannot add option with the same name twice'); } @@ -88,10 +93,10 @@ public function getOption($name) public function removeOption($name) { - if(null === ($option = $this->_findOption($name))) { + if (($option = $this->_findOption($name)) === null) { throw new \InvalidArgumentException('option ' . $name . ' doesn\'t exist'); } - if ($this->options instanceof \Doctrine\Common\Collections\Collection) { + if ($this->options instanceof Collection) { $index = $this->options->indexOf($option); } else { $index = array_search($option, $this->options); @@ -102,13 +107,13 @@ public function removeOption($name) public function hasOption($name) { - return null !== $this->_findOption($name); + return $this->_findOption($name) !== null; } public function selectOption($name) { $option = $this->_findOption($name); - if ( ! isset($option)) { + if (! isset($option)) { throw new \InvalidArgumentException('specified option: ' . $name . ' doesn\'t exist'); } $this->selectedOption = $option; @@ -118,7 +123,7 @@ public function selectOption($name) protected function _findOption($name) { foreach ($this->options as $option) { - if ($name == $option->getName()) { + if ($name === $option->getName()) { return $option; } } @@ -137,5 +142,4 @@ protected function _getStockItems() return $option->getStockItem(); }, $this->getOptions()); } - } diff --git a/tests/Documents/Ecommerce/Currency.php b/tests/Documents/Ecommerce/Currency.php index 5002c892e0..479eb1d201 100644 --- a/tests/Documents/Ecommerce/Currency.php +++ b/tests/Documents/Ecommerce/Currency.php @@ -1,15 +1,19 @@ money; } return $this->money->getAmount(); diff --git a/tests/Documents/Ecommerce/StockItem.php b/tests/Documents/Ecommerce/StockItem.php index ffeed94f0b..7baf726c0e 100644 --- a/tests/Documents/Ecommerce/StockItem.php +++ b/tests/Documents/Ecommerce/StockItem.php @@ -1,5 +1,7 @@ id; } - public function __construct($name = null, $cost = null, $inventory = null) + public function __construct($name = null, $cost = null, $inventory = null) { - if (null !== $name) { + if ($name !== null) { $this->setName($name); } - if (null !== $cost) { + if ($cost !== null) { $this->setCost($cost); } - if (null !== $inventory) { + if ($inventory !== null) { $this->setInventory($inventory); } } diff --git a/tests/Documents/Employee.php b/tests/Documents/Employee.php index 69278c48cd..7c72500d63 100644 --- a/tests/Documents/Employee.php +++ b/tests/Documents/Employee.php @@ -1,5 +1,7 @@ manager = $val; return $this; } -} \ No newline at end of file +} diff --git a/tests/Documents/Event.php b/tests/Documents/Event.php index 452821761b..bc57dabb64 100644 --- a/tests/Documents/Event.php +++ b/tests/Documents/Event.php @@ -1,5 +1,7 @@ id; + return $this->id; } - + public function getUsername() { - return $this->username; + return $this->username; } - + public function getAvatar() { - return $this->avatar; + return $this->avatar; } - + public function setAvatar(ForumAvatar $avatar) { - $this->avatar = $avatar; + $this->avatar = $avatar; } } diff --git a/tests/Documents/FriendUser.php b/tests/Documents/FriendUser.php index 1238f88cae..bb38237563 100644 --- a/tests/Documents/FriendUser.php +++ b/tests/Documents/FriendUser.php @@ -1,7 +1,10 @@ name = $name; - $this->friendsWithMe = new \Doctrine\Common\Collections\ArrayCollection(); - $this->myFriends = new \Doctrine\Common\Collections\ArrayCollection(); + $this->friendsWithMe = new ArrayCollection(); + $this->myFriends = new ArrayCollection(); } public function addFriend(FriendUser $user) diff --git a/tests/Documents/Functional/EmbedNamed.php b/tests/Documents/Functional/EmbedNamed.php index 6a30ccadb9..0da05f713f 100644 --- a/tests/Documents/Functional/EmbedNamed.php +++ b/tests/Documents/Functional/EmbedNamed.php @@ -1,5 +1,7 @@ seller; } -} \ No newline at end of file +} diff --git a/tests/Documents/Functional/PreUpdateTestSeller.php b/tests/Documents/Functional/PreUpdateTestSeller.php index 40b57e3ea6..2975455685 100644 --- a/tests/Documents/Functional/PreUpdateTestSeller.php +++ b/tests/Documents/Functional/PreUpdateTestSeller.php @@ -1,5 +1,7 @@ vhostDirective) { + if (! $this->vhostDirective) { $this->vhostDirective = new VirtualHostDirective('VirtualHost', '*:80'); } return $this->vhostDirective; @@ -39,6 +40,4 @@ public function setVHostDirective($value) return $this; } - } - diff --git a/tests/Documents/Functional/VirtualHostDirective.php b/tests/Documents/Functional/VirtualHostDirective.php index 8bbefa7cd5..fc7f9b5036 100644 --- a/tests/Documents/Functional/VirtualHostDirective.php +++ b/tests/Documents/Functional/VirtualHostDirective.php @@ -1,8 +1,12 @@ name = $name; $this->value = $value; @@ -35,10 +39,11 @@ public function getRecId() return $this->recId; } - public function setRecId($value=null) + public function setRecId($value = null) { - if (!$value) + if (! $value) { $value = uniqid(); + } $this->recId = $value; } @@ -67,8 +72,9 @@ public function setValue($value) public function getDirectives() { - if (!$this->directives) - $this->directives = new \Doctrine\Common\Collections\ArrayCollection(array()); + if (! $this->directives) { + $this->directives = new ArrayCollection([]); + } return $this->directives; } @@ -94,7 +100,7 @@ public function addDirective(VirtualHostDirective $d) public function hasDirective($name) { foreach ($this->getDirectives() as $d) { - if ($d->getName() == $name) { + if ($d->getName() === $name) { return $d; } } @@ -114,5 +120,4 @@ public function removeDirective(VirtualHostDirective $d) return $this; } - } diff --git a/tests/Documents/GraphLookup/Airport.php b/tests/Documents/GraphLookup/Airport.php index 6b94d1b20b..0d5b32203a 100644 --- a/tests/Documents/GraphLookup/Airport.php +++ b/tests/Documents/GraphLookup/Airport.php @@ -1,5 +1,7 @@ name = $name; $this->reportsTo = $reportsTo; diff --git a/tests/Documents/GraphLookup/ReportingHierarchy.php b/tests/Documents/GraphLookup/ReportingHierarchy.php index 43e5161b33..fc8d1479a6 100644 --- a/tests/Documents/GraphLookup/ReportingHierarchy.php +++ b/tests/Documents/GraphLookup/ReportingHierarchy.php @@ -1,5 +1,7 @@ projects[] = $project; } -} \ No newline at end of file +} diff --git a/tests/Documents/Message.php b/tests/Documents/Message.php index f60fbaf834..100eb6d845 100644 --- a/tests/Documents/Message.php +++ b/tests/Documents/Message.php @@ -1,5 +1,7 @@ phonenumber = $phonenumber; $this->lastCalledBy = $lastCalledBy; @@ -34,7 +36,7 @@ public function getLastCalledBy() return $this->lastCalledBy; } - public function setLastCalledBy(User $lastCalledBy = null) + public function setLastCalledBy(?User $lastCalledBy = null) { $this->lastCalledBy = $lastCalledBy; } diff --git a/tests/Documents/Product.php b/tests/Documents/Product.php index b0edc1428f..62540eee7f 100644 --- a/tests/Documents/Product.php +++ b/tests/Documents/Product.php @@ -1,7 +1,10 @@ name = $name; - $this->features = new \Doctrine\Common\Collections\ArrayCollection(); + $this->features = new ArrayCollection(); } public function addFeature(Feature $feature) diff --git a/tests/Documents/Profile.php b/tests/Documents/Profile.php index c489073067..7fb30ebcb5 100644 --- a/tests/Documents/Profile.php +++ b/tests/Documents/Profile.php @@ -1,5 +1,7 @@ name = $name; $this->subProjects = $subProjects ? $subProjects : new ArrayCollection(); diff --git a/tests/Documents/ReferenceUser.php b/tests/Documents/ReferenceUser.php index 088bd96eeb..13e172bb3a 100644 --- a/tests/Documents/ReferenceUser.php +++ b/tests/Documents/ReferenceUser.php @@ -1,5 +1,7 @@ user = $user; @@ -95,9 +94,6 @@ public function getUser() return $this->user; } - /** - * @param User $user - */ public function addUser(User $user) { $this->users[] = $user; @@ -111,9 +107,6 @@ public function getUsers() return $this->users; } - /** - * @param User $parentUser - */ public function setParentUser(User $parentUser) { $this->parentUser = $parentUser; @@ -127,9 +120,6 @@ public function getParentUser() return $this->parentUser; } - /** - * @param User $parentUser - */ public function addParentUser(User $parentUser) { $this->parentUsers[] = $parentUser; @@ -143,9 +133,6 @@ public function getParentUsers() return $this->parentUsers; } - /** - * @param User $otherUser - */ public function setOtherUser(User $otherUser) { $this->otherUser = $otherUser; @@ -159,9 +146,6 @@ public function getOtherUser() return $this->otherUser; } - /** - * @param User $otherUser - */ public function addOtherUser(User $otherUser) { $this->otherUsers[] = $otherUser; @@ -175,9 +159,6 @@ public function getOtherUsers() return $this->otherUsers; } - /** - * @param User $referencedUser - */ public function setReferencedUser(User $referencedUser) { $this->referencedUser = $referencedUser; @@ -191,9 +172,6 @@ public function getreferencedUser() return $this->referencedUser; } - /** - * @param User $referencedUser - */ public function addReferencedUser(User $referencedUser) { $this->referencedUsers[] = $referencedUser; diff --git a/tests/Documents/Server.php b/tests/Documents/Server.php index 3071892712..74e9b5329e 100644 --- a/tests/Documents/Server.php +++ b/tests/Documents/Server.php @@ -1,5 +1,7 @@ rules; } -} \ No newline at end of file +} diff --git a/tests/Documents/Strategy.php b/tests/Documents/Strategy.php index 53a80b17c2..8fa5f381e2 100644 --- a/tests/Documents/Strategy.php +++ b/tests/Documents/Strategy.php @@ -1,5 +1,7 @@ issues = $issues; } -} \ No newline at end of file +} diff --git a/tests/Documents/Tag.php b/tests/Documents/Tag.php index 43da6264cd..03b765f035 100644 --- a/tests/Documents/Tag.php +++ b/tests/Documents/Tag.php @@ -1,5 +1,7 @@ address; } - public function setAddress(Address $address = null) + public function setAddress(?Address $address = null) { $this->address = $address; } diff --git a/tests/Documents/UserUpsert.php b/tests/Documents/UserUpsert.php index 967c98ae8d..d895c7bb4e 100644 --- a/tests/Documents/UserUpsert.php +++ b/tests/Documents/UserUpsert.php @@ -1,5 +1,7 @@ testdirectory = $directory; } - public function setTest($test) { + public function setTest($test) + { $this->test = $test; } - public function setTestfile($testfile) { + public function setTestfile($testfile) + { $this->testfile = $testfile; } - public function setJunitlogfile($junitlogfile) { - if (strlen($junitlogfile) == 0) { - $junitlogfile = NULL; + public function setJunitlogfile($junitlogfile) + { + if (strlen($junitlogfile) === 0) { + $junitlogfile = null; } $this->junitlogfile = $junitlogfile; } - public function setConfiguration($configuration) { - if (strlen($configuration) == 0) { - $configuration = NULL; + public function setConfiguration($configuration) + { + if (strlen($configuration) === 0) { + $configuration = null; } $this->configuration = $configuration; } - public function setCoverageClover($coverageClover) { - if (strlen($coverageClover) == 0) { - $coverageClover = NULL; + public function setCoverageClover($coverageClover) + { + if (strlen($coverageClover) === 0) { + $coverageClover = null; } $this->coverageClover = $coverageClover; } - public function setHaltonfailure($haltonfailures) { + public function setHaltonfailure($haltonfailures) + { $this->haltonfailure = $haltonfailures; } - public function setHaltonerror($haltonerrors) { + public function setHaltonerror($haltonerrors) + { $this->haltonerror = $haltonerrors; } public function init() { - require_once "PHPUnit/Runner/Version.php"; + require_once 'PHPUnit/Runner/Version.php'; $version = PHPUnit_Runner_Version::id(); - if (version_compare($version, '3.4.0') < 0) - { - throw new BuildException("NativePHPUnitTask requires PHPUnit version >= 3.2.0", $this->getLocation()); + if (version_compare($version, '3.4.0') < 0) { + throw new BuildException('NativePHPUnitTask requires PHPUnit version >= 3.2.0', $this->getLocation()); } require_once 'PHPUnit/Util/Filter.php'; // point PHPUnit_MAIN_METHOD define to non-existing method - if (!defined('PHPUnit_MAIN_METHOD')) - { + if (! defined('PHPUnit_MAIN_METHOD')) { define('PHPUnit_MAIN_METHOD', 'PHPUnitTask::undefined'); } } public function main() { - if (!is_dir(realpath($this->testdirectory))) { - throw new BuildException("NativePHPUnitTask requires a Test Directory path given, '".$this->testdirectory."' given."); + if (! is_dir(realpath($this->testdirectory))) { + throw new BuildException("NativePHPUnitTask requires a Test Directory path given, '" . $this->testdirectory . "' given."); } set_include_path(realpath($this->testdirectory) . PATH_SEPARATOR . get_include_path()); $printer = new NativePhpunitPrinter(); - $arguments = array( + $arguments = [ 'configuration' => $this->configuration, 'coverageClover' => $this->coverageClover, 'junitLogfile' => $this->junitlogfile, 'printer' => $printer, - ); + ]; - require_once "PHPUnit/TextUI/TestRunner.php"; + require_once 'PHPUnit/TextUI/TestRunner.php'; $runner = new PHPUnit_TextUI_TestRunner(); $suite = $runner->getTest($this->test, $this->testfile, true); @@ -105,32 +113,31 @@ public function main() $result = $runner->doRun($suite, $arguments); /* @var $result PHPUnit_Framework_TestResult */ - if ( ($this->haltonfailure && $result->failureCount() > 0) || ($this->haltonerror && $result->errorCount() > 0) ) { - throw new BuildException("PHPUnit: ".$result->failureCount()." Failures and ".$result->errorCount()." Errors, ". - "last failure message: ".$printer->getMessages()); + if (($this->haltonfailure && $result->failureCount() > 0) || ($this->haltonerror && $result->errorCount() > 0)) { + throw new BuildException('PHPUnit: ' . $result->failureCount() . ' Failures and ' . $result->errorCount() . ' Errors, ' . + 'last failure message: ' . $printer->getMessages()); } - $this->log("PHPUnit Success: ".count($result->passed())." tests passed, no ". - "failures (".$result->skippedCount()." skipped, ".$result->notImplementedCount()." not implemented)"); + $this->log('PHPUnit Success: ' . count($result->passed()) . ' tests passed, no ' . + 'failures (' . $result->skippedCount() . ' skipped, ' . $result->notImplementedCount() . ' not implemented)'); // Hudson for example doesn't like the backslash in class names if (file_exists($this->coverageClover)) { - $this->log("Generated Clover Coverage XML to: ".$this->coverageClover); + $this->log('Generated Clover Coverage XML to: ' . $this->coverageClover); $content = file_get_contents($this->coverageClover); - $content = str_replace("\\", ".", $content); + $content = str_replace('\\', '.', $content); file_put_contents($this->coverageClover, $content); unset($content); } - - } catch(\Exception $e) { - throw new BuildException("NativePhpunitTask failed: ".$e->getMessage()); + } catch (Throwable $e) { + throw new BuildException('NativePhpunitTask failed: ' . $e->getMessage()); } } } class NativePhpunitPrinter extends PHPUnit_Util_Printer implements PHPUnit_Framework_TestListener { - private $_messages = array(); + private $_messages = []; public function write($buffer) { @@ -145,92 +152,74 @@ public function getMessages() /** * An error occurred. * - * @param PHPUnit_Framework_Test $test - * @param Exception $e - * @param float $time + * @param Exception $e + * @param float $time */ - public function addError(PHPUnit_Framework_Test $test, Exception $e, $time) + public function addError(PHPUnit_Framework_Test $test, Throwable $e, $time) { - $this->_messages[] = "Test ERROR: ".$test->getName().": ".$e->getMessage(); + $this->_messages[] = 'Test ERROR: ' . $test->getName() . ': ' . $e->getMessage(); } /** * A failure occurred. * - * @param PHPUnit_Framework_Test $test - * @param PHPUnit_Framework_AssertionFailedError $e - * @param float $time + * @param float $time */ public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time) { - $this->_messages[] = "Test FAILED: ".$test->getName().": ".$e->getMessage(); + $this->_messages[] = 'Test FAILED: ' . $test->getName() . ': ' . $e->getMessage(); } /** * Incomplete test. * - * @param PHPUnit_Framework_Test $test - * @param Exception $e - * @param float $time + * @param Exception $e + * @param float $time */ - public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time) + public function addIncompleteTest(PHPUnit_Framework_Test $test, Throwable $e, $time) { - } /** * Skipped test. * - * @param PHPUnit_Framework_Test $test - * @param Exception $e - * @param float $time - * @since Method available since Release 3.0.0 + * @param Exception $e + * @param float $time */ - public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time) + public function addSkippedTest(PHPUnit_Framework_Test $test, Throwable $e, $time) { - } /** * A test suite started. * - * @param PHPUnit_Framework_TestSuite $suite - * @since Method available since Release 2.2.0 */ public function startTestSuite(PHPUnit_Framework_TestSuite $suite) { - } /** * A test suite ended. * - * @param PHPUnit_Framework_TestSuite $suite - * @since Method available since Release 2.2.0 */ public function endTestSuite(PHPUnit_Framework_TestSuite $suite) { - } /** * A test started. * - * @param PHPUnit_Framework_Test $test */ public function startTest(PHPUnit_Framework_Test $test) { - } /** * A test ended. * - * @param PHPUnit_Framework_Test $test - * @param float $time + * @param float $time */ public function endTest(PHPUnit_Framework_Test $test, $time) { - } } diff --git a/tests/Stubs/DocumentManager.php b/tests/Stubs/DocumentManager.php index 7722c39403..ab8f2153be 100644 --- a/tests/Stubs/DocumentManager.php +++ b/tests/Stubs/DocumentManager.php @@ -1,15 +1,16 @@ classMetadatas[$className])) { + if (! isset($this->classMetadatas[$className])) { throw new \InvalidArgumentException('Metadata for class ' . $className . ' doesn\'t exist, try calling ->setClassMetadata() first'); } return $this->classMetadatas[$className]; } - } diff --git a/tests/bootstrap.php b/tests/bootstrap.php index ad0856a1f4..4483540f04 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -1,8 +1,10 @@ new DocumentManagerHelper($dm), -)); +]); diff --git a/tools/sandbox/config.php b/tools/sandbox/config.php index 2849e88485..a206a98d27 100644 --- a/tools/sandbox/config.php +++ b/tools/sandbox/config.php @@ -1,12 +1,14 @@ setHelperSet($helperSet); } -$app->addCommands(array( - new \Doctrine\ODM\MongoDB\Tools\Console\Command\GenerateHydratorsCommand(), - new \Doctrine\ODM\MongoDB\Tools\Console\Command\GenerateProxiesCommand(), - new \Doctrine\ODM\MongoDB\Tools\Console\Command\QueryCommand(), - new \Doctrine\ODM\MongoDB\Tools\Console\Command\ClearCache\MetadataCommand(), - new \Doctrine\ODM\MongoDB\Tools\Console\Command\Schema\CreateCommand(), - new \Doctrine\ODM\MongoDB\Tools\Console\Command\Schema\DropCommand(), - new \Doctrine\ODM\MongoDB\Tools\Console\Command\Schema\UpdateCommand(), -)); +$app->addCommands([ + new GenerateHydratorsCommand(), + new GenerateProxiesCommand(), + new QueryCommand(), + new MetadataCommand(), + new CreateCommand(), + new DropCommand(), + new UpdateCommand(), +]); $app->run();