Completed
Push — master ( 554f9d...0d589d )
by
unknown
13:57
created

SchemaUtils   D

Complexity

Total Complexity 58

Size/Duplication

Total Lines 503
Duplicated Lines 3.18 %

Coupling/Cohesion

Components 1
Dependencies 15

Test Coverage

Coverage 6.75%

Importance

Changes 0
Metric Value
wmc 58
lcom 1
cbo 15
dl 16
loc 503
ccs 14
cts 207
cp 0.0675
rs 4.8387
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 27 1
A getCollectionSchema() 0 10 1
A makeArrayTranslatable() 0 6 1
A getSchemaRouteName() 0 13 3
B getCollectionItemType() 0 15 5
F getModelSchema() 16 269 46
A makeTranslatable() 0 18 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like SchemaUtils often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use SchemaUtils, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Utils for generating schemas.
4
 */
5
6
namespace Graviton\SchemaBundle;
7
8
use Doctrine\Common\Cache\CacheProvider;
9
use Graviton\I18nBundle\Document\TranslatableDocumentInterface;
10
use Graviton\I18nBundle\Document\Language;
11
use Graviton\I18nBundle\Repository\LanguageRepository;
12
use Graviton\RestBundle\Model\DocumentModel;
13
use Graviton\SchemaBundle\Constraint\ConstraintBuilder;
14
use Graviton\SchemaBundle\Document\Schema;
15
use Graviton\SchemaBundle\Document\SchemaAdditionalProperties;
16
use Graviton\SchemaBundle\Document\SchemaType;
17
use Graviton\SchemaBundle\Service\RepositoryFactory;
18
use JMS\Serializer\Serializer;
19
use Metadata\MetadataFactoryInterface as SerializerMetadataFactoryInterface;
20
use Symfony\Component\Routing\RouterInterface;
21
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
22
23
/**
24
 * Utils for generating schemas.
25
 *
26
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
27
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
28
 * @link     http://swisscom.ch
29
 */
