Beispiel #1
0
 /**
  * Prepares the field to have a sequence. If $value is zero or not defined
  * a new auto-increment number will be "generated" for the collection of
  * the schema. The sequence generation is done by the SequenceService.
  *
  * @param int|null $value Value that will be evaluated.
  *
  * @return int
  */
 public function sequence(int $value = null)
 {
     if ($value) {
         return $value;
     }
     return Ioc::make(SequenceService::class)->getNextValue($this->collection ?: $this->entityClass);
 }
Beispiel #2
0
 public function testShouldCallMethodsPropertlywithFiveOrMoreArgument()
 {
     $container = m::mock(Container::class);
     $container->shouldReceive('method')->once()->with(1, 2, 3, 4, 5)->andReturn(true);
     Ioc::setContainer($container);
     Ioc::method(1, 2, 3, 4, 5);
 }
 /**
  * Constructs a new Mongolid connection. It uses the same constructor
  * parameters as the original MongoDB\Client constructor.
  *
  * @see   http://php.net/manual/en/mongodb-driver-manager.construct.php
  *
  * @param string $server         The specified connection string.
  * @param array  $options        The mongodb client options.
  * @param array  $driver_options The mongodb driver options when opening a connection.
  */
 public function __construct(string $server = 'mongodb://localhost:27017', array $options = ['connect' => true], array $driver_options = [])
 {
     // In order to work with PHP arrays instead of with objects
     $driver_options['typeMap'] = ['array' => 'array', 'document' => 'array'];
     $this->findDefaultDatabase($server);
     $parameters = [$server, $options, $driver_options];
     $this->rawManager = Ioc::make(Manager::class, $parameters);
     $this->rawConnection = Ioc::make(Client::class, $parameters);
 }
 public function testShouldRegisterConnectorWithUsernameAndPassword()
 {
     // Set
     $provider = new MongolidServiceProvider($this->app);
     config(['database.mongodb.default.database' => 'databaseName', 'database.mongodb.default.username' => 'us3r', 'database.mongodb.default.password' => 'p455']);
     // Actions
     $provider->registerConnector();
     $pool = Ioc::make(Pool::class);
     // Assertions
     $this->assertEquals('databaseName', $pool->getConnection()->defaultDatabase);
 }
 public function testShouldGetRawManager()
 {
     // Arrange
     $mongoManager = new Manager('mongodb://localhost:27017');
     $container = m::mock(Container::class)->makePartial();
     Ioc::setContainer($container);
     // Act
     $container->shouldReceive('make')->once()->with(Manager::class, m::any())->andReturn($mongoManager);
     // Assert
     $connection = new Connection();
     $this->assertEquals($mongoManager, $connection->getRawManager());
 }
 public function testShouldNotAutoIncrementSequenceIfValueIsNotNull()
 {
     $schema = m::mock(Schema::class . '[]');
     $sequenceService = m::mock(SequenceService::class);
     $value = 3;
     $schema->collection = 'resources';
     // Act
     Ioc::instance(SequenceService::class, $sequenceService);
     $sequenceService->shouldReceive('getNextValue')->with('resources')->never()->andReturn(7);
     // Should never be returned
     // Assertion
     $this->assertEquals(3, $schema->sequence($value));
 }
 public function testShouldGetDataMapperForEntitiesWithRegisteredSchemas()
 {
     // Arrange
     $manager = new Manager();
     $schema = m::mock(Schema::class);
     $dataMapper = m::mock(DataMapper::class)->makePartial();
     $schema->entityClass = 'Bacon';
     // Act
     Ioc::instance(DataMapper::class, $dataMapper);
     // Assert
     $manager->registerSchema($schema);
     $result = $manager->getMapper('Bacon');
     $this->assertEquals($dataMapper, $result);
     $this->assertAttributeEquals($schema, 'schema', $result);
 }
 /**
  * Register MongoDbConnector within the application.
  *
  * @return void
  */
 public function registerConnector()
 {
     $config = $this->app->make('config');
     MongolidIoc::setContainer($this->app);
     $connectionString = $this->buildConnectionString();
     $connection = new Connection($connectionString);
     $pool = new Pool();
     $eventService = new EventTriggerService();
     $eventService->registerEventDispatcher($this->app->make(LaravelEventTrigger::class));
     $pool->addConnection($connection);
     $this->app->instance(Pool::class, $pool);
     $this->app->instance(EventTriggerService::class, $eventService);
     $this->app->bind(CacheComponentInterface::class, function ($app) {
         return new LaravelCacheComponent($app[CacheRepository::class], $app[Serializer::class]);
     });
     $connection->defaultDatabase = $config->get('database.mongodb.default.database', 'mongolid');
 }
 /**
  * @dataProvider EntityAssemblerFixture
  */
 public function testShouldAssembleEntityForTheGivenSchema($inputValue, $availableSchemas, $inputSchema, $expectedOutput)
 {
     // Arrange
     $entityAssembler = new EntityAssembler();
     $schemas = [];
     foreach ($availableSchemas as $key => $value) {
         $schemas[$key] = m::mock(Schema::class . '[]');
         $schemas[$key]->entityClass = $value['entityClass'];
         $schemas[$key]->fields = $value['fields'];
     }
     // Act
     foreach ($schemas as $className => $instance) {
         Ioc::instance($className, $instance);
     }
     // Assert
     $result = $entityAssembler->assemble($inputValue, $schemas[$inputSchema]);
     $this->assertEquals($expectedOutput, $result);
 }
 public function testShouldGetOriginalCursorFromDatabaseAfterTheDocumentLimit()
 {
     // Arrange
     $documentsFromDb = [['name' => 'joe'], ['name' => 'doe']];
     $cursor = $this->getCachableCursor()->limit(150);
     $cacheComponent = m::mock(CacheComponentInterface::class);
     $rawCollection = m::mock();
     $this->setProtected($cursor, 'position', CacheableCursor::DOCUMENT_LIMIT + 1);
     $this->setProtected($cursor, 'collection', $rawCollection);
     // Act
     $cursor->shouldReceive('generateCacheKey')->never();
     Ioc::instance(CacheComponentInterface::class, $cacheComponent);
     $cacheComponent->shouldReceive('get')->with('find:collection:123', null)->never();
     $rawCollection->shouldReceive('find')->with([], ['skip' => CacheableCursor::DOCUMENT_LIMIT, 'limit' => 49])->andReturn(new ArrayIterator($documentsFromDb));
     $cacheComponent->shouldReceive('put')->never();
     // Assert
     $this->assertEquals(new IteratorIterator(new ArrayIterator($documentsFromDb)), $this->callProtected($cursor, 'getCursor'));
 }
 public function testShouldExecuteBulkWrite()
 {
     $entity = m::mock(HasSchemaInterface::class);
     $schema = m::mock(Schema::class);
     $entity->schema = $schema;
     $mongoBulkWrite = m::mock(new MongoBulkWrite());
     $pool = m::mock(Pool::class);
     $connection = m::mock(Connection::class);
     $manager = m::mock(Manager::class);
     $connection->defaultDatabase = 'foo';
     $schema->collection = 'bar';
     $namespace = 'foo.bar';
     Ioc::instance(Pool::class, $pool);
     // Expect
     $entity->shouldReceive('getSchema')->once()->with()->andReturn($schema);
     $pool->shouldReceive('getConnection')->once()->with()->andReturn($connection);
     $connection->shouldReceive('getRawManager')->once()->with()->andReturn($manager);
     $manager->shouldReceive('executeBulkWrite')->once()->with($namespace, $mongoBulkWrite, m::type(WriteConcern::class))->andReturn(true);
     $bulkWrite = m::mock(BulkWrite::class . '[getBulkWrite]', [$entity]);
     $bulkWrite->shouldReceive('getBulkWrite')->once()->with()->andReturn($mongoBulkWrite);
     // Act
     $bulkWrite->execute();
 }
