Completed
Push — feature/min-max-field-lengths ( f79e0b )
by Narcotic
10:29
created

SchemaUtils::getCollectionSchema()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 10
ccs 0
cts 6
cp 0
rs 9.4285
cc 1
eloc 6
nc 1
nop 2
crap 2
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));
0 ignored issues
show
Bug introduced by
It seems like $this->getModelSchema($modelName, $model) targeting Graviton\SchemaBundle\Sc...Utils::getModelSchema() can also be of type object<stdClass>; however, Graviton\SchemaBundle\Document\Schema::setItems() does only seem to accept object<Graviton\SchemaBundle\Document\Schema>, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
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->setType('object');
220
221
        // grab schema info from model
222
        $repo = $model->getRepository();
223
        $meta = $repo->getClassMetadata();
224
225
        // Init sub searchable fields
226
        $subSearchableFields = array();
227
228
        // look for translatables in document class
229
        $documentReflection = new \ReflectionClass($repo->getClassName());
230
        if ($documentReflection->implementsInterface('Graviton\I18nBundle\Document\TranslatableDocumentInterface')) {
231
            /** @var TranslatableDocumentInterface $documentInstance */
232
            $documentInstance = $documentReflection->newInstanceWithoutConstructor();
233
            $translatableFields = array_merge(
234
                $documentInstance->getTranslatableFields(),
235
                $documentInstance->getPreTranslatedFields()
236
            );
237
        } else {
238
            $translatableFields = [];
239
        }
240
241
        if (!empty($translatableFields)) {
242
            $invalidateCacheMap[$this->languageRepository->getClassName()][] = $cacheKey;
243
        }
244
245
        // exposed fields
246
        $documentFieldNames = isset($this->documentFieldNames[$repo->getClassName()]) ?
247
            $this->documentFieldNames[$repo->getClassName()] :
248
            [];
249
250
        $languages = [];
251
        if ($online) {
252
            $languages = array_map(
253
                function (Language $language) {
254
                    return $language->getId();
255
                },
256
                $this->languageRepository->findAll()
257
            );
258
        }
259
        if (empty($languages)) {
260
            $languages = [
261
                $this->defaultLocale
262
            ];
263
        }
264
265
        // exposed events..
266
        $classShortName = $documentReflection->getShortName();
267
        if (isset($this->eventMap[$classShortName])) {
268
            $schema->setEventNames(array_unique($this->eventMap[$classShortName]['events']));
269
        }
270
271
        $requiredFields = [];
272
        $modelRequiredFields = $model->getRequiredFields();
273
        if (is_array($modelRequiredFields)) {
274
            foreach ($modelRequiredFields as $field) {
275
                // don't describe hidden fields
276
                if (!isset($documentFieldNames[$field])) {
277
                    continue;
278
                }
279
280
                $requiredFields[] = $documentFieldNames[$field];
281
            }
282
        }
