MongoDBRefTest.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace Alcaeus\MongoDbAdapter\Tests;
  3. /**
  4. * @author alcaeus <alcaeus@alcaeus.org>
  5. */
  6. class MongoDBRefTest extends TestCase
  7. {
  8. public function testCreate()
  9. {
  10. $id = new \MongoId();
  11. $ref = \MongoDBRef::create('foo', $id);
  12. $this->assertSame(['$ref' => 'foo', '$id' => $id], $ref);
  13. }
  14. public function testCreateWithDatabase()
  15. {
  16. $id = new \MongoId();
  17. $ref = \MongoDBRef::create('foo', $id, 'database');
  18. $this->assertSame(['$ref' => 'foo', '$id' => $id, '$db' => 'database'], $ref);
  19. }
  20. /**
  21. * @dataProvider dataIsRef
  22. */
  23. public function testIsRef($expected, $ref)
  24. {
  25. $this->assertSame($expected, \MongoDBRef::isRef($ref));
  26. }
  27. public static function dataIsRef()
  28. {
  29. $objectRef = new \stdClass();
  30. $objectRef->{'$ref'} = 'coll';
  31. $objectRef->{'$id'} = 'id';
  32. return [
  33. 'validRef' => [true, ['$ref' => 'coll', '$id' => 'id']],
  34. 'validRefWithDatabase' => [true, ['$ref' => 'coll', '$id' => 'id', '$db' => 'db']],
  35. 'refMissing' => [false, ['$id' => 'id']],
  36. 'idMissing' => [false, ['$ref' => 'coll']],
  37. 'objectRef' => [true, $objectRef],
  38. 'int' => [false, 5],
  39. ];
  40. }
  41. public function testGet()
  42. {
  43. $id = new \MongoId();
  44. $client = new \MongoClient();
  45. $db = $client->selectDB('mongo-php-adapter');
  46. $document = ['_id' => $id, 'foo' => 'bar'];
  47. $db->selectCollection('test')->insert($document);
  48. $fetchedRef = \MongoDBRef::get($db, ['$ref' => 'test', '$id' => $id]);
  49. $this->assertInternalType('array', $fetchedRef);
  50. $this->assertEquals($document, $fetchedRef);
  51. }
  52. public function testGetWithNonExistingDocument()
  53. {
  54. $client = new \MongoClient();
  55. $db = $client->selectDB('mongo-php-adapter');
  56. $this->assertNull(\MongoDBRef::get($db, ['$ref' => 'test', '$id' => 'foo']));
  57. }
  58. public function testGetWithInvalidRef()
  59. {
  60. $client = new \MongoClient();
  61. $db = $client->selectDB('mongo-php-adapter');
  62. $this->assertNull(\MongoDBRef::get($db, []));
  63. }
  64. }