Completed
Pull Request — master (#500)
by
unknown
04:51
created

MetadataCollector   A

Complexity

Total Complexity 34

Size/Duplication

Total Lines 306
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 9
Bugs 1 Features 3
Metric Value
wmc 34
c 9
b 1
f 3
lcom 1
cbo 3
dl 0
loc 306
rs 9.2

13 Methods

Rating   Name   Duplication   Size   Complexity  
A setEnableCache() 0 4 1
A getMappings() 0 20 3
A __construct() 0 10 2
C getBundleMapping() 0 68 10
A getManagerTypes() 0 6 1
A getDocumentType() 0 6 1
A getMappingByNamespace() 0 11 2
B getClientMapping() 0 24 4
A getDocumentReflectionMapping() 0 4 1
A getDocumentMapping() 0 4 1
A getMapping() 0 9 3
A cacheBundle() 0 7 2
A getFileNamespace() 0 9 3
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
use ONGR\ElasticsearchBundle\Document\DocumentInterface;
16
17
/**
18
 * DocumentParser wrapper for getting bundle documents mapping.
19
 */
20
class MetadataCollector
21
{
22
    /**
23
     * @var DocumentFinder
24
     */
25
    private $finder;
26
27
    /**
28
     * @var DocumentParser
29
     */
30
    private $parser;
31
32
    /**
33
     * @var CacheProvider
34
     */
35
    private $cache = null;
36
37
    /**
38
     * @var bool
39
     */
40
    private $enableCache = false;
41
42
    /**
43
     * Bundles mappings local cache container. Could be stored as the whole bundle or as single document.
44
     * e.g. AcmeDemoBundle, AcmeDemoBundle:Product.
45
     *
46
     * @var mixed
47
     */
48
    private $mappings = [];
49
50
    /**
51
     * @param DocumentFinder $finder For finding documents.
52
     * @param DocumentParser $parser For reading document annotations.
53
     * @param CacheProvider  $cache  Cache provider to store the meta data for later use.
54
     */
55
    public function __construct($finder, $parser, $cache = null)
56
    {
57
        $this->finder = $finder;
58
        $this->parser = $parser;
59
        $this->cache = $cache;
60
61
        if ($this->cache) {
62
            $this->mappings = $this->cache->fetch('ongr.metadata.mappings');
63
        }
64
    }
65
66
    /**
67
     * Enables metadata caching.
68
     *
69
     * @param bool $enableCache
70
     */
71
    public function setEnableCache($enableCache)
72
    {
73
        $this->enableCache = $enableCache;
74
    }
75
76
    /**
77
     * Fetches bundles mapping from documents.
78
     *
79
     * @param string[] $bundles Elasticsearch manager config. You can get bundles list from 'mappings' node.
80
     * @return array
81
     */
82
    public function getMappings(array $bundles)
83
    {
84
        $output = [];
85
        foreach ($bundles as $bundle) {
86
            $mappings = $this->getBundleMapping($bundle);
87
88
            $alreadyDefinedTypes = array_intersect_key($mappings, $output);
89
            if (count($alreadyDefinedTypes)) {
90
                throw new \LogicException(
91
                    implode(',', array_keys($alreadyDefinedTypes)) .
92
                    ' type(s) already defined in other document, you can use the same ' .
93
                    'type only once in a manager definition.'
94
                );
95
            }
96
97
            $output = array_merge($output, $mappings);
98
        }
99
100
        return $output;
101
    }
102
103
    /**
104
     * Searches for documents in the bundle and tries to read them.
105
     *
106
     * @param string $name
107
     *
108
     * @return array Empty array on containing zero documents.
109
     */
110
    public function getBundleMapping($name)
111
    {
112
        if (!is_string($name)) {
113
            throw new \LogicException('getBundleMapping() in the Metadata collector expects a string argument only!');
114
        }
115
116
        if (isset($this->mappings[$name])) {
117
            return $this->mappings[$name];
118
        }
119
120
        // Checks if is mapped document or bundle.
121
        if (strpos($name, ':') !== false) {
122
            $bundleInfo = explode(':', $name);
123
            $bundle = $bundleInfo[0];
124
            $documentClass = $bundleInfo[1];
125
126
            $documents = $this->finder->getBundleDocumentPaths($bundle);
127
            $documents = array_filter(
128
                $documents,
129
                function ($document) use ($documentClass) {
130
                    if (pathinfo($document, PATHINFO_FILENAME) == $documentClass) {
131
                        return true;
132
                    }
133
                }
134
            );
135
        } else {
136
            $documents = $this->finder->getBundleDocumentPaths($name);
137
            $bundle = $name;
138
        }
139
140
        $mappings = [];
141
        $this->finder->getBundleClass($bundle);
142
143
        if (!count($documents)) {
144
            return [];
145
        }
146
147
        // Loop through documents found in bundle.
148
        foreach ($documents as $document) {
149
            $namespace = $this->getFileNamespace($document);
150
            if (!$namespace) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $namespace of type string|false is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
151
                continue;
152
            }
153
            $documentReflection = new \ReflectionClass(
154
                $namespace . '\\' . pathinfo($document, PATHINFO_FILENAME)
155
            );
156
157
            $documentMapping = $this->getDocumentReflectionMapping($documentReflection);
158
159
            if (!array_key_exists('type', $documentMapping)) {
160
                continue;
161
            }
162
163
            if (!array_key_exists($documentMapping['type'], $mappings)) {
164
                $documentMapping['bundle'] = $bundle;
165
                $mappings = array_merge($mappings, [$documentMapping['type'] => $documentMapping]);
166
            } else {
167
                throw new \LogicException(
168
                    $bundle . ' has 2 same type names defined in the documents. ' .
169
                    'Type names must be unique!'
170
                );
171
            }
172
        }
173
174
        $this->cacheBundle($name, $mappings);
175
176
        return $mappings;
177
    }
178
179
    /**
180
     * @param array $manager
181
     *
182
     * @return array
183
     */
184
    public function getManagerTypes($manager)
185
    {
186
        $mapping = $this->getMappings($manager['mappings']);
187
188
        return array_keys($mapping);
189
    }
190
191
    /**
192
     * Resolves document elasticsearch type, use format: SomeBarBundle:AcmeDocument.
193
     *
194
     * @param string $document
195
     *
196
     * @return string
197
     */
198
    public function getDocumentType($document)
199
    {
200
        $mapping = $this->getMappingByNamespace($document);
201
202
        return $mapping['type'];
203
    }
204
205
    /**
206
     * Retrieves document mapping by namespace.
207
     *
208
     * @param string $namespace Document namespace.
209
     *
210
     * @return array|null
211
     */
212
    public function getMappingByNamespace($namespace)
213
    {
214
        if (isset($this->mappings[$namespace])) {
215
            return $this->mappings[$namespace];
216
        }
217
218
        $mapping = $this->getDocumentReflectionMapping(new \ReflectionClass($this->finder->getNamespace($namespace)));
219
        $this->cacheBundle($namespace, $mapping);
220
221
        return $mapping;
222
    }
223
224
    /**
225
     * Retrieves prepared mapping to sent to the elasticsearch client.
226
     *
227
     * @param array $bundles Manager config.
228
     *
229
     * @return array
230
     */
231
    public function getClientMapping(array $bundles)
232
    {
233
        /** @var array $typesMapping Array of filtered mappings for the elasticsearch client*/
234
        $typesMapping = [];
235
236
        /** @var array $mappings All mapping info */
237
        $mappings = $this->getMappings($bundles);
238
239
        foreach ($mappings as $type => $mapping) {
240
            if (!empty($mapping['properties'])) {
241
                $typesMapping[$type] = array_filter(
242
                    array_merge(
243
                        ['properties' => $mapping['properties']],
244
                        $mapping['fields']
245
                    ),
246
                    function ($value) {
247
                        return (bool)$value || is_bool($value);
248
                    }
249
                );
250
            }
251
        }
252
253
        return $typesMapping;
254
    }
255
256
    /**
257
     * Gathers annotation data from class.
258
     *
259
     * @param \ReflectionClass $reflectionClass Document reflection class to read mapping from.
260
     *
261
     * @return array
262
     */
263
    private function getDocumentReflectionMapping(\ReflectionClass $reflectionClass)
264
    {
265
        return $this->parser->parse($reflectionClass);
266
    }
267
268
    /**
269
     * Retrieves mapping from document.
270
     *
271
     * @param DocumentInterface $document
272
     *
273
     * @return array
274
     */
275
    public function getDocumentMapping(DocumentInterface $document)
276
    {
277
        return $this->getDocumentReflectionMapping(new \ReflectionObject($document));
278
    }
279
280
    /**
281
     * Returns mapping with metadata.
282
     *
283
     * @param string $namespace Bundle or document namespace.
284
     *
285
     * @return array
286
     */
287
    public function getMapping($namespace)
288
    {
289
        if (strpos($namespace, ':') === false) {
290
            return $this->getBundleMapping($namespace);
291
        }
292
        $mapping = $this->getMappingByNamespace($namespace);
293
294
        return $mapping === null ? [] : $mapping;
295
    }
296
297
    /**
298
     * Adds metadata information to the cache storage.
299
     *
300
     * @param string $bundle
301
     * @param array  $mapping
302
     */
303
    private function cacheBundle($bundle, array $mapping)
304
    {
305
        if ($this->enableCache) {
306
            $this->mappings[$bundle] = $mapping;
307
            $this->cache->save('ongr.metadata.mappings', $this->mappings);
308
        }
309
    }
310
311
    /**
312
     * returns the namespace declared at the start of a file
313
     * @param $filepath
314
     * @return bool
315
     */
316
    private function getFileNamespace($filepath)
317
    {
318
        $exists = preg_match('/<\?php.+?namespace ([^;]+)/si', file_get_contents($filepath), $match);
319
320
        if ($exists && isset($match[1])) {
321
            return $match[1];
322
        }
323
        return false;
324
    }
325
}
326