MongoIdTest.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace Alcaeus\MongoDbAdapter\Tests\Mongo;
  3. use Alcaeus\MongoDbAdapter\Tests\TestCase;
  4. use MongoDB\BSON\ObjectID;
  5. /**
  6. * @author alcaeus <alcaeus@alcaeus.org>
  7. */
  8. class MongoIdTest extends TestCase
  9. {
  10. public function testCreateWithoutParameter()
  11. {
  12. $id = new \MongoId();
  13. $stringId = (string) $id;
  14. $this->assertSame(24, strlen($stringId));
  15. $this->assertSame($stringId, $id->{'$id'});
  16. $serialized = serialize($id);
  17. $this->assertSame(sprintf('C:7:"MongoId":24:{%s}', $stringId), $serialized);
  18. $unserialized = unserialize($serialized);
  19. $this->assertInstanceOf('MongoId', $unserialized);
  20. $this->assertSame($stringId, (string) $unserialized);
  21. $json = json_encode($id);
  22. $this->assertSame(sprintf('{"$id":"%s"}', $stringId), $json);
  23. }
  24. public function testCreateWithString()
  25. {
  26. $original = '54203e08d51d4a1f868b456e';
  27. $id = new \MongoId($original);
  28. $this->assertSame($original, (string) $id);
  29. $this->assertSame(9127278, $id->getInc());
  30. $this->assertSame(1411399176, $id->getTimestamp());
  31. $this->assertSame(34335, $id->getPID());
  32. }
  33. /**
  34. * @expectedException \MongoException
  35. * @expectedExceptionMessage Invalid object ID
  36. */
  37. public function testCreateWithInvalidStringThrowsMongoException()
  38. {
  39. new \MongoId('invalid');
  40. }
  41. public function testCreateWithObjectId()
  42. {
  43. $this->skipTestIf(extension_loaded('mongo'));
  44. $original = '54203e08d51d4a1f868b456e';
  45. $objectId = new ObjectID($original);
  46. $id = new \MongoId($objectId);
  47. $this->assertSame($original, (string) $id);
  48. $this->assertAttributeNotSame($objectId, 'objectID', $id);
  49. }
  50. /**
  51. * @dataProvider dataIsValid
  52. */
  53. public function testIsValid($expected, $value)
  54. {
  55. $this->skipTestIf($value instanceof ObjectID && extension_loaded('mongo'));
  56. $this->assertSame($expected, \MongoId::isValid($value));
  57. }
  58. public static function dataIsValid()
  59. {
  60. $original = '54203e08d51d4a1f868b456e';
  61. return [
  62. 'validId' => [true, '' . $original . ''],
  63. 'MongoId' => [true, new \MongoId($original)],
  64. 'ObjectID' => [true, new ObjectID($original)],
  65. 'invalidString' => [false, 'abc'],
  66. 'object' => [false, new \stdClass()],
  67. ];
  68. }
  69. }