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 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 |
||
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( |
|
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) |
||
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()); |
||
|
|||
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; |
||
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) { |
||
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())) { |
||
398 | // make sure a required field cannot be blank |
||
399 | if (in_array($documentFieldNames[$field], $requiredFields)) { |
||
400 | $property->setMinLength(1); |
||
401 | } else { |
||
402 | // in the other case, make sure also null can be sent.. |
||
403 | $currentType = $property->getType(); |
||
404 | if ($currentType instanceof SchemaType) { |
||
405 | $property->setType(array_merge($currentType->getTypes(), ['null'])); |
||
406 | } else { |
||
407 | $property->setType('null'); |
||
408 | } |
||
409 | } |
||
410 | } |
||
411 | |||
412 | $property = $this->constraintBuilder->addConstraints($field, $property, $model); |
||
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) |
||
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) |
||
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) |
||
532 | } |
||
533 |