1<?php
2
3namespace Elastica\Bulk\Action;
4
5use Elastica\Document;
6use Elastica\Script\AbstractScript;
7
8class UpdateDocument extends IndexDocument
9{
10    /**
11     * @var string
12     */
13    protected $_opType = self::OP_TYPE_UPDATE;
14
15    /**
16     * {@inheritdoc}
17     */
18    public function setDocument(Document $document): AbstractDocument
19    {
20        parent::setDocument($document);
21
22        $source = ['doc' => $document->getData()];
23
24        if ($document->getDocAsUpsert()) {
25            $source['doc_as_upsert'] = true;
26        } elseif ($document->hasUpsert()) {
27            $upsert = $document->getUpsert()->getData();
28
29            if (!empty($upsert)) {
30                $source['upsert'] = $upsert;
31            }
32        }
33
34        $this->setSource($source);
35
36        return $this;
37    }
38
39    /**
40     * {@inheritdoc}
41     */
42    public function setScript(AbstractScript $script): AbstractDocument
43    {
44        parent::setScript($script);
45
46        // FIXME: can we throw away toArray cast?
47        $source = $script->toArray();
48
49        if ($script->hasUpsert()) {
50            $upsert = $script->getUpsert()->getData();
51
52            if (!empty($upsert)) {
53                $source['upsert'] = $upsert;
54
55                if ($script->getScriptedUpsert()) {
56                    $source['scripted_upsert'] = true;
57                }
58            }
59        }
60
61        $this->setSource($source);
62
63        return $this;
64    }
65}
66