Completed
Push — feature/EVO-7324-id-as-null-fi... ( e8d4b0 )
by
unknown
08:53
created

SchemaUtils   D

Complexity

Total Complexity 58

Size/Duplication

Total Lines 514
Duplicated Lines 3.11 %

Coupling/Cohesion

Components 1
Dependencies 15

Test Coverage

Coverage 5.58%

Importance

Changes 0
Metric Value
wmc 58
lcom 1
cbo 15
dl 16
loc 514
ccs 14
cts 251
cp 0.0558
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
F getModelSchema() 16 280 46
A makeTranslatable() 0 18 1
A makeArrayTranslatable() 0 6 1
A getSchemaRouteName() 0 13 3
B getCollectionItemType() 0 15 5

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