/** * Abstract test * * @param mixed $value1 first value to push * @param mixed $value2 second value to push * @param array $expectedList expected list, stored in db * @param int $fieldName name of field, where values pushed: one of self::FIELD_NAME_* * @param bool $isDocumentSaved is document already stored to db before push */ private function doPushTest($value1, $value2, $expectedList, $fieldName, $isDocumentSaved) { // create document $doc = $this->collection->createDocument($this->initialDocument); // test push to saved or new document if ($isDocumentSaved) { $doc->save(); } // prepare expected value switch ($fieldName) { case self::FIELD_NAME_SCALAR: $expectedList = array_merge(array($this->initialDocument[$fieldName]), $expectedList); break; case self::FIELD_NAME_LIST: $expectedList = array_merge($this->initialDocument[$fieldName], $expectedList); break; } // push single to empty $doc->push($fieldName, $value1)->push($fieldName, $value2); // test document in identity map after push before save $this->assertEquals($expectedList, $doc->get($fieldName)); $doc->save(); // test document in identity map after push after save $this->assertEquals($expectedList, $this->collection->getDocument($doc->getId())->get($fieldName)); // test document in db $this->assertEquals($expectedList, $this->collection->getDocumentDirectly($doc->getId())->get($fieldName)); }
/** * Get document instance * * @return \Sokil\Mongo\Document */ public function getDocument() { $data = $this->toArray(); // restore document id $data['_id'] = $data['__documentId__']; // unset meta fields unset($data['__date__'], $data['__documentId__']); return $this->baseCollection->hydrate($data); }
public function testDetach() { $document = $this->collection->createDocument(array('param' => 'value')); $this->assertFalse($this->persistence->contains($document)); // attach document $this->persistence->persist($document); // check if document in persistence $this->assertTrue($this->persistence->contains($document)); // detach document $this->persistence->detach($document); // check if document in persistence $this->assertFalse($this->persistence->contains($document)); }
/** * Move selected documents to another collection. * Dociuments will be removed from source collection only after * copying them to target collection. * * @param type $targetCollectionName * @param type $targetDatabaseName Target database name. If not specified - use current */ public function moveToCollection($targetCollectionName, $targetDatabaseName = null) { // copy to target $this->copyToCollection($targetCollectionName, $targetDatabaseName); // remove from source $this->collection->deleteDocuments($this->expression); }
public function testDelete() { // insert $this->collection->batchInsert(array(array('a' => 1), array('a' => 2), array('a' => 3), array('a' => 4), array('a' => 5), array('a' => 6))); // delete $batch = new BatchDelete($this->collection); $batch->delete(array('a' => 2))->delete($this->collection->expression()->where('a', 4))->delete(function (Expression $e) { $e->where('a', 6); })->execute(); // test $result = $this->collection->findAsArray()->sort(array('a' => 1))->map(function ($data) { unset($data['_id']); return $data; }); $this->assertEquals(array_values($result), array(array('a' => 1), array('a' => 3), array('a' => 5))); }
public function testClearTriggeredErrors() { $document = $this->collection->createDocument()->triggerError('someField', 'someRule', 'someMessage'); $this->assertTrue($document->hasErrors()); $document->clearTriggeredErrors(); $this->assertFalse($document->hasErrors()); }
public function testHashEquals() { $queryBuilder1 = $this->collection->find()->field('_id')->field('ineterests')->sort(array('age' => 1, 'gender' => -1))->limit(10, 20)->whereAll('interests', array('php', 'snowboard')); $queryBuilder2 = $this->collection->find()->sort(array('gender' => -1, 'age' => 1))->field('ineterests')->whereAll('interests', array('php', 'snowboard'))->field('_id')->limit(10, 20); $queryBuilder3 = $this->collection->find()->sort(array('age' => 1))->whereAll('interests', array('php', 'snowboard'))->field('_id')->limit(10, 20); $this->assertEquals($queryBuilder1->getHash(), $queryBuilder2->getHash()); $this->assertNotEquals($queryBuilder1->getHash(), $queryBuilder3->getHash()); }
/** * @expectedException \Sokil\Mongo\Exception * @expectedExceptionMessage Wrong pipeline specified */ public function testExplainAggregate_WrongArgument() { // define db version where aggregate explanation supported $clientMock = $this->getMock('\\Sokil\\Mongo\\Client', array('getDbVersion')); $clientMock->expects($this->once())->method('getDbVersion')->will($this->returnValue('2.6.0')); $clientMock->setMongoClient($this->collection->getDatabase()->getClient()->getMongoClient()); $this->collection = $clientMock->getDatabase('test')->getCollection('phpmongo_test_collection')->explainAggregate('wrong_argument'); }
public function testAddValidatorNamespace() { $document = $this->collection->createDocument()->addValidatorNamespace('\\Vendor\\Mongo\\Validator\\'); $reflectionClass = new \ReflectionClass($document); $property = $reflectionClass->getProperty('validatorNamespaces'); $property->setAccessible(true); $namespaces = $property->getValue($document); $this->assertNotEquals(false, array_search('\\Vendor\\Mongo\\Validator', $namespaces)); }
public function testExpressionWithinPolygon() { $this->collection->ensure2dIndex('point'); $point1Id = $this->collection->createDocument()->setLegacyPoint('point', 5, 4)->save()->getId(); $point2Id = $this->collection->createDocument()->setLegacyPoint('point', 50, 40)->save()->getId(); $point = $this->collection->find()->withinPolygon('point', array(array(0, 0), array(0, 10), array(10, 10), array(10, 0)))->findOne(); $this->assertNotEmpty($point); $this->assertEquals($point1Id, $point->getId()); }
public function testCancelOperation_BeforeValidate() { $testCase = $this; $this->collection->createDocument()->onBeforeValidate(function (\Sokil\Mongo\Event $event, $eventName, $dispatcher) { $event->cancel(); })->onAfterValidate(function (\Sokil\Mongo\Event $event, $eventName, $dispatcher) use($testCase) { $testCase->fail('Validation must be cancelled'); })->validate(); }
public function testBehaviorInCursor() { $db = $this->collection->getDatabase(); $db->map('col', array('behaviors' => array('get42' => new SomeBehavior()))); $collection = $db->getCollection('col'); $collection->insertMultiple(array(array('key' => 'value1'), array('key' => 'value2'), array('key' => 'value3'), array('key' => 'value4'), array('key' => 'value5')), false); foreach ($collection->find() as $document) { $this->assertEquals(42, $document->return42()); } }
public function testGetRelatedDocumentList() { $this->collection->disableDocumentPool(); $relatedDocument = $this->collection->createDocument(array('param' => 'value'))->save(); $document = $this->collection->createDocument()->pushReference('related', $relatedDocument)->save(); $foundRelatedDocumentList = $document->getReferencedDocumentList('related'); $this->assertSame(1, count($foundRelatedDocumentList)); $foundRelatedDocument = current($foundRelatedDocumentList); $this->assertEquals($relatedDocument->getId(), $foundRelatedDocument->getId()); }
public function testPaginatorIteratorInterface() { $d11 = $this->collection->createDocument(array('param1' => 1, 'param2' => 1))->save(); $d12 = $this->collection->createDocument(array('param1' => 1, 'param2' => 2))->save(); $d21 = $this->collection->createDocument(array('param1' => 2, 'param2' => 1))->save(); $d22 = $this->collection->createDocument(array('param1' => 2, 'param2' => 2))->save(); $pager = $this->collection->find()->paginate(20, 2); $this->assertEquals($d21->getId(), $pager->current()->getId()); $this->assertEquals((string) $d21->getId(), $pager->key()); $this->assertTrue($pager->valid()); $pager->next(); $this->assertEquals($d22->getId(), $pager->current()->getId()); $this->assertEquals((string) $d22->getId(), $pager->key()); $this->assertTrue($pager->valid()); $pager->next(); $this->assertFalse($pager->valid()); $pager->rewind(); $this->assertEquals($d21->getId(), $pager->current()->getId()); $this->assertEquals((string) $d21->getId(), $pager->key()); }
/** * @expectedException \Sokil\Mongo\Exception * @expectedExceptionMessage Keys not specified */ public function testInitIndexes_KeysNotSpecified() { $reflection = new \ReflectionClass($this->collection); $property = $reflection->getProperty('definition'); $property->setAccessible(true); $definition = $property->getValue($this->collection); $definition->setOption('index', array(array('unique' => true))); $this->collection->initIndexes(); $indexes = $this->collection->getIndexes(); $this->assertEquals(array('asc' => 1, 'desc' => -1), $indexes[1]['key']); $this->assertArrayHasKey('unique', $indexes[1]); }
public function testPush() { $this->collection->insertMultiple(array(array("_id" => 1, "item" => "abc", "price" => 10, "quantity" => 2, "date" => new \MongoDate(strtotime("2014-01-01T08:00:00Z"))), array("_id" => 2, "item" => "jkl", "price" => 20, "quantity" => 1, "date" => new \MongoDate(strtotime("2014-02-03T09:00:00Z"))), array("_id" => 3, "item" => "xyz", "price" => 5, "quantity" => 5, "date" => new \MongoDate(strtotime("2014-02-03T09:05:00Z"))), array("_id" => 4, "item" => "abc", "price" => 10, "quantity" => 10, "date" => new \MongoDate(strtotime("2014-02-15T08:00:00Z"))), array("_id" => 5, "item" => "xyz", "price" => 5, "quantity" => 10, "date" => new \MongoDate(strtotime("2014-02-15T09:05:00Z"))), array("_id" => 6, "item" => "xyz", "price" => 5, "quantity" => 5, "date" => new \MongoDate(strtotime("2014-02-15T12:05:10Z"))), array("_id" => 7, "item" => "xyz", "price" => 5, "quantity" => 10, "date" => new \MongoDate(strtotime("2014-02-15T14:12:12Z"))))); $pipeline = new Pipeline($this->collection); $pipeline->group(function ($stage) { /* @var $stage \Sokil\Mongo\Pipeline\GroupStage */ $stage->setId('$item')->push('itemsSold', array('quantity' => '$quantity', 'price' => '$price', 'quantityPrice' => array('$multiply' => array('$quantity', '$price')))); }); $result = $pipeline->aggregate(); $this->assertEquals('xyz', $result[0]['_id']); $this->assertEquals(5, $result[0]['itemsSold'][0]['quantity']); $this->assertEquals(5, $result[0]['itemsSold'][0]['price']); $this->assertEquals(25, $result[0]['itemsSold'][0]['quantityPrice']); }
public function delete() { if ($this->triggerEvent('beforeDelete')->isCancelled()) { return $this; } $status = $this->collection->getMongoCollection()->remove(array('_id' => $this->getId())); if (true !== $status && $status['ok'] != 1) { throw new \Sokil\Mongo\Exception(sprintf('Delete document error: %s', $status['err'])); } $this->triggerEvent('afterDelete'); // drop from document's pool $this->getCollection()->removeDocumentFromDocumentPool($this); return $this; }
/** * Check if document belongs to specified collection * * @deprecated since 1.12.8 Use Collection::hasDocument() * @param \Sokil\Mongo\Collection $collection collection instance * @return boolean */ public function belongsToCollection(Collection $collection) { return $collection->hasDocument($this); }
public function aggregate() { return $this->collection->aggregate($this); }
public function aggregateCursor(array $options = array()) { return $this->collection->aggregate($this, $options, true); }
public function testJsonSerializable() { $document = $this->collection->createDocument(array('k1' => 'v1')); $this->assertEquals(array('k1' => 'v1'), $document->jsonSerialize()); }
public function tearDown() { $this->collection->delete(); }
/** * Clear queue * * @return \Sokil\Mongo\Queue */ public function clear() { $this->collection->delete(); return $this; }
/** * @expectedException \Sokil\Mongo\Exception * @expectedExceptionMessage Update error: some_strange_error: Some strange error */ public function testSave_UpdateError() { $mongoCollectionMock = $this->getMock('\\MongoCollection', array('update'), array($this->collection->getDatabase()->getMongoDb(), 'phpmongo_test_collection')); $mongoCollectionMock->expects($this->once())->method('update')->will($this->returnValue(array('ok' => (double) 0, 'err' => 'some_strange_error', 'errmsg' => 'Some strange error'))); $collection = new Collection($this->collection->getDatabase(), $mongoCollectionMock); // create document $document = $collection->createDocument(array('p' => 'v'))->save(); // update document with error $document->set('p', 'v1')->save(); }