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 |
||
12 | class PostType extends AbstractType |
||
13 | { |
||
14 | /** |
||
15 | * @param FormBuilderInterface $builder |
||
16 | * @param $options |
||
17 | */ |
||
18 | public function buildForm(FormBuilderInterface $builder, array $options) |
||
19 | { |
||
20 | $builder->add('title', 'text'); |
||
21 | |||
22 | $builder->add('image', 'file', array( |
||
23 | 'required' => false, |
||
24 | )); |
||
25 | $builder->add('removeImage', 'checkbox', array( |
||
26 | 'required' => false, |
||
27 | 'data' => false, |
||
28 | 'label' => 'Remove image?', |
||
29 | 'attr' => array( |
||
30 | 'data-help-text' => 'Should the image be removed (goes into effect after the save)?', |
||
31 | ), |
||
32 | )); |
||
33 | |||
34 | $builder->add('content', 'textarea', array( |
||
35 | 'required' => false, |
||
36 | 'attr' => array( |
||
37 | 'class' => 'html-editor', |
||
38 | ), |
||
39 | )); |
||
40 | |||
41 | $builder->add('user', 'entity', array( |
||
42 | 'required' => false, |
||
43 | 'empty_value' => false, |
||
44 | 'class' => 'Application\Entity\UserEntity', |
||
45 | 'attr' => array( |
||
46 | 'class' => 'select-picker', |
||
47 | 'data-live-search' => 'true', |
||
48 | ), |
||
49 | )); |
||
50 | |||
51 | $builder->add('postMetas', 'collection', array( |
||
52 | 'type' => new PostMetaType(), |
||
53 | 'allow_add' => true, |
||
54 | 'allow_delete' => true, |
||
55 | 'delete_empty' => true, |
||
56 | 'prototype' => true, |
||
57 | 'cascade_validation' => true, |
||
58 | 'error_bubbling' => false, |
||
59 | 'by_reference' => false, |
||
60 | )); |
||
61 | |||
62 | $builder->add('submitButton', 'submit', array( |
||
63 | 'label' => 'Save', |
||
64 | 'attr' => array( |
||
65 | 'class' => 'btn-primary btn-lg btn-block', |
||
66 | ), |
||
67 | )); |
||
68 | } |
||
69 | |||
70 | /** |
||
71 | * @param OptionsResolverInterface $resolver |
||
72 | */ |
||
73 | View Code Duplication | public function setDefaultOptions(OptionsResolverInterface $resolver) |
|
|
|||
74 | { |
||
75 | $resolver->setDefaults(array( |
||
76 | 'data_class' => 'Application\Entity\PostEntity', |
||
77 | 'validation_groups' => array('new_and_edit'), |
||
78 | 'csrf_protection' => true, |
||
79 | 'csrf_field_name' => 'csrf_token', |
||
80 | )); |
||
81 | } |
||
82 | |||
83 | /** |
||
84 | * @return string |
||
85 | */ |
||
86 | public function getName() |
||
90 | } |
||
91 |
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.