Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.74% covered (success)
94.74%
18 / 19
75.00% covered (warning)
75.00%
3 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
ElasticaDocumentsJsonSerde
94.74% covered (success)
94.74%
18 / 19
75.00% covered (warning)
75.00%
3 / 4
7.01
0.00% covered (danger)
0.00%
0 / 1
 serialize
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 serializeOne
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 deserialize
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 deserializeOne
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
2.02
1<?php
2
3namespace CirrusSearch\Job;
4
5use Elastica\Document;
6
7/**
8 * Updates to be sent to elasticsearch need to be represented as a Document
9 * object, but we can't directly serialize those into the job queue which only
10 * supports json.
11 *
12 * Implements a simple serialize / deserialize routine that round trips
13 * documents to plain json types and back.
14 */
15class ElasticaDocumentsJsonSerde {
16    /**
17     * @param Document[] $docs
18     * @return array[] Document represented with json compatible types
19     */
20    public function serialize( array $docs ) {
21        $res = [];
22        foreach ( $docs as $doc ) {
23            $res[] = $this->serializeOne( $doc );
24        }
25        return $res;
26    }
27
28    public function serializeOne( Document $doc ) {
29        return [
30            'data' => $doc->getData(),
31            'params' => $doc->getParams(),
32            'upsert' => $doc->getDocAsUpsert(),
33        ];
34    }
35
36    /**
37     * @param array[] $serialized Data returned by self::serialize
38     * @return Document[]
39     */
40    public function deserialize( array $serialized ) {
41        $res = [];
42        foreach ( $serialized as $x ) {
43            $res[] = $this->deserializeOne( $x );
44        }
45        return $res;
46    }
47
48    public function deserializeOne( array $serialized, ?Document $doc = null ): Document {
49        // TODO: Because json_encode/decode is involved the round trip
50        // is imperfect. Almost everything here is an array regardless
51        // of what it was before serialization.  That shouldn't matter
52        // for documents, but elastica does occasionally use `(object)[]`
53        // instead of an empty array to force `{}` in the json output
54        // and that has been lost here.
55        // document _source
56        if ( $doc === null ) {
57            $doc = Document::create( $serialized['data'] );
58        } else {
59            $doc->setData( $serialized['data'] );
60        }
61        // id, version, etc.
62        $doc->setParams( $serialized['params'] );
63        $doc->setDocAsUpsert( $serialized['upsert'] );
64        return $doc;
65    }
66}