<?php
namespace Elastica\Bulk;
use Elastica\Bulk;
use Elastica\Index;
use Elastica\JSON;
use Elastica\Type;
class Action
{
const OP_TYPE_CREATE = 'create';
const OP_TYPE_INDEX = 'index';
const OP_TYPE_DELETE = 'delete';
const OP_TYPE_UPDATE = 'update';
public static $opTypes = [
self::OP_TYPE_CREATE,
self::OP_TYPE_INDEX,
self::OP_TYPE_DELETE,
self::OP_TYPE_UPDATE,
];
protected $_opType;
protected $_metadata = [];
protected $_source = [];
public function __construct($opType = self::OP_TYPE_INDEX, array $metadata = [], array $source = [])
{
$this->setOpType($opType);
$this->setMetadata($metadata);
$this->setSource($source);
}
public function setOpType($type)
{
$this->_opType = $type;
return $this;
}
public function getOpType()
{
return $this->_opType;
}
public function setMetadata(array $metadata)
{
$this->_metadata = $metadata;
return $this;
}
public function getMetadata()
{
return $this->_metadata;
}
public function getActionMetadata()
{
return [$this->_opType => $this->getMetadata()];
}
public function setSource($source)
{
$this->_source = $source;
return $this;
}
public function getSource()
{
return $this->_source;
}
public function hasSource()
{
return !empty($this->_source);
}
public function setIndex($index)
{
if ($index instanceof Index) {
$index = $index->getName();
}
$this->_metadata['_index'] = $index;
return $this;
}
public function setType($type)
{
if ($type instanceof Type) {
$this->setIndex($type->getIndex()->getName());
$type = $type->getName();
}
$this->_metadata['_type'] = $type;
return $this;
}
public function setId($id)
{
$this->_metadata['_id'] = $id;
return $this;
}
public function setRouting($routing)
{
$this->_metadata['_routing'] = $routing;
return $this;
}
public function toArray()
{
$data[] = $this->getActionMetadata();
if ($this->hasSource()) {
$data[] = $this->getSource();
}
return $data;
}
public function toString()
{
$string = JSON::stringify($this->getActionMetadata(), JSON_FORCE_OBJECT).Bulk::DELIMITER;
if ($this->hasSource()) {
$source = $this->getSource();
if (is_string($source)) {
$string .= $source;
} elseif (is_array($source) && array_key_exists('doc', $source) && is_string($source['doc'])) {
$docAsUpsert = (isset($source['doc_as_upsert'])) ? ', "doc_as_upsert": '.$source['doc_as_upsert'] : '';
$string .= '{"doc": '.$source['doc'].$docAsUpsert.'}';
} else {
$string .= JSON::stringify($source, JSON_UNESCAPED_UNICODE);
}
$string .= Bulk::DELIMITER;
}
return $string;
}
public static function isValidOpType($opType)
{
return in_array($opType, self::$opTypes);
}
}