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:
1 | <?php |
||
23 | class ImageThumbnail extends FieldWidgetDisplayBase implements ContainerFactoryPluginInterface { |
||
24 | |||
25 | /** |
||
26 | * Entity type manager service. |
||
27 | * |
||
28 | * @var \Drupal\Core\Entity\EntityTypeManagerInterface |
||
29 | */ |
||
30 | protected $entityTypeManager; |
||
31 | |||
32 | /** |
||
33 | * Constructs widget plugin. |
||
34 | * |
||
35 | * @param array $configuration |
||
36 | * A configuration array containing information about the plugin instance. |
||
37 | * @param string $plugin_id |
||
38 | * The plugin_id for the plugin instance. |
||
39 | * @param mixed $plugin_definition |
||
40 | * The plugin implementation definition. |
||
41 | * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager |
||
42 | * Entity manager service. |
||
43 | */ |
||
44 | public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager) { |
||
48 | |||
49 | /** |
||
50 | * {@inheritdoc} |
||
51 | */ |
||
52 | public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { |
||
60 | |||
61 | /** |
||
62 | * {@inheritdoc} |
||
63 | */ |
||
64 | public function view(EntityInterface $entity) { |
||
73 | |||
74 | /** |
||
75 | * {@inheritdoc} |
||
76 | */ |
||
77 | View Code Duplication | public function settingsForm(array $form, FormStateInterface $form_state) { |
|
|
|||
78 | $options = []; |
||
79 | foreach ($this->entityTypeManager->getStorage('image_style')->loadMultiple() as $id => $image_style) { |
||
80 | $options[$id] = $image_style->label(); |
||
81 | } |
||
82 | |||
83 | return [ |
||
84 | 'image_style' => [ |
||
85 | '#type' => 'select', |
||
86 | '#title' => $this->t('Image style'), |
||
87 | '#description' => $this->t('Select image style to be used to display thumbnails.'), |
||
88 | '#default_value' => $this->configuration['image_style'], |
||
89 | '#options' => $options, |
||
90 | ], |
||
91 | ]; |
||
92 | } |
||
93 | |||
94 | /** |
||
95 | * {@inheritdoc} |
||
96 | */ |
||
97 | public function isApplicable(EntityTypeInterface $entity_type) { |
||
100 | |||
101 | /** |
||
102 | * {@inheritdoc} |
||
103 | */ |
||
104 | public function defaultConfiguration() { |
||
109 | |||
110 | /** |
||
111 | * {@inheritdoc} |
||
112 | */ |
||
113 | public function calculateDependencies() { |
||
120 | |||
121 | } |
||
122 |
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.