MongoIdTest.php 2.1 KB

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