DocumentsMatchConstraint.php 15.3 KB
Newer Older
1 2 3 4
<?php

namespace MongoDB\Tests\SpecTests;

5 6
use ArrayObject;
use InvalidArgumentException;
7 8 9 10 11 12 13 14 15 16 17 18 19
use MongoDB\BSON\BinaryInterface;
use MongoDB\BSON\DBPointer;
use MongoDB\BSON\Decimal128;
use MongoDB\BSON\Int64;
use MongoDB\BSON\Javascript;
use MongoDB\BSON\MaxKey;
use MongoDB\BSON\MinKey;
use MongoDB\BSON\ObjectId;
use MongoDB\BSON\Regex;
use MongoDB\BSON\Symbol;
use MongoDB\BSON\Timestamp;
use MongoDB\BSON\Undefined;
use MongoDB\BSON\UTCDateTime;
20 21 22
use MongoDB\Model\BSONArray;
use MongoDB\Model\BSONDocument;
use PHPUnit\Framework\Constraint\Constraint;
23 24 25 26 27 28
use PHPUnit\Framework\Constraint\IsInstanceOf;
use PHPUnit\Framework\Constraint\IsNull;
use PHPUnit\Framework\Constraint\IsType;
use PHPUnit\Framework\Constraint\LogicalAnd;
use PHPUnit\Framework\Constraint\LogicalNot;
use PHPUnit\Framework\Constraint\LogicalOr;
29
use RuntimeException;
30 31
use SebastianBergmann\Comparator\ComparisonFailure;
use SebastianBergmann\Comparator\Factory;
32
use stdClass;
33
use Symfony\Bridge\PhpUnit\ConstraintTrait;
34 35
use function array_values;
use function get_class;
36
use function gettype;
37 38 39 40
use function in_array;
use function is_array;
use function is_object;
use function is_scalar;
41
use function method_exists;
42
use function sprintf;
43
use const PHP_INT_SIZE;
44 45 46 47 48 49 50 51

/**
 * Constraint that checks if one document matches another.
 *
 * The expected value is passed in the constructor.
 */
class DocumentsMatchConstraint extends Constraint
{
52 53
    use ConstraintTrait;

54
    /** @var boolean */
55
    private $ignoreExtraKeysInRoot = false;
56 57

    /** @var boolean */
58
    private $ignoreExtraKeysInEmbedded = false;
59 60

    /** @var array */
61
    private $placeholders = [];
62 63 64

    /**
     * TODO: This is not currently used, but was preserved from the design of
65 66 67
     * TestCase::assertMatchesDocument(), which would sort keys and then compare
     * documents as JSON strings. If the TODO item in matches() is implemented
     * to make document comparisons more efficient, we may consider supporting
68 69 70 71
     * this option.
     *
     * @var boolean
     */
72
    private $sortKeys = false;
73 74

    /** @var BSONArray|BSONDocument */
75 76
    private $value;

77 78 79 80 81 82
    /** @var ComparisonFailure|null */
    private $lastFailure;

    /** @var Factory */
    private $comparatorFactory;

83 84 85 86 87 88
    /**
     * Creates a new constraint.
     *
     * @param array|object $value
     * @param boolean      $ignoreExtraKeysInRoot     If true, ignore extra keys within the root document
     * @param boolean      $ignoreExtraKeysInEmbedded If true, ignore extra keys within embedded documents
89
     * @param array        $placeholders              Placeholders for any value
90
     */
91
    public function __construct($value, $ignoreExtraKeysInRoot = false, $ignoreExtraKeysInEmbedded = false, array $placeholders = [])
92 93 94 95
    {
        $this->value = $this->prepareBSON($value, true, $this->sortKeys);
        $this->ignoreExtraKeysInRoot = $ignoreExtraKeysInRoot;
        $this->ignoreExtraKeysInEmbedded = $ignoreExtraKeysInEmbedded;
96
        $this->placeholders = $placeholders;
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
        $this->comparatorFactory = Factory::getInstance();
    }

