Completed
Push — master ( aec4d6...0b1183 )
by Simonas
04:40
created

MetadataCollector::getClassName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
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
        // Handle the case when single document mapping requested
120
        if (strpos($name, ':') !== false) {
121
            list($bundle, $documentClass) = explode(':', $name);
122
            $documents = $this->finder->getBundleDocumentClasses($bundle);
123
            $documents = in_array($documentClass, $documents) ? [$documentClass] : [];
124
        } else {
125
            $documents = $this->finder->getBundleDocumentClasses($name);
126
            $bundle = $name;
127
        }
128
129
        $mappings = [];
130
        $bundleNamespace = $this->finder->getBundleClass($bundle);
131
        $bundleNamespace = substr($bundleNamespace, 0, strrpos($bundleNamespace, '\\'));
132
133
        if (!count($documents)) {
134
            return [];
135
        }
136
137
        // Loop through documents found in bundle.
138
        foreach ($documents as $document) {
139
            $documentReflection = new \ReflectionClass(
140
                $bundleNamespace .
141
                '\\' . DocumentFinder::DOCUMENT_DIR .
142
                '\\' . $document
143
            );
144
145
            $documentMapping = $this->getDocumentReflectionMapping($documentReflection);
146
147
            if (!array_key_exists('type', $documentMapping)) {
148
                continue;
149
            }
150
151
            if (!array_key_exists($documentMapping['type'], $mappings)) {
152
                $documentMapping['bundle'] = $bundle;
153
                $mappings = array_merge($mappings, [$documentMapping['type'] => $documentMapping]);
154
            } else {
155
                throw new \LogicException(
156
                    $bundle . ' has 2 same type names defined in the documents. ' .
157
                    'Type names must be unique!'
158
                );
159
            }
160
        }
161
162
        $this->cacheBundle($name, $mappings);
163
164
        return $mappings;
165
    }
166
167
    /**
168
     * @param array $manager
169
     *
170
     * @return array
171
     */
172
    public function getManagerTypes($manager)
173
    {
174
        $mapping = $this->getMappings($manager['mappings']);
175
176
        return array_keys($mapping);
177
    }
178
179
    /**
180
     * Resolves Elasticsearch type by document class.
181
     *
182
     * @param string $className FQCN or string in AppBundle:Document format
183
     *
184
     * @return string
185
     * @throws \Exception
186
     */
187
    public function getDocumentType($className)
188
    {
189
        $mapping = $this->getMapping($className);
190
191
        if (empty($mapping)) {
192
            throw new \Exception(sprintf('Mapping for class "%s" was not found!', $className));
193
        }
194
195
        return $mapping['type'];
196
    }
197
198
    /**
199
     * Retrieves prepared mapping to sent to the elasticsearch client.
200
     *
201
     * @param array $bundles Manager config.
202
     *
203
     * @return array|null
204
     */
205
    public function getClientMapping(array $bundles)
206
    {
207
        /** @var array $typesMapping Array of filtered mappings for the elasticsearch client*/
208
        $typesMapping = null;
209
210
        /** @var array $mappings All mapping info */
211
        $mappings = $this->getMappings($bundles);
212
213
        foreach ($mappings as $type => $mapping) {
214
            if (!empty($mapping['properties'])) {
215
                $typesMapping[$type] = array_filter(
216
                    array_merge(
217
                        ['properties' => $mapping['properties']],
218
                        $mapping['fields']
219
                    ),
220
                    function ($value) {
221
                        return (bool)$value || is_bool($value);
222
                    }
223
                );
224
            }
225
        }
226
227
        return $typesMapping;
228
    }
229
230
    /**
231
     * Gathers annotation data from class.
232
     *
233
     * @param \ReflectionClass $reflectionClass Document reflection class to read mapping from.
234
     *
235
     * @return array
236
     */
237
    private function getDocumentReflectionMapping(\ReflectionClass $reflectionClass)
238
    {
239
        return $this->parser->parse($reflectionClass);
240
    }
241
242
    /**
243
     * Returns single document mapping metadata.
244
     *
245
     * @param string $namespace Document namespace
246
     *
247
     * @return array
248
     */
249
    public function getMapping($namespace)
250
    {
251
        $namespace = $this->getClassName($namespace);
252
253
        if (isset($this->mappings[$namespace])) {
254
            return $this->mappings[$namespace];
255
        }
256
257
        $mapping = $this->getDocumentReflectionMapping(new \ReflectionClass($namespace));
258
        $this->cacheBundle($namespace, $mapping);
259
260
        return $mapping;
261
    }
262
263
    /**
264
     * Adds metadata information to the cache storage.
265
     *
266
     * @param string $bundle
267
     * @param array  $mapping
268
     */
269
    private function cacheBundle($bundle, array $mapping)
270
    {
271
        if ($this->enableCache) {
272
            $this->mappings[$bundle] = $mapping;
273
            $this->cache->save('ongr.metadata.mappings', $this->mappings);
274
        }
275
    }
276
277
    /**
278
     * Returns fully qualified class name.
279
     *
280
     * @param string $className
281
     *
282
     * @return string
283
     */
284
    public function getClassName($className)
285
    {
286
        return $this->finder->getNamespace($className);
287
    }
288
}
289