Completed
Push — master ( 35bf32...5024d1 )
by Karel
12s
created

getObjectClass()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
/*
4
 * This file is part of the FOSElasticaBundle package.
5
 *
6
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace FOS\ElasticaBundle\Doctrine;
13
14
use Doctrine\Common\Persistence\ManagerRegistry;
15
use FOS\ElasticaBundle\HybridResult;
16
use FOS\ElasticaBundle\Transformer\AbstractElasticaToModelTransformer as BaseTransformer;
17
use FOS\ElasticaBundle\Transformer\HighlightableModelInterface;
18
19
/**
20
 * Maps Elastica documents with Doctrine objects
21
 * This mapper assumes an exact match between
22
 * elastica documents ids and doctrine object ids.
23
 */
24
abstract class AbstractElasticaToModelTransformer extends BaseTransformer
25
{
26
    /**
27
     * Manager registry.
28
     *
29
     * @var ManagerRegistry
30
     */
31
    protected $registry = null;
32
33
    /**
34
     * Class of the model to map to the elastica documents.
35
     *
36
     * @var string
37
     */
38
    protected $objectClass = null;
39
40
    /**
41
     * Optional parameters.
42
     *
43
     * @var array
44
     */
45
    protected $options = [
46
        'hints' => [],
47
        'hydrate' => true,
48
        'identifier' => 'id',
49
        'ignore_missing' => false,
50
        'query_builder_method' => 'createQueryBuilder',
51
    ];
52
53
    /**
54
     * Instantiates a new Mapper.
55
     *
56
     * @param ManagerRegistry $registry
57
     * @param string          $objectClass
58
     * @param array           $options
59
     */
60 14
    public function __construct(ManagerRegistry $registry, $objectClass, array $options = [])
61
    {
62 14
        $this->registry = $registry;
63 14
        $this->objectClass = $objectClass;
64 14
        $this->options = array_merge($this->options, $options);
65 14
    }
66
67
    /**
68
     * Returns the object class that is used for conversion.
69
     *
70
     * @return string
71
     */
72 1
    public function getObjectClass()
73
    {
74 1
        return $this->objectClass;
75
    }
76
77
    /**
78
     * Transforms an array of elastica objects into an array of
79
     * model objects fetched from the doctrine repository.
80
     *
81
     * @param array $elasticaObjects of elastica objects
82
     *
83
     * @throws \RuntimeException
84
     *
85
     * @return array
86
     **/
87 7
    public function transform(array $elasticaObjects)
88
    {
89 7
        $ids = $highlights = [];
90 7
        foreach ($elasticaObjects as $elasticaObject) {
91 7
            $ids[] = $elasticaObject->getId();
92 7
            $highlights[$elasticaObject->getId()] = $elasticaObject->getHighlights();
93
        }
94
95 7
        $objects = $this->findByIdentifiers($ids, $this->options['hydrate']);
96 7
        $objectsCnt = count($objects);
97 7
        $elasticaObjectsCnt = count($elasticaObjects);
98 7
        if (!$this->options['ignore_missing'] && $objectsCnt < $elasticaObjectsCnt) {
99 1
            throw new \RuntimeException(sprintf('Cannot find corresponding Doctrine objects (%d) for all Elastica results (%d). IDs: %s', $objectsCnt, $elasticaObjectsCnt, implode(', ', $ids)));
100
        }
101
102 6
        $propertyAccessor = $this->propertyAccessor;
103 6
        $identifier = $this->options['identifier'];
104 6
        foreach ($objects as $object) {
105 5
            if ($object instanceof HighlightableModelInterface) {
106 4
                $id = $propertyAccessor->getValue($object, $identifier);
107 5
                $object->setElasticHighlights($highlights[(string) $id]);
108
            }
109
        }
110
111
        // sort objects in the order of ids
112 6
        $idPos = array_flip($ids);
113 6
        usort(
114 6
            $objects,
115 6
            function ($a, $b) use ($idPos, $identifier, $propertyAccessor) {
116 5
                if ($this->options['hydrate']) {
117 5
                    return $idPos[(string) $propertyAccessor->getValue(
118 5
                        $a,
119
                        $identifier
120 5
                    )] > $idPos[(string) $propertyAccessor->getValue($b, $identifier)];
121
                }
122
123
                return $idPos[$a[$identifier]] > $idPos[$b[$identifier]];
124 6
            }
125
        );
126
127 6
        return $objects;
128
    }
129
130 2
    public function hybridTransform(array $elasticaObjects)
131
    {
132 2
        $indexedElasticaResults = [];
133 2
        foreach ($elasticaObjects as $elasticaObject) {
134 2
            $indexedElasticaResults[(string) $elasticaObject->getId()] = $elasticaObject;
135
        }
136
137 2
        $objects = $this->transform($elasticaObjects);
138
139 2
        $result = [];
140 2
        foreach ($objects as $object) {
141 2
            if ($this->options['hydrate']) {
142 2
                $id = $this->propertyAccessor->getValue($object, $this->options['identifier']);
143
            } else {
144
                $id = $object[$this->options['identifier']];
145
            }
146 2
            $result[] = new HybridResult($indexedElasticaResults[(string) $id], $object);
147
        }
148
149 2
        return $result;
150
    }
151
152
    /**
153
     * {@inheritdoc}
154
     */
155 1
    public function getIdentifierField()
156
    {
157 1
        return $this->options['identifier'];
158
    }
159
160
    /**
161
     * Fetches objects by theses identifier values.
162
     *
163
     * @param array $identifierValues ids values
164
     * @param bool  $hydrate          whether or not to hydrate the objects, false returns arrays
165
     *
166
     * @return array of objects or arrays
167
     */
168
    abstract protected function findByIdentifiers(array $identifierValues, $hydrate);
169
}
170