Skip to content

Commit

Permalink
Fix Elastica_Document::toArray() #178
Browse files Browse the repository at this point in the history
  • Loading branch information
ruflin committed Jun 9, 2012
1 parent 8a0eb56 commit 9316dee
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 9 deletions.
1 change: 1 addition & 0 deletions changes.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ CHANGES

2012-06-09
- Change $_parent to null to also support 0 for an id
- Fix Elasitca_Document->toArray()

2012-05-01
- Release v0.19.3.0
Expand Down
30 changes: 21 additions & 9 deletions lib/Elastica/Document.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,14 @@ class Elastica_Document {
*
* @var string Document type name
*/
protected $_type = '';
protected $_type = null;

/**
* Document index name
*
* @var string Document index name
*/
protected $_index = '';
protected $_index = null;

/**
* Document version
Expand Down Expand Up @@ -207,7 +207,7 @@ public function setType($type) {
public function getType() {
$type = $this->_type;

if (empty($type)) {
if (is_null($type)) {
throw new Elastica_Exception_Invalid('Type not set');
}
return $type;
Expand All @@ -233,7 +233,7 @@ public function setIndex($index) {
public function getIndex() {
$index = $this->_index;

if (empty($index)) {
if (is_null($index)) {
throw new Elastica_Exception_Invalid('Index not set');
}
return $index;
Expand Down Expand Up @@ -326,19 +326,31 @@ public function getPercolate() {
* @return array
*/
public function toArray() {
$index = array('_index' => $this->getIndex(), '_type' => $this->getType(), '_id' => $this->getId());
$doc = array();

if (!is_null($this->_index)) {
$doc['_index'] = $this->_index;
}

if (!is_null($this->_type)) {
$doc['_type'] = $this->_type;
}

if (!is_null($this->_index)) {
$doc['_id'] = $this->getId();
}

$version = $this->getVersion();
if (!empty($version)) {
$index['_version'] = $version;
$doc['_version'] = $version;
}

$parent = $this->getParent();
if (!is_null($parent)) {
$index['_parent'] = $parent;
$doc['_parent'] = $parent;
}

$params[] = $action;
$params[] = $doc->getData();
$doc['_source'] = $this->getData();
return $doc;
}
}
12 changes: 12 additions & 0 deletions test/lib/Elastica/DocumentTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,16 @@ public function testSetData()
$returnValue = $doc->setData(array('data'));
$this->assertInstanceOf('Elastica_Document', $returnValue);
}

public function testToArray() {
$id = 17;
$data = array('hello' => 'world');
$type = 'testtype';
$index = 'textindex';

$doc = new Elastica_Document($id, $data, $type, $index);

$result = array('_index' => $index, '_type' => $type, '_id' => $id, '_source' => $data);
$this->assertEquals($result, $doc->toArray());
}
}

0 comments on commit 9316dee

Please sign in to comment.