30
class SchemaUtils
31
{
32
33
    /**
34
     * language repository
35
     *
36
     * @var LanguageRepository repository
37
     */
38
    private $languageRepository;
39
40
    /**
41
     * router
42
     *
43
     * @var RouterInterface router
44
     */
45
    private $router;
46
47
    /**
48
     * serializer
49
     *
50
     * @var Serializer
51
     */
52
    private $serializer;
53
54
    /**
55
     * mapping service names => route names
56
     *
57
     * @var array service mapping
58
     */
59
    private $extrefServiceMapping;
60
61
    /**
62
     * event map
63
     *
64
     * @var array event map
65
     */
66
    private $eventMap;
67
68
    /**
69
     * @var array [document class => [field name -> exposed name]]
70
     */
71
    private $documentFieldNames;
72
73
    /**
74
     * @var string
75
     */
76
    private $defaultLocale;
77
78
    /**
79
     * @var RepositoryFactory
80
     */
81
    private $repositoryFactory;
82
83
    /**
84
     * @var SerializerMetadataFactoryInterface
85
     */
86
    private $serializerMetadataFactory;
87
88
    /**
89
     * @var CacheProvider
90
     */
91
    private $cache;
92
93
    /**
94
     * @var string
95
     */
96
    private $cacheInvalidationMapKey;
97
98
    /**
99
     * @var ConstraintBuilder
100
     */
101
    private $constraintBuilder;
102
103
    /**
104
     * Constructor
105
     *
106
     * @param RepositoryFactory                  $repositoryFactory         Create repos from model class names
107
     * @param SerializerMetadataFactoryInterface $serializerMetadataFactory Serializer metadata factory
108
     * @param LanguageRepository                 $languageRepository        repository
109
     * @param RouterInterface                    $router                    router
110
     * @param Serializer                         $serializer                serializer
111
     * @param array                              $extrefServiceMapping      Extref service mapping
112
     * @param array                              $eventMap                  eventmap
113
     * @param array                              $documentFieldNames        Document field names
114
     * @param string                             $defaultLocale             Default Language
115
     * @param ConstraintBuilder                  $constraintBuilder         Constraint builder
116
     * @param CacheProvider                      $cache                     Doctrine cache provider
117
     * @param string                             $cacheInvalidationMapKey   Cache invalidation map cache key
118
     */
119 4
    public function __construct(
120
        RepositoryFactory $repositoryFactory,
121
        SerializerMetadataFactoryInterface $serializerMetadataFactory,
122
        LanguageRepository $languageRepository,
123
        RouterInterface $router,
124
        Serializer $serializer,
125
        array $extrefServiceMapping,
126
        array $eventMap,
127
        array $documentFieldNames,
128
        $defaultLocale,
129
        ConstraintBuilder $constraintBuilder,
130
        CacheProvider $cache,
131
        $cacheInvalidationMapKey
132
    ) {
133 4
        $this->repositoryFactory = $repositoryFactory;
134 4
        $this->serializerMetadataFactory = $serializerMetadataFactory;
135 4
        $this->languageRepository = $languageRepository;
136 4
        $this->router = $router;
137 4
        $this->serializer = $serializer;
138 4
        $this->extrefServiceMapping = $extrefServiceMapping;
139 4
        $this->eventMap = $eventMap;
140 4
        $this->documentFieldNames = $documentFieldNames;
141 4
        $this->defaultLocale = $defaultLocale;
142 4
        $this->constraintBuilder = $constraintBuilder;
143 4
        $this->cache = $cache;
144 4
        $this->cacheInvalidationMapKey = $cacheInvalidationMapKey;
145 4
    }
146
147
    /**
148
     * get schema for an array of models
149
     *
150
     * @param string        $modelName name of model
151
     * @param DocumentModel $model     model
152
     *
153
     * @return Schema
154
     */
155
    public function getCollectionSchema($modelName, DocumentModel $model)
156
    {
157
        $collectionSchema = new Schema;
158
        $collectionSchema->setTitle(sprintf('Array of %s objects', $modelName));
159
        $collectionSchema->setType('array');
160
161
        $collectionSchema->setItems($this->getModelSchema($modelName, $model));
162
163
        return $collectionSchema;
164
    }
165
166
    /**
167
     * return the schema for a given route
168
     *
169
     * @param string        $modelName  name of mode to generate schema for
170
     * @param DocumentModel $model      model to generate schema for
171
     * @param boolean       $online     if we are online and have access to mongodb during this build
172
     * @param boolean       $internal   if true, we generate the schema for internal validation use
173
     * @param boolean       $serialized if true, it will serialize the Schema object and return a \stdClass instead
174
     *
175
     * @return Schema|\stdClass Either a Schema instance or serialized as \stdClass if $serialized is true
176
     */
177
    public function getModelSchema(
178
        $modelName,
179
        DocumentModel $model,
180
        $online = true,
181
        $internal = false,
182
        $serialized = false
183
    ) {
184
185
        $cacheKey = sprintf(
186
            'schema.%s.%s.%s.%s',
187
            $model->getEntityClass(),
188
            (string) $online,
189
            (string) $internal,
190
            (string) $serialized
191
        );
192
193
        if ($this->cache->contains($cacheKey)) {
194
            return $this->cache->fetch($cacheKey);
195
        }
196
197
        $invalidateCacheMap = [];
198
        if ($this->cache->contains($this->cacheInvalidationMapKey)) {
199
            $invalidateCacheMap = $this->cache->fetch($this->cacheInvalidationMapKey);
200
        }
201
202
        // build up schema data
203
        $schema = new Schema;
204
205
        if (!empty($model->getTitle())) {
206
            $schema->setTitle($model->getTitle());
207
        } else {
208
            if (!is_null($modelName)) {
209
                $schema->setTitle(ucfirst($modelName));
210
            } else {
211
                $reflection = new \ReflectionClass($model);
212
                $schema->setTitle(ucfirst($reflection->getShortName()));
213
            }
214
        }
215
216
        $schema->setDescription($model->getDescription());
217
        $schema->setDocumentClass($model->getDocumentClass());
0 ignored issues
show
Security Bug introduced by
It seems like $model->getDocumentClass() targeting Graviton\SchemaBundle\Mo...del::getDocumentClass() can also be of type false; however, Graviton\SchemaBundle\Do...ema::setDocumentClass() does only seem to accept string, did you maybe forget to handle an error condition?
Loading history...
218
        $schema->setRecordOriginModifiable($model->getRecordOriginModifiable());
219
        $schema->setIsVersioning($model->isVersioning());
220
        $schema->setType('object');
221
222
        // grab schema info from model
223
        $repo = $model->getRepository();
224
        $meta = $repo->getClassMetadata();
225
226
        // Init sub searchable fields
227
        $subSearchableFields = array();
228
229
        // look for translatables in document class
230
        $documentReflection = new \ReflectionClass($repo->getClassName());
231
        if ($documentReflection->implementsInterface('Graviton\I18nBundle\Document\TranslatableDocumentInterface')) {
232
            /** @var TranslatableDocumentInterface $documentInstance */
233
            $documentInstance = $documentReflection->newInstanceWithoutConstructor();
234
            $translatableFields = array_merge(
235
                $documentInstance->getTranslatableFields(),
236
                $documentInstance->getPreTranslatedFields()
237
            );
238
        } else {
239
            $translatableFields = [];
240
        }
241
242
        if (!empty($translatableFields)) {
243
            $invalidateCacheMap[$this->languageRepository->getClassName()][] = $cacheKey;
244
        }
245
246
        // exposed fields
247
        $documentFieldNames = isset($this->documentFieldNames[$repo->getClassName()]) ?
248
            $this->documentFieldNames[$repo->getClassName()] :
249
            [];
250
251
        $languages = [];
252
        if ($online) {
253
            $languages = array_map(
254
                function (Language $language) {
255
                    return $language->getId();
256
                },
257
                $this->languageRepository->findAll()
258
            );
259
        }
260
        if (empty($languages)) {
261
            $languages = [
262
                $this->defaultLocale
263
            ];
264
        }
265
266
        // exposed events..
267
        $classShortName = $documentReflection->getShortName();
268
        if (isset($this->eventMap[$classShortName])) {
269
            $schema->setEventNames(array_unique($this->eventMap[$classShortName]['events']));
270
        }
271
272
        // don't describe hidden fields
273
        $requiredFields = $model->getRequiredFields() ?: [];
274
        $requiredFields = array_intersect_key($documentFieldNames, array_combine($requiredFields, $requiredFields));
275
276
        foreach ($meta->getFieldNames() as $field) {
277
            // don't describe hidden fields
278
            if (!isset($documentFieldNames[$field])) {
279
                continue;
280
            }
281
            // hide realId field (I was aiming at a cleaner solution than the matching realId string initially)
282
            // hide embedded ID field unless it's required or for internal validation need, back-compatibility.
283
            // TODO remove !$internal once no clients use it for embedded objects as these id are done automatically
284
            if (($meta->getTypeOfField($field) == 'id' && $field == 'realId') ||
285
                ($field == 'id' && !$internal && $meta->isEmbeddedDocument && !in_array('id', $requiredFields))
286
            ) {
287
                continue;
288
            }
289
290
            $property = new Schema();
291
            $property->setTitle($model->getTitleOfField($field));
292
            $property->setDescription($model->getDescriptionOfField($field));
293
            $property->setType($meta->getTypeOfField($field));
294
            $property->setReadOnly($model->getReadOnlyOfField($field));
295
296
            // we only want to render if it's true
297
            if ($model->getRecordOriginExceptionOfField($field) === true) {
298
                $property->setRecordOriginException(true);
299
            }
300
301
            if ($meta->getTypeOfField($field) === 'many') {
302
                $propertyModel = $model->manyPropertyModelForTarget($meta->getAssociationTargetClass($field));
303
304
                if ($model->hasDynamicKey($field)) {
305
                    $property->setType('object');
306
307
                    if ($online) {
308
                        // we generate a complete list of possible keys when we have access to mongodb
309
                        // this makes everything work with most json-schema v3 implementations (ie. schemaform.io)
310
                        $dynamicKeySpec = $model->getDynamicKeySpec($field);
311
312
                        $documentId = $dynamicKeySpec->{'document-id'};
313
                        $dynamicRepository = $this->repositoryFactory->get($documentId);
314
315
                        // put this in invalidate map so when know we have to invalidate when this document is used
316
                        $invalidateCacheMap[$dynamicRepository->getDocumentName()][] = $cacheKey;
0 ignored issues
show
Bug introduced by
The method getDocumentName() does not seem to exist on object<Doctrine\Common\Persistence\ObjectManager>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
317
318
                        $repositoryMethod = $dynamicKeySpec->{'repository-method'};
319
                        $records = $dynamicRepository->$repositoryMethod();
320
321
                        $dynamicProperties = array_map(
322
                            function ($record) {
323
                                return $record->getId();
324
                            },
325
                            $records
326
                        );
327
                        foreach ($dynamicProperties as $propertyName) {
328
                            $property->addProperty(
329
                                $propertyName,
330
                                $this->getModelSchema($field, $propertyModel, $online, $internal)
331
                            );
332
                        }
333
                    } else {
334
                        // swagger case
335
                        $property->setAdditionalProperties(
336
                            new SchemaAdditionalProperties(
337
                                $this->getModelSchema($field, $propertyModel, $online, $internal)
338
                            )
339
                        );
340
                    }
341
                } else {
342
                    $property->setItems($this->getModelSchema($field, $propertyModel, $online, $internal));
343
                    $property->setType('array');
344
                }
345
            } elseif ($meta->getTypeOfField($field) === 'one') {
346
                $propertyModel = $model->manyPropertyModelForTarget($meta->getAssociationTargetClass($field));
347
                $property = $this->getModelSchema($field, $propertyModel, $online, $internal);
348
349
                if ($property->getSearchable()) {
350
                    foreach ($property->getSearchable() as $searchableSubField) {
0 ignored issues
show
Bug introduced by
The method getSearchable does only exist in Graviton\SchemaBundle\Document\Schema, but not in stdClass.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
351
                        $subSearchableFields[] = $field . '.' . $searchableSubField;
352
                    }
353
                }
354
            } elseif (in_array($field, $translatableFields, true)) {
355
                $property = $this->makeTranslatable($property, $languages);
356
            } elseif (in_array($field.'[]', $translatableFields, true)) {
357
                $property = $this->makeArrayTranslatable($property, $languages);
358
            } elseif ($meta->getTypeOfField($field) === 'extref') {
359
                $urls = array();
360
                $refCollections = $model->getRefCollectionOfField($field);
361
                foreach ($refCollections as $collection) {
362
                    if (isset($this->extrefServiceMapping[$collection])) {
363
                        $urls[] = $this->router->generate(
364
                            $this->extrefServiceMapping[$collection].'.all',
365
                            [],
366
                            UrlGeneratorInterface::ABSOLUTE_URL
367
                        );
368
                    } elseif ($collection === '*') {
369
                        $urls[] = '*';
370
                    }
371
                }
372
                $property->setRefCollection($urls);
373 View Code Duplication
            } elseif ($meta->getTypeOfField($field) === 'collection') {
374
                $itemSchema = new Schema();
375
                $property->setType('array');
376
                $itemSchema->setType($this->getCollectionItemType($meta->name, $field));
377
378
                $property->setItems($itemSchema);
379
                $property->setFormat(null);
380
            } elseif ($meta->getTypeOfField($field) === 'datearray') {
381
                $itemSchema = new Schema();
382
                $property->setType('array');
383
                $itemSchema->setType('string');
384
                $itemSchema->setFormat('date-time');
385
386
                $property->setItems($itemSchema);
387
                $property->setFormat(null);
388 View Code Duplication
            } elseif ($meta->getTypeOfField($field) === 'hasharray') {
389
                $itemSchema = new Schema();
390
                $itemSchema->setType('object');
391
392
                $property->setType('array');
393
                $property->setItems($itemSchema);
394
                $property->setFormat(null);
395
            }
396
397
            if (in_array($meta->getTypeOfField($field), $property->getMinLengthTypes())) {
0 ignored issues
show
Bug introduced by
The method getMinLengthTypes does only exist in Graviton\SchemaBundle\Document\Schema, but not in stdClass.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
398
                // make sure a required field cannot be blank
399
                if (in_array($documentFieldNames[$field], $requiredFields)) {
400
                    $property->setMinLength(1);
0 ignored issues
show
Bug introduced by
The method setMinLength does only exist in Graviton\SchemaBundle\Document\Schema, but not in stdClass.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
401
                } else {
402
                    // in the other case, make sure also null can be sent..
403
                    $currentType = $property->getType();
0 ignored issues
show
Bug introduced by
The method getType does only exist in Graviton\SchemaBundle\Document\Schema, but not in stdClass.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
404
                    if ($currentType instanceof SchemaType) {
405
                        $property->setType(array_merge($currentType->getTypes(), ['null']));
0 ignored issues
show
Bug introduced by
The method setType does only exist in Graviton\SchemaBundle\Document\Schema, but not in stdClass.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
406
                    } else {
407
                        $property->setType('null');
408
                    }
409
                }
410
            }
411
412
            $property = $this->constraintBuilder->addConstraints($field, $property, $model);
0 ignored issues
show
Bug introduced by
It seems like $property can also be of type object<stdClass>; however, Graviton\SchemaBundle\Co...ilder::addConstraints() does only seem to accept object<Graviton\SchemaBundle\Document\Schema>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
413
414
            $schema->addProperty($documentFieldNames[$field], $property);
415
        }
416
417
        /**
418
         * if we generate schema for internal use; don't have id in required array as
419
         * it's 'requiredness' depends on the method used (POST/PUT/PATCH) and is checked in checks
420
         * before validation.
421
         */
422
        $idPosition = array_search('id', $requiredFields);
423
        if ($internal === true && $idPosition !== false && !$meta->isEmbeddedDocument) {
424
            unset($requiredFields[$idPosition]);
425
        }
426
427
        $schema->setRequired($requiredFields);
428
429
        // set additionalProperties to false (as this is our default policy) if not already set
430
        if (is_null($schema->getAdditionalProperties()) && $online) {
431
            $schema->setAdditionalProperties(new SchemaAdditionalProperties(false));
432
        }
433
434
        $searchableFields = array_merge($subSearchableFields, $model->getSearchableFields());
435
        $schema->setSearchable($searchableFields);
436
437
        if ($serialized === true) {
438
            $schema = json_decode($this->serializer->serialize($schema, 'json'));
439
        }
440
441
        $this->cache->save($cacheKey, $schema);
442
        $this->cache->save($this->cacheInvalidationMapKey, $invalidateCacheMap);
443
444
        return $schema;
445
    }
446
447
    /**
448
     * turn a property into a translatable property
449
     *
450
     * @param Schema   $property  simple string property
451
     * @param string[] $languages available languages
452
     *
453
     * @return Schema
454
     */
455
    public function makeTranslatable(Schema $property, $languages)
456
    {
457
        $property->setType('object');
458
        $property->setTranslatable(true);
459
460
        array_walk(
461
            $languages,
462
            function ($language) use ($property) {
463
                $schema = new Schema;
464
                $schema->setType('string');
465
                $schema->setTitle('Translated String');
466
                $schema->setDescription('String in ' . $language . ' locale.');
467
                $property->addProperty($language, $schema);
468
            }
469
        );
470
        $property->setRequired(['en']);
471
        return $property;
472
    }
473
474
    /**
475
     * turn a array property into a translatable property
476
     *
477
     * @param Schema   $property  simple string property
478
     * @param string[] $languages available languages
479
     *
480
     * @return Schema
481
     */
482
    public function makeArrayTranslatable(Schema $property, $languages)
483
    {
484
        $property->setType('array');
485
        $property->setItems($this->makeTranslatable(new Schema(), $languages));
486
        return $property;
487
    }
488
489
    /**
490
     * get canonical route to a schema based on a route
491
     *
492
     * @param string $routeName route name
493
     *
494
     * @return string schema route name
495
     */
496
    public static function getSchemaRouteName($routeName)
497
    {
498
        $routeParts = explode('.', $routeName);
499
500
        $routeType = array_pop($routeParts);
501
        // check if we need to create an item or collection schema
502
        $realRouteType = 'canonicalSchema';
503
        if ($routeType != 'options' && $routeType != 'all') {
504
            $realRouteType = 'canonicalIdSchema';
505
        }
506
507
        return implode('.', array_merge($routeParts, array($realRouteType)));
508
    }
509
510
    /**
511
     * Get item type of collection field
512
     *
513
     * @param string $className Class name
514
     * @param string $fieldName Field name
515
     * @return string|null
516
     */
517
    private function getCollectionItemType($className, $fieldName)
518
    {
519
        $serializerMetadata = $this->serializerMetadataFactory->getMetadataForClass($className);
520
        if ($serializerMetadata === null) {
521
            return null;
522
        }
523
        if (!isset($serializerMetadata->propertyMetadata[$fieldName])) {
524
            return null;
525
        }
526
527
        $type = $serializerMetadata->propertyMetadata[$fieldName]->type;
528
        return isset($type['name'], $type['params'][0]['name']) && $type['name'] === 'array' ?
529
            $type['params'][0]['name'] :
530
            null;
531
    }
532
}
533