MongoIdTest.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. }
  22. public function testCreateWithString()
  23. {
  24. $original = '54203e08d51d4a1f868b456e';
  25. $id = new \MongoId($original);
  26. $this->assertSame($original, (string) $id);
  27. $this->assertSame(9127278, $id->getInc());
  28. $this->assertSame(1411399176, $id->getTimestamp());
  29. $this->assertSame(34335, $id->getPID());
  30. }
  31. /**
  32. * @expectedException \MongoException
  33. * @expectedExceptionMessage Invalid object ID
  34. */
  35. public function testCreateWithInvalidStringThrowsMongoException()
  36. {
  37. new \MongoId('invalid');
  38. }
  39. public function testCreateWithObjectId()
  40. {
  41. $this->skipTestIf(extension_loaded('mongo'));
  42. $original = '54203e08d51d4a1f868b456e';
  43. $objectId = new ObjectID($original);
  44. $id = new \MongoId($objectId);
  45. $this->assertSame($original, (string) $id);
  46. $this->assertAttributeNotSame($objectId, 'objectID', $id);
  47. }
  48. /**
  49. * @dataProvider dataIsValid
  50. */
  51. public function testIsValid($expected, $value)
  52. {
  53. $this->skipTestIf($value instanceof ObjectID && extension_loaded('mongo'));
  54. $this->assertSame($expected, \MongoId::isValid($value));
  55. }
  56. public static function dataIsValid()
  57. {
  58. $original = '54203e08d51d4a1f868b456e';
  59. return [
  60. 'validId' => [true, '' . $original . ''],
  61. 'MongoId' => [true, new \MongoId($original)],
  62. 'ObjectID' => [true, new ObjectID($original)],
  63. 'invalidString' => [false, 'abc'],
  64. ];
  65. }
  66. }