    public function evaluate($other, $description = '', $returnResult = false)
    {
        /* TODO: If ignoreExtraKeys and sortKeys are both false, then we may be
         * able to skip preparation, convert both documents to extended JSON,
         * and compare strings.
         *
         * If ignoreExtraKeys is false and sortKeys is true, we still be able to
         * compare JSON strings but will still require preparation to sort keys
         * in all documents and sub-documents. */
        $other = $this->prepareBSON($other, true, $this->sortKeys);

        $success = false;
        $this->lastFailure = null;

        try {
            $this->assertEquals($this->value, $other, $this->ignoreExtraKeysInRoot);
            $success = true;
        } catch (RuntimeException $e) {
            $this->lastFailure = new ComparisonFailure(
                $this->value,
                $other,
                $this->exporter()->export($this->value),
                $this->exporter()->export($other),
                false,
                $e->getMessage()
            );
        }

        if ($returnResult) {
            return $success;
        }

132
        if (! $success) {
133 134
            $this->fail($other, $description, $this->lastFailure);
        }
135 136
    }

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
    /**
     * @param string $expectedType
     * @param mixed  $actualValue
     */
    private function assertBSONType($expectedType, $actualValue)
    {
        switch ($expectedType) {
            case 'double':
                (new IsType('float'))->evaluate($actualValue);

                return;
            case 'string':
                (new IsType('string'))->evaluate($actualValue);

                return;
            case 'object':
                $constraints = [
                    new IsType('object'),
                    new LogicalNot(new IsInstanceOf(BSONArray::class)),
                ];

                // LogicalAnd::fromConstraints was introduced in PHPUnit 6.5.0.
                // This check can be removed when the PHPUnit dependency is bumped to that version
                if (method_exists(LogicalAnd::class, 'fromConstraints')) {
                    $constraint = LogicalAnd::fromConstraints(...$constraints);
                } else {
                    $constraint = new LogicalAnd();
                    $constraint->setConstraints($constraints);
                }

                $constraint->evaluate($actualValue);

                return;
            case 'array':
                $constraints = [
                    new IsType('array'),
                    new IsInstanceOf(BSONArray::class),
                ];

                // LogicalOr::fromConstraints was introduced in PHPUnit 6.5.0.
                // This check can be removed when the PHPUnit dependency is bumped to that version
                if (method_exists(LogicalOr::class, 'fromConstraints')) {
                    $constraint = LogicalOr::fromConstraints(...$constraints);
                } else {
                    $constraint = new LogicalOr();
                    $constraint->setConstraints($constraints);
                }

                $constraint->evaluate($actualValue);

                return;
            case 'binData':
                (new IsInstanceOf(BinaryInterface::class))->evaluate($actualValue);

                return;
            case 'undefined':
                (new IsInstanceOf(Undefined::class))->evaluate($actualValue);

                return;
            case 'objectId':
                (new IsInstanceOf(ObjectId::class))->evaluate($actualValue);

                return;
            case 'boolean':
                (new IsType('bool'))->evaluate($actualValue);

                return;
            case 'date':
                (new IsInstanceOf(UTCDateTime::class))->evaluate($actualValue);

                return;
            case 'null':
                (new IsNull())->evaluate($actualValue);

                return;
            case 'regex':
                (new IsInstanceOf(Regex::class))->evaluate($actualValue);

                return;
            case 'dbPointer':
                (new IsInstanceOf(DBPointer::class))->evaluate($actualValue);

                return;
            case 'javascript':
                (new IsInstanceOf(Javascript::class))->evaluate($actualValue);

                return;
            case 'symbol':
                (new IsInstanceOf(Symbol::class))->evaluate($actualValue);

                return;
            case 'int':
                (new IsType('int'))->evaluate($actualValue);

                return;
            case 'timestamp':
                (new IsInstanceOf(Timestamp::class))->evaluate($actualValue);

                return;
            case 'long':
                if (PHP_INT_SIZE == 4) {
                    (new IsInstanceOf(Int64::class))->evaluate($actualValue);
                } else {
                    (new IsType('int'))->evaluate($actualValue);
                }

                return;
            case 'decimal':
                (new IsInstanceOf(Decimal128::class))->evaluate($actualValue);

                return;
            case 'minKey':
                (new IsInstanceOf(MinKey::class))->evaluate($actualValue);

                return;
            case 'maxKey':
                (new IsInstanceOf(MaxKey::class))->evaluate($actualValue);

                return;
        }
    }

259 260 261 262 263 264
    /**
     * Compares two documents recursively.
     *
     * @param ArrayObject $expected
     * @param ArrayObject $actual
     * @param boolean     $ignoreExtraKeys
265
     * @param string      $keyPrefix
266 267
     * @throws RuntimeException if the documents do not match
     */
268
    private function assertEquals(ArrayObject $expected, ArrayObject $actual, $ignoreExtraKeys, $keyPrefix = '')
269 270
    {
        if (get_class($expected) !== get_class($actual)) {
271 272 273 274 275
            throw new RuntimeException(sprintf(
                '%s is not instance of expected class "%s"',
                $this->exporter()->shortenedExport($actual),
                get_class($expected)
            ));
276 277 278 279 280
        }

        foreach ($expected as $key => $expectedValue) {
            $actualHasKey = $actual->offsetExists($key);

281
            if (! $actualHasKey) {
282
                throw new RuntimeException(sprintf('$actual is missing key: "%s"', $keyPrefix . $key));
283 284
            }

285 286 287 288
            if (in_array($expectedValue, $this->placeholders, true)) {
                continue;
            }

289 290
            $actualValue = $actual[$key];

291 292 293 294 295
            if ($expectedValue instanceof BSONDocument && isset($expectedValue['$$type'])) {
                $this->assertBSONType($expectedValue['$$type'], $actualValue);
                continue;
            }

296 297
            if (($expectedValue instanceof BSONArray && $actualValue instanceof BSONArray) ||
                ($expectedValue instanceof BSONDocument && $actualValue instanceof BSONDocument)) {
298
                $this->assertEquals($expectedValue, $actualValue, $this->ignoreExtraKeysInEmbedded, $keyPrefix . $key . '.');
299 300 301
                continue;
            }

302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
            if (is_scalar($expectedValue) && is_scalar($actualValue)) {
                if ($expectedValue !== $actualValue) {
                    throw new ComparisonFailure(
                        $expectedValue,
                        $actualValue,
                        '',
                        '',
                        false,
                        sprintf('Field path "%s": %s', $keyPrefix . $key, 'Failed asserting that two values are equal.')
                    );
                }

                continue;
            }

317 318 319
            $expectedType = is_object($expectedValue) ? get_class($expectedValue) : gettype($expectedValue);
            $actualType = is_object($expectedValue) ? get_class($actualValue) : gettype($actualValue);

320
            // Workaround for ObjectComparator printing the whole actual object
321
            if ($expectedType !== $actualType) {
322 323 324 325 326 327
                throw new ComparisonFailure(
                    $expectedValue,
                    $actualValue,
                    '',
                    '',
                    false,
328
                    sprintf(
329
                        'Field path "%s": %s is not instance of expected type "%s".',
330 331
                        $keyPrefix . $key,
                        $this->exporter()->shortenedExport($actualValue),
332
                        $expectedType
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
                    )
                );
            }

            try {
                $this->comparatorFactory->getComparatorFor($expectedValue, $actualValue)->assertEquals($expectedValue, $actualValue);
            } catch (ComparisonFailure $failure) {
                throw new ComparisonFailure(
                    $expectedValue,
                    $actualValue,
                    '',
                    '',
                    false,
                    sprintf('Field path "%s": %s', $keyPrefix . $key, $failure->getMessage())
                );
348 349 350 351 352 353 354 355
            }
        }

        if ($ignoreExtraKeys) {
            return;
        }

        foreach ($actual as $key => $value) {
356
            if (! $expected->offsetExists($key)) {
357
                throw new RuntimeException(sprintf('$actual has extra key: "%s"', $keyPrefix . $key));
358 359 360 361
            }
        }
    }

362 363 364 365 366 367 368 369 370 371 372 373 374 375
    private function doAdditionalFailureDescription($other)
    {
        if ($this->lastFailure === null) {
            return '';
        }

        return $this->lastFailure->getMessage();
    }

