TestCase.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace Alcaeus\MongoDbAdapter\Tests;
  3. use MongoDB\Client;
  4. abstract class TestCase extends \PHPUnit_Framework_TestCase
  5. {
  6. protected function tearDown()
  7. {
  8. $this->getCheckDatabase()->drop();
  9. }
  10. /**
  11. * @return \MongoDB\Database
  12. */
  13. protected function getCheckDatabase()
  14. {
  15. $client = new Client('mongodb://localhost', ['connect' => true]);
  16. return $client->selectDatabase('mongo-php-adapter');
  17. }
  18. /**
  19. * @param array|null $options
  20. * @return \MongoClient
  21. */
  22. protected function getClient($options = null)
  23. {
  24. $args = ['mongodb://localhost'];
  25. if ($options !== null) {
  26. $args[] = $options;
  27. }
  28. $reflection = new \ReflectionClass('MongoClient');
  29. return $reflection->newInstanceArgs($args);
  30. }
  31. /**
  32. * @param \MongoClient|null $client
  33. * @return \MongoDB
  34. */
  35. protected function getDatabase(\MongoClient $client = null)
  36. {
  37. if ($client === null) {
  38. $client = $this->getClient();
  39. }
  40. return $client->selectDB('mongo-php-adapter');
  41. }
  42. /**
  43. * @param string $name
  44. * @param \MongoDB|null $database
  45. * @return \MongoCollection
  46. */
  47. protected function getCollection($name = 'test', \MongoDB $database = null)
  48. {
  49. if ($database === null) {
  50. $database = $this->getDatabase();
  51. }
  52. return $database->selectCollection($name);
  53. }
  54. /**
  55. * @param string $prefix
  56. * @param \MongoDB|null $database
  57. * @return \MongoGridFS
  58. */
  59. protected function getGridFS($prefix = 'fs', \MongoDB $database = null)
  60. {
  61. if ($database === null) {
  62. $database = $this->getDatabase();
  63. }
  64. return $database->getGridFS($prefix);
  65. }
  66. /**
  67. * @return \MongoCollection
  68. */
  69. protected function prepareData()
  70. {
  71. $collection = $this->getCollection();
  72. $document = ['foo' => 'bar'];
  73. $collection->insert($document);
  74. unset($document['_id']);
  75. $collection->insert($document);
  76. $document = ['foo' => 'foo'];
  77. $collection->insert($document);
  78. return $collection;
  79. }
  80. }