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 |
||
11 | class AdministratorsRequest extends FormRequest |
||
12 | { |
||
13 | /** |
||
14 | * Retourne un tableau de validation par champ. |
||
15 | * |
||
16 | * @return array |
||
17 | */ |
||
18 | public function rules() |
||
19 | { |
||
20 | // Je viens recupérer mon id en URL si je suis en mode edition |
||
21 | // Depuis ma route, je peux récupérer un argument "id" |
||
22 | $id = $this->route('id'); |
||
23 | |||
24 | // Création d'administrateur |
||
25 | if ($id === null) { |
||
26 | return [ |
||
27 | 'firstname' => 'required|max:255', |
||
28 | 'lastname' => 'required|max:255', |
||
29 | 'description' => 'required|min:10', |
||
30 | 'email' => 'required|email|max:255|unique:administrators', |
||
31 | 'password' => 'required|confirmed|min:6', |
||
32 | 'image' => 'required|image', |
||
33 | ]; |
||
34 | } |
||
35 | // Edition administrateur |
||
36 | else { |
||
37 | return [ |
||
38 | 'firstname' => 'required|max:255', |
||
39 | 'lastname' => 'required|max:255', |
||
40 | 'description' => 'required|min:10', |
||
41 | 'email' => 'required|email|max:255|unique:administrators,email,'.$id, |
||
42 | 'password' => 'confirmed|min:6', |
||
43 | 'image' => 'image', |
||
44 | ]; |
||
45 | } |
||
46 | } |
||
47 | |||
48 | /** |
||
49 | * Customisation des messages par champs. |
||
50 | * |
||
51 | * @return array |
||
52 | */ |
||
53 | View Code Duplication | public function messages() |
|
|
|||
54 | { |
||
55 | return [ |
||
56 | 'title.required' => 'Un titre pour le film!', |
||
57 | 'required' => ':attribute est obligatoire', |
||
58 | 'min' => 'Ce champ doit faire plus de :min caractères', |
||
59 | 'max' => 'Ce champ doit faire moins de :max caractères', |
||
60 | 'integer' => 'Ce champ doit être un chiffre', |
||
61 | 'regex' => ':attribute a un mauvais format', |
||
62 | 'date_format' => 'Le format de date doit etre valide', |
||
63 | 'image' => "Le format de l'image est invalide", |
||
64 | ]; |
||
65 | } |
||
66 | |||
67 | /** |
||
68 | * Autoriser l'accès de mon formulaire |
||
69 | * pour tout utilisateur. |
||
70 | * |
||
71 | * @return bool |
||
72 | */ |
||
73 | public function authorize() |
||
77 | } |
||
78 |
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.