    private function doFailureDescription($other)
    {
        return 'two BSON objects are equal';
    }

376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
    private function doMatches($other)
    {
        /* TODO: If ignoreExtraKeys and sortKeys are both false, then we may be
         * able to skip preparation, convert both documents to extended JSON,
         * and compare strings.
         *
         * If ignoreExtraKeys is false and sortKeys is true, we still be able to
         * compare JSON strings but will still require preparation to sort keys
         * in all documents and sub-documents. */
        $other = $this->prepareBSON($other, true, $this->sortKeys);

        try {
            $this->assertEquals($this->value, $other, $this->ignoreExtraKeysInRoot);
        } catch (RuntimeException $e) {
            return false;
        }

        return true;
    }

    private function doToString()
    {
398
        return 'matches ' . $this->exporter()->export($this->value);
399 400
    }

401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
    /**
     * Prepare a BSON document or array for comparison.
     *
     * The argument will be converted to a BSONArray or BSONDocument based on
     * its type and keys. Keys within documents will optionally be sorted. Each
     * value within the array or document will then be prepared recursively.
     *
     * @param array|object $bson
     * @param boolean      $isRoot   If true, ensure an array value is converted to a document
     * @param boolean      $sortKeys
     * @return BSONDocument|BSONArray
     * @throws InvalidArgumentException if $bson is not an array or object
     */
    private function prepareBSON($bson, $isRoot, $sortKeys = false)
    {
416
        if (! is_array($bson) && ! is_object($bson)) {
417 418 419 420 421 422 423 424
            throw new InvalidArgumentException('$bson is not an array or object');
        }

        if ($isRoot && is_array($bson)) {
            $bson = (object) $bson;
        }

        if ($bson instanceof BSONArray || (is_array($bson) && $bson === array_values($bson))) {
425
            if (! $bson instanceof BSONArray) {
426 427 428
                $bson = new BSONArray($bson);
            }
        } else {
429
            if (! $bson instanceof BSONDocument) {
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
                $bson = new BSONDocument((array) $bson);
            }

            if ($sortKeys) {
                $bson->ksort();
            }
        }

        foreach ($bson as $key => $value) {
            if ($value instanceof BSONArray || (is_array($value) && $value === array_values($value))) {
                $bson[$key] = $this->prepareBSON($value, false, $sortKeys);
                continue;
            }

            if ($value instanceof BSONDocument || $value instanceof stdClass || is_array($value)) {
                $bson[$key] = $this->prepareBSON($value, false, $sortKeys);
                continue;
            }
448 449 450 451 452 453

            /* Convert Int64 objects to integers on 64-bit platforms for
             * compatibility reasons. */
            if ($value instanceof Int64 && PHP_INT_SIZE != 4) {
                $bson[$key] = (int) ((string) $value);
            }
454 455 456 457 458
        }

        return $bson;
    }
}