Beispiel #12
0
 /**
  * Unserializes this object. Re-creating the database connection.
  *
  * @param mixed $serialized Serialized cursor.
  *
  * @return void
  */
 public function unserialize($serialized)
 {
     $attributes = unserialize($serialized);
     $conn = Ioc::make(Pool::class)->getConnection();
     $db = $conn->defaultDatabase;
     $collectionObject = $conn->getRawConnection()->{$db}->{$attributes['collection']};
     foreach ($attributes as $key => $value) {
         $this->{$key} = $value;
     }
     $this->collection = $collectionObject;
 }
Beispiel #13
0
 public function testShouldSerializeAnActiveCursor()
 {
     // Arrange
     $pool = m::mock(Pool::class);
     $conn = m::mock(Connection::class);
     $schema = new DynamicSchema();
     $cursor = $this->getCursor($schema, null, 'find', [[]]);
     $driverCollection = $this->getDriverCollection();
     $this->setProtected($cursor, 'collection', $driverCollection);
     // Act
     Ioc::instance(Pool::class, $pool);
     $pool->shouldReceive('getConnection')->andReturn($conn);
     $conn->shouldReceive('getRawConnection')->andReturn($conn);
     $conn->defaultDatabase = 'db';
     $conn->db = $conn;
     $conn->my_collection = $driverCollection;
     // Return the same driver Collection
     // Assert
     $result = unserialize(serialize($cursor));
     $this->assertEquals($cursor, $result);
 }
 protected function getEventService()
 {
     if (!($this->eventService ?? false)) {
         $this->eventService = m::mock(EventTriggerService::class);
         Ioc::instance(EventTriggerService::class, $this->eventService);
     }
     return $this->eventService;
 }
 /**
  * Returns the a valid instance from Ioc.
  *
  * @throws NoCollectionNameException Throws exception when has no collection filled.
  *
  * @return mixed
  */
 private static function getDataMapperInstance()
 {
     $instance = Ioc::make(get_called_class());
     if (!$instance->getCollectionName()) {
         throw new NoCollectionNameException();
     }
     return $instance->getDataMapper();
 }
 public function testShouldGetSchemaIfFieldsIsTheClassName()
 {
     // Arrage
     $this->setProtected($this->entity, 'fields', 'MySchemaClass');
     $schema = m::mock(Schema::class);
     // Act
     Ioc::instance('MySchemaClass', $schema);
     // Assert
     $this->assertEquals($schema, $this->entity->getSchema());
 }
 /**
  * Assembly multiple documents for the given $schemaClass recursively.
  *
  * @param mixed  $value       A value of an embeded field containing entity data to be assembled.
  * @param string $schemaClass The schemaClass to be used when assembling the entities within $value.
  *
  * @return mixed
  */
 protected function assembleDocumentsRecursively($value, string $schemaClass)
 {
     $value = (array) $value;
     if (empty($value)) {
         return;
     }
     $schema = Ioc::make($schemaClass);
     $assembler = Ioc::make(self::class);
     if (!isset($value[0])) {
         $value = [$value];
     }
     foreach ($value as $key => $subValue) {
         $value[$key] = $assembler->assemble($subValue, $schema);
     }
     return $value;
 }
 /**
  * Generates an unique cache key for the cursor in it's current state.
  *
  * @return string Cache key to identify the query of the current cursor.
  */
 protected function generateCacheKey() : string
 {
     $serializer = Ioc::make(Serializer::class);
     return sprintf('%s:%s:%s', $this->command, $this->collection->getNamespace(), md5($serializer->serialize($this->params)));
 }
Beispiel #19
0
 /**
  * Removes a document _id reference from an attribute. It will remove the
  * _id of the given $obj from inside the given $field.
  *
  * @param string $field Field where the reference is stored.
  * @param mixed  $obj   Document, model instance or _id that have been referenced by $field.
  *
  * @return void
  */
 public function detach(string $field, &$obj)
 {
     $embedder = Ioc::make(DocumentEmbedder::class);
     $embedder->detach($this, $field, $obj);
 }
 /**
  * @dataProvider embedsScenarios
  */
 public function testShouldEmbedsMany($entity, $field, $fieldValue, $expectedItems)
 {
     // Set
     $model = m::mock(ActiveRecord::class . '[]');
     $cursorFactory = m::mock(CursorFactory::class);
     $cursor = m::mock(EmbeddedCursor::class);
     $document = $fieldValue;
     $model->{$field} = $document;
     $instantiableClass = $entity instanceof Schema ? 'stdClass' : get_class($entity);
     // Act
     Ioc::instance(CursorFactory::class, $cursorFactory);
     $cursorFactory->shouldReceive('createEmbeddedCursor')->once()->with($instantiableClass, $expectedItems)->andReturn($cursor);
     // Assert
     $result = $this->callProtected($model, 'embedsMany', [get_class($entity), $field]);
     $this->assertEquals($cursor, $result);
 }
Beispiel #21
0
 /**
  * Constructs a connection pool.
  */
 public function __construct()
 {
     $this->connections = Ioc::make('SplQueue');
 }
Beispiel #22
0
 /**
  * Triggers an event. May return if that event had success.
  *
  * @param string $event  Identification of the event.
  * @param mixed  $entity Event payload.
  * @param bool   $halt   True if the return of the event handler will be used in a conditional.
  *
  * @return mixed Event handler return.
  */
 protected function fireEvent(string $event, $entity, bool $halt = false)
 {
     $event = "mongolid.{$event}: " . get_class($entity);
     $this->eventService ? $this->eventService : ($this->eventService = Ioc::make(EventTriggerService::class));
     return $this->eventService->fire($event, $entity, $halt);
 }
 public function testShouldMapAnArrayValueToAnotherSchemaSchema()
 {
     // Arrange
     $schema = m::mock(Schema::class);
     $mySchema = m::mock(Schema::class);
     $schemaMapper = new SchemaMapper($schema);
     $value = ['foo' => 'bar'];
     $test = $this;
     // Act
     Ioc::instance('Xd\\MySchema', $mySchema);
     // Register MySchema in Ioc
     // When instantiating the SchemaMapper with the specified $param as dependency
     Ioc::bind(SchemaMapper::class, function ($container, $params) use($value, $mySchema, $test) {
         // Check if mySchema has been injected correctly
         $test->assertSame($mySchema, $params[0]);
         // Instantiate a SchemaMapper with mySchema
         $anotherSchemaMapper = m::mock(SchemaMapper::class, [$params[0]]);
         // Set expectation to receiva a map call
         $anotherSchemaMapper->shouldReceive('map')->once()->with($value)->andReturn(['foo' => 'PARSED']);
         return $anotherSchemaMapper;
     });
     //Assert
     $this->assertEquals([['foo' => 'PARSED']], $this->callProtected($schemaMapper, 'mapToSchema', [$value, 'Xd\\MySchema']));
 }
Beispiel #24
0
 /**
  * Initializes the Mongolid manager.
  *
  * @return void
  */
 protected function init()
 {
     if ($this->container) {
         return;
     }
     $this->container = new Container();
     $this->connectionPool = new Pool();
     $this->cacheComponent = new CacheComponent();
     $this->container->instance(Pool::class, $this->connectionPool);
     $this->container->instance(CacheComponentInterface::class, $this->cacheComponent);
     Ioc::setContainer($this->container);
     static::$singleton = $this;
 }
 /**
  * Instantiate another SchemaMapper with the given $schemaClass and maps
  * the given $value.
  *
  * @param mixed  $value       Value that will be mapped.
  * @param string $schemaClass Class that will be passed to the new SchemaMapper constructor.
  *
  * @return mixed
  */
 protected function mapToSchema($value, string $schemaClass)
 {
     $value = (array) $value;
     $schema = Ioc::make($schemaClass);
     $mapper = Ioc::make(self::class, [$schema]);
     if (!isset($value[0])) {
         $value = [$value];
     }
     foreach ($value as $key => $subValue) {
         $value[$key] = $mapper->map($subValue);
     }
     return $value;
 }
Beispiel #26
0
 /**
  * Execute the BulkWrite, using a connection from the Pool.
  * The collection is inferred from entity's collection name.
  *
  * @param int $writeConcern
  *
  * @return \MongoDB\Driver\WriteResult
  */
 public function execute($writeConcern = 1)
 {
     $connection = Ioc::make(Pool::class)->getConnection();
     $manager = $connection->getRawManager();
     $namespace = $connection->defaultDatabase . '.' . $this->schema->collection;
     return $manager->executeBulkWrite($namespace, $this->getBulkWrite(), new WriteConcern($writeConcern));
 }
 /**
  * Iterator interface current. Return a model object
  * with cursor document. (used in foreach).
  *
  * @return mixed
  */
 public function current()
 {
     if (!$this->valid()) {
         return;
     }
     $document = $this->items[$this->position];
     if ($document instanceof $this->entityClass) {
         return $document;
     }
     $schema = $this->getSchemaForEntity();
     $entityAssembler = Ioc::make(EntityAssembler::class, [$schema]);
     return $entityAssembler->assemble($document, $schema);
 }
Beispiel #28
0
<?php

include 'vendor/autoload.php';
if (!extension_loaded('mongodb')) {
    throw new Exception('MongoClient PHP extension required.', 1);
}
use Illuminate\Container\Container;
use Mongolid\Container\Ioc;
Ioc::setContainer(new Container());
 /**
  * Create a new instance of the model.
  *
  * @return \MongolidLaravel\MongoLidModel
  */
 protected function createModel()
 {
     $class = '\\' . ltrim($this->model, '\\');
     return Ioc::make($class);
 }
 /**
  * {@inheritdoc}
  */
 public function setUp()
 {
     parent::setUp();
     Ioc::setContainer($this->app);
 }