283
284
        foreach ($meta->getFieldNames() as $field) {
285
            // don't describe hidden fields
286
            if (!isset($documentFieldNames[$field])) {
287
                continue;
288
            }
289
            // hide realId field (I was aiming at a cleaner solution than the macig realId string initially)
290
            if ($meta->getTypeOfField($field) == 'id' && $field == 'realId') {
291
                continue;
292
            }
293
294
            $property = new Schema();
295
            $property->setTitle($model->getTitleOfField($field));
296
            $property->setDescription($model->getDescriptionOfField($field));
297
298
            $property->setType($meta->getTypeOfField($field));
299
            $property->setReadOnly($model->getReadOnlyOfField($field));
300
301
            // we only want to render if it's true
302
            if ($model->getRecordOriginExceptionOfField($field) === true) {
303
                $property->setRecordOriginException(true);
304
            }
305
306
            if ($meta->getTypeOfField($field) === 'many') {
307
                $propertyModel = $model->manyPropertyModelForTarget($meta->getAssociationTargetClass($field));
308
309
                if ($model->hasDynamicKey($field)) {
310
                    $property->setType('object');
311
312
                    if ($online) {
313
                        // we generate a complete list of possible keys when we have access to mongodb
314
                        // this makes everything work with most json-schema v3 implementations (ie. schemaform.io)
315
                        $dynamicKeySpec = $model->getDynamicKeySpec($field);
316
317
                        $documentId = $dynamicKeySpec->{'document-id'};
318
                        $dynamicRepository = $this->repositoryFactory->get($documentId);
319
320
                        // put this in invalidate map so when know we have to invalidate when this document is used
321
                        $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...
322
323
                        $repositoryMethod = $dynamicKeySpec->{'repository-method'};
324
                        $records = $dynamicRepository->$repositoryMethod();
325
326
                        $dynamicProperties = array_map(
327
                            function ($record) {
328
                                return $record->getId();
329
                            },
330
                            $records
331
                        );
332
                        foreach ($dynamicProperties as $propertyName) {
333
                            $property->addProperty(
334
                                $propertyName,
335
                                $this->getModelSchema($field, $propertyModel, $online)
0 ignored issues
show
Bug introduced by
It seems like $this->getModelSchema($f...propertyModel, $online) targeting Graviton\SchemaBundle\Sc...Utils::getModelSchema() can also be of type object<stdClass>; however, Graviton\SchemaBundle\Do...t\Schema::addProperty() does only seem to accept object<Graviton\SchemaBundle\Document\Schema>, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
336
                            );
337
                        }
338
                    } else {
339
                        // swagger case
340
                        $property->setAdditionalProperties(
341
                            new SchemaAdditionalProperties($this->getModelSchema($field, $propertyModel, $online))
0 ignored issues
show
Bug introduced by
It seems like $this->getModelSchema($f...propertyModel, $online) targeting Graviton\SchemaBundle\Sc...Utils::getModelSchema() can also be of type object<stdClass>; however, Graviton\SchemaBundle\Do...operties::__construct() does only seem to accept object<Graviton\SchemaBu...ocument\Schema>|boolean, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
342
                        );
343
                    }
344
                } else {
345
                    $property->setItems($this->getModelSchema($field, $propertyModel, $online));
0 ignored issues
show
Bug introduced by
It seems like $this->getModelSchema($f...propertyModel, $online) targeting Graviton\SchemaBundle\Sc...Utils::getModelSchema() can also be of type object<stdClass>; however, Graviton\SchemaBundle\Document\Schema::setItems() does only seem to accept object<Graviton\SchemaBundle\Document\Schema>, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
346
                    $property->setType('array');
347
                }
348
            } elseif ($meta->getTypeOfField($field) === 'one') {
349
                $propertyModel = $model->manyPropertyModelForTarget($meta->getAssociationTargetClass($field));
350
                $property = $this->getModelSchema($field, $propertyModel, $online);
351
352
                if ($property->getSearchable()) {
353
                    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...
354
                        $subSearchableFields[] = $field . '.' . $searchableSubField;
355
                    }
356
                }
357
            } elseif (in_array($field, $translatableFields, true)) {
358
                $property = $this->makeTranslatable($property, $languages);
359
            } elseif (in_array($field.'[]', $translatableFields, true)) {
360
                $property = $this->makeArrayTranslatable($property, $languages);
361
            } elseif ($meta->getTypeOfField($field) === 'extref') {
362
                $urls = array();
363
                $refCollections = $model->getRefCollectionOfField($field);
364
                foreach ($refCollections as $collection) {
365
                    if (isset($this->extrefServiceMapping[$collection])) {
366
                        $urls[] = $this->router->generate(
367
                            $this->extrefServiceMapping[$collection].'.all',
368
                            [],
369
                            UrlGeneratorInterface::ABSOLUTE_URL
370
                        );
371
                    } elseif ($collection === '*') {
372
                        $urls[] = '*';
373
                    }
374
                }
375
                $property->setRefCollection($urls);
376 View Code Duplication
            } elseif ($meta->getTypeOfField($field) === 'collection') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
377
                $itemSchema = new Schema();
378
                $property->setType('array');
379
                $itemSchema->setType($this->getCollectionItemType($meta->name, $field));
380
381
                $property->setItems($itemSchema);
382
                $property->setFormat(null);
383
            } elseif ($meta->getTypeOfField($field) === 'datearray') {
384
                $itemSchema = new Schema();
385
                $property->setType('array');
386
                $itemSchema->setType('string');
387
                $itemSchema->setFormat('date-time');
388
389
                $property->setItems($itemSchema);
390
                $property->setFormat(null);
391 View Code Duplication
            } elseif ($meta->getTypeOfField($field) === 'hasharray') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
392
                $itemSchema = new Schema();
393
                $itemSchema->setType('object');
394
395
                $property->setType('array');
396
                $property->setItems($itemSchema);
397
                $property->setFormat(null);
398
            }
399
400
            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...
401
                // make sure a required field cannot be blank
402
                if (in_array($documentFieldNames[$field], $requiredFields)) {
403
                    $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...
404
                } else {
405
                    // in the other case, make sure also null can be sent..
406
                    $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...
407
                    if ($currentType instanceof SchemaType) {
408
                        $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...
409
                    } else {
410
                        $property->setType('null');
411
                    }
412
                }
