MongoIdTest.php 2.7 KB

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