Completed
Pull Request — master (#518)
by Mantas
04:35
created

MetadataCollector::getMappings()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 2
Metric Value
c 3
b 0
f 2
dl 0
loc 20
rs 9.4286
cc 3
eloc 12
nc 3
nop 1
1
<?php
2
3
/*
4
 * This file is part of the ONGR package.
5
 *
6
 * (c) NFQ Technologies UAB <[email protected]>
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 ONGR\ElasticsearchBundle\Mapping;
13
14
use Doctrine\Common\Cache\CacheProvider;
15
16
/**
17
 * DocumentParser wrapper for getting bundle documents mapping.
18
 */
19
class MetadataCollector
20
{
21
    /**
22
     * @var DocumentFinder
23
     */
24
    private $finder;
25
26
    /**
27
     * @var DocumentParser
28
     */
29
    private $parser;
30
31
    /**
32
     * @var CacheProvider
33
     */
34
    private $cache = null;
35
36
    /**
37
     * @var bool
38
     */
39
    private $enableCache = false;
40
41
    /**
42
     * Bundles mappings local cache container. Could be stored as the whole bundle or as single document.
43
     * e.g. AcmeDemoBundle, AcmeDemoBundle:Product.
44
     *
45
     * @var mixed
46
     */
47
    private $mappings = [];
48
49
    /**
50
     * @param DocumentFinder $finder For finding documents.
51
     * @param DocumentParser $parser For reading document annotations.
52
     * @param CacheProvider  $cache  Cache provider to store the meta data for later use.
53
     */
54
    public function __construct($finder, $parser, $cache = null)
55
    {
56
        $this->finder = $finder;
57
        $this->parser = $parser;
58
        $this->cache = $cache;
59
60
        if ($this->cache) {
61
            $this->mappings = $this->cache->fetch('ongr.metadata.mappings');
62
        }
63
    }
64
65
    /**
66
     * Enables metadata caching.
67
     *
68
     * @param bool $enableCache
69
     */
70
    public function setEnableCache($enableCache)
71
    {
72
        $this->enableCache = $enableCache;
73
    }
74
75
    /**
76
     * Fetches bundles mapping from documents.
77
     *
78
     * @param string[] $bundles Elasticsearch manager config. You can get bundles list from 'mappings' node.
79
     * @return array
80
     */
81
    public function getMappings(array $bundles)
82
    {
83
        $output = [];
84
        foreach ($bundles as $bundle) {
85
            $mappings = $this->getBundleMapping($bundle);
86
87
            $alreadyDefinedTypes = array_intersect_key($mappings, $output);
88
            if (count($alreadyDefinedTypes)) {
89
                throw new \LogicException(
90
                    implode(',', array_keys($alreadyDefinedTypes)) .
91
                    ' type(s) already defined in other document, you can use the same ' .
92
                    'type only once in a manager definition.'
93
                );
94
            }
95
96
            $output = array_merge($output, $mappings);
97
        }
98
99
        return $output;
100
    }
101
102
    /**
103
     * Searches for documents in the bundle and tries to read them.
104
     *
105
     * @param string $name
106
     *
107
     * @return array Empty array on containing zero documents.
108
     */
109
    public function getBundleMapping($name)
110
    {
111
        if (!is_string($name)) {
112
            throw new \LogicException('getBundleMapping() in the Metadata collector expects a string argument only!');
113
        }
114
115
        if (isset($this->mappings[$name])) {
116
            return $this->mappings[$name];
117
        }
118
119
        // Checks if is mapped document or bundle.
120
        if (strpos($name, ':') !== false) {
121
            $bundleInfo = explode(':', $name);
122
            $bundle = $bundleInfo[0];
123
            $documentClass = $bundleInfo[1];
124
125
            $documents = $this->finder->getBundleDocumentPaths($bundle);
126
            $documents = array_filter(
127
                $documents,
128
                function ($document) use ($documentClass) {
129
                    if (pathinfo($document, PATHINFO_FILENAME) == $documentClass) {
130
                        return true;
131
                    }
132
                }
133
            );
134
        } else {
135
            $documents = $this->finder->getBundleDocumentPaths($name);
136
            $bundle = $name;
137
        }
138
139
        $mappings = [];
140
        $bundleNamespace = $this->finder->getBundleClass($bundle);
141
        $bundleNamespace = substr($bundleNamespace, 0, strrpos($bundleNamespace, '\\'));
142
143
        if (!count($documents)) {
144
            return [];
145
        }
146
147
        // Loop through documents found in bundle.
148
        foreach ($documents as $document) {
149
            $documentReflection = new \ReflectionClass(
150
                $bundleNamespace .
151
                '\\' . DocumentFinder::DOCUMENT_DIR .
152
                '\\' . pathinfo($document, PATHINFO_FILENAME)
153
            );
154
155
            $documentMapping = $this->getDocumentReflectionMapping($documentReflection);
156
157
            if (!array_key_exists('type', $documentMapping)) {
158
                continue;
159
            }
160
161
            if (!array_key_exists($documentMapping['type'], $mappings)) {
162
                $documentMapping['bundle'] = $bundle;
163
                $mappings = array_merge($mappings, [$documentMapping['type'] => $documentMapping]);
164
            } else {
165
                throw new \LogicException(
166
                    $bundle . ' has 2 same type names defined in the documents. ' .
167
                    'Type names must be unique!'
168
                );
169
            }
170
        }
171
172
        $this->cacheBundle($name, $mappings);
173
174
        return $mappings;
175
    }
176
177
    /**
178
     * @param array $manager
179
     *
180
     * @return array
181
     */
182
    public function getManagerTypes($manager)
183
    {
184
        $mapping = $this->getMappings($manager['mappings']);
185
186
        return array_keys($mapping);
187
    }
188
189
    /**
190
     * Resolves Elasticsearch type by document class.
191
     *
192
     * @param string $className FQCN or string in AppBundle:Document format
193
     *
194
     * @return string
195
     * @throws \Exception
196
     */
197
    public function getDocumentType($className)
198
    {
199
        $mapping = $this->getMapping($className);
200
201
        if (empty($mapping)) {
202
            throw new \Exception(sprintf('Mapping for class "%s" was not found!', $className));
203
        }
204
205
        return $mapping['type'];
206
    }
207
208
    /**
209
     * Retrieves prepared mapping to sent to the elasticsearch client.
210
     *
211
     * @param array $bundles Manager config.
212
     *
213
     * @return array|null
214
     */
215
    public function getClientMapping(array $bundles)
216
    {
217
        /** @var array $typesMapping Array of filtered mappings for the elasticsearch client*/
218
        $typesMapping = null;
219
220
        /** @var array $mappings All mapping info */
221
        $mappings = $this->getMappings($bundles);
222
223
        foreach ($mappings as $type => $mapping) {
224
            if (!empty($mapping['properties'])) {
225
                $typesMapping[$type] = array_filter(
226
                    array_merge(
227
                        ['properties' => $mapping['properties']],
228
                        $mapping['fields']
229
                    ),
230
                    function ($value) {
231
                        return (bool)$value || is_bool($value);
232
                    }
233
                );
234
            }
235
        }
236
237
        return $typesMapping;
238
    }
239
240
    /**
241
     * Gathers annotation data from class.
242
     *
243
     * @param \ReflectionClass $reflectionClass Document reflection class to read mapping from.
244
     *
245
     * @return array
246
     */
247
    private function getDocumentReflectionMapping(\ReflectionClass $reflectionClass)
248
    {
249
        return $this->parser->parse($reflectionClass);
250
    }
251
252
    /**
253
     * Returns single document mapping metadata.
254
     *
255
     * @param string $namespace Document namespace
256
     *
257
     * @return array
258
     */
259
    public function getMapping($namespace)
260
    {
261
        $namespace = $this->getClassName($namespace);
262
263
        if (isset($this->mappings[$namespace])) {
264
            return $this->mappings[$namespace];
265
        }
266
267
        $mapping = $this->getDocumentReflectionMapping(new \ReflectionClass($namespace));
268
        $this->cacheBundle($namespace, $mapping);
269
270
        return $mapping;
271
    }
272
273
    /**
274
     * Adds metadata information to the cache storage.
275
     *
276
     * @param string $bundle
277
     * @param array  $mapping
278
     */
279
    private function cacheBundle($bundle, array $mapping)
280
    {
281
        if ($this->enableCache) {
282
            $this->mappings[$bundle] = $mapping;
283
            $this->cache->save('ongr.metadata.mappings', $this->mappings);
284
        }
285
    }
286
287
    /**
288
     * Returns fully qualified class name.
289
     *
290
     * @param string $className
291
     *
292
     * @return string
293
     */
294
    public function getClassName($className)
295
    {
296
        return $this->finder->getNamespace($className);
297
    }
298
}
299