MongoIdTest.php 2.2 KB

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