413
            }
414
415
            $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...
416
417
            // min/max length always last as it may (and should) override other constraints, like required
418
            $minLength = $model->getMinLength($field);
419
            if (is_numeric($minLength) && $minLength > 0) {
420
                $property->setMinLength($minLength);
421
            }
422
            $maxLength = $model->getMaxLength($field);
423
            if (is_numeric($maxLength) && $maxLength > 0) {
424
                $property->setMaxLength($maxLength);
425
            }
426
427
            $schema->addProperty($documentFieldNames[$field], $property);
428
        }
429
430
        if ($meta->isEmbeddedDocument && !in_array('id', $model->getRequiredFields())) {
431
            $schema->removeProperty('id');
432
        }
433
434
        /**
435
         * if we generate schema for internal use; don't have id in required array as
436
         * it's 'requiredness' depends on the method used (POST/PUT/PATCH) and is checked in checks
437
         * before validation.
438
         */
439
        $idPosition = array_search('id', $requiredFields);
440
        if ($internal === true && $idPosition !== false) {
441
            unset($requiredFields[$idPosition]);
442
        }
443
444
        $schema->setRequired($requiredFields);
445
446
        // set additionalProperties to false (as this is our default policy) if not already set
447
        if (is_null($schema->getAdditionalProperties()) && $online) {
448
            $schema->setAdditionalProperties(new SchemaAdditionalProperties(false));
449
        }
450
451
        $searchableFields = array_merge($subSearchableFields, $model->getSearchableFields());
452
        $schema->setSearchable($searchableFields);
453
454
        if ($serialized === true) {
455
            $schema = json_decode($this->serializer->serialize($schema, 'json'));
456
        }
457
458
        $this->cache->save($cacheKey, $schema);
459
        $this->cache->save($this->cacheInvalidationMapKey, $invalidateCacheMap);
460
461
        return $schema;
462
    }
463
464
    /**
465
     * turn a property into a translatable property
466
     *
467
     * @param Schema   $property  simple string property
468
     * @param string[] $languages available languages
469
     *
470
     * @return Schema
471
     */
472
    public function makeTranslatable(Schema $property, $languages)
473
    {
474
        $property->setType('object');
475
        $property->setTranslatable(true);
476
477
        array_walk(
478
            $languages,
479
            function ($language) use ($property) {
480
                $schema = new Schema;
481
                $schema->setType('string');
482
                $schema->setTitle('Translated String');
483
                $schema->setDescription('String in ' . $language . ' locale.');
484
                $property->addProperty($language, $schema);
485
            }
486
        );
487
        $property->setRequired(['en']);
488
        return $property;
489
    }
490
491
    /**
492
     * turn a array property into a translatable property
493
     *
494
     * @param Schema   $property  simple string property
495
     * @param string[] $languages available languages
496
     *
497
     * @return Schema
498
     */
499
    public function makeArrayTranslatable(Schema $property, $languages)
500
    {
501
        $property->setType('array');
502
        $property->setItems($this->makeTranslatable(new Schema(), $languages));
503
        return $property;
504
    }
505
506
    /**
507
     * get canonical route to a schema based on a route
508
     *
509
     * @param string $routeName route name
510
     *
511
     * @return string schema route name
512
     */
513
    public static function getSchemaRouteName($routeName)
514
    {
515
        $routeParts = explode('.', $routeName);
516
517
        $routeType = array_pop($routeParts);
518
        // check if we need to create an item or collection schema
519
        $realRouteType = 'canonicalSchema';
520
        if ($routeType != 'options' && $routeType != 'all') {
521
            $realRouteType = 'canonicalIdSchema';
522
        }
523
524
        return implode('.', array_merge($routeParts, array($realRouteType)));
525
    }
526
527
    /**
528
     * Get item type of collection field
529
     *
530
     * @param string $className Class name
531
     * @param string $fieldName Field name
532
     * @return string|null
533
     */
534
    private function getCollectionItemType($className, $fieldName)
535
    {
536
        $serializerMetadata = $this->serializerMetadataFactory->getMetadataForClass($className);
537
        if ($serializerMetadata === null) {
538
            return null;
539
        }
540
        if (!isset($serializerMetadata->propertyMetadata[$fieldName])) {
541
            return null;
542
        }
543
544
        $type = $serializerMetadata->propertyMetadata[$fieldName]->type;
545
        return isset($type['name'], $type['params'][0]['name']) && $type['name'] === 'array' ?
546
            $type['params'][0]['name'] :
547
            null;
548
    }
549
}
550