Completed
Push — master ( 6ebb44...8dedb1 )
by cam
04:35
created

precharger_objet.php ➔ precharger_traduction_objet()   C

Complexity

Conditions 14
Paths 66

Size

Total Lines 74

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
nc 66
nop 5
dl 0
loc 74
rs 5.5805
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/***************************************************************************\
4
 *  SPIP, Système de publication pour l'internet                           *
5
 *                                                                         *
6
 *  Copyright © avec tendresse depuis 2001                                 *
7
 *  Arnaud Martin, Antoine Pitrou, Philippe Rivière, Emmanuel Saint-James  *
8
 *                                                                         *
9
 *  Ce programme est un logiciel libre distribué sous licence GNU/GPL.     *
10
 *  Pour plus de détails voir le fichier COPYING.txt ou l'aide en ligne.   *
11
\***************************************************************************/
12
13
/**
14
 * Préchargement les formulaires d'édition d'objets, notament pour les traductions
15
 *
16
 * @package SPIP\Core\Objets
17
 **/
18
19
if (!defined('_ECRIRE_INC_VERSION')) {
20
	return;
21
}
22
23
include_spip('inc/autoriser'); // necessaire si appel de l'espace public
24
25
26
/**
27
 * Retourne les valeurs à charger pour un formulaire d'édition d'un objet
28
 *
29
 * Lors d'une création, certains champs peuvent être préremplis
30
 * (c'est le cas des traductions)
31
 *
32
 * @param string $type
33
 *     Type d'objet (article, breve...)
34
 * @param string|int $id_objet
35
 *     Identifiant de l'objet, ou "new" pour une création
36
 * @param int $id_rubrique
37
 *     Identifiant éventuel de la rubrique parente
38
 * @param int $lier_trad
39
 *     Identifiant éventuel de la traduction de référence
40
 * @param string $champ_titre
41
 *     Nom de la colonne SQL de l'objet donnant le titre : pas vraiment idéal !
42
 *     On devrait pouvoir le savoir dans la déclaration de l'objet
43
 * @return array
44
 *     Couples clés / valeurs des champs du formulaire à charger.
45
 **/
46
function precharger_objet($type, $id_objet, $id_rubrique = 0, $lier_trad = 0, $champ_titre = 'titre') {
47
48
	$table = table_objet_sql($type);
49
	$_id_objet = id_table_objet($table);
50
51
	// si l'objet existe deja, on retourne simplement ses valeurs
52
	if (is_numeric($id_objet)) {
53
		return sql_fetsel("*", $table, "$_id_objet=".intval($id_objet));
54
	}
55
56
	// ici, on demande une creation.
57
	// on prerempli certains elements : les champs si traduction,
58
	// les id_rubrique et id_secteur si l'objet a ces champs
59
	$desc = lister_tables_objets_sql($table);
60
	# il faudrait calculer $champ_titre ici
61
	$is_rubrique = isset($desc['field']['id_rubrique']);
62
	$is_secteur = isset($desc['field']['id_secteur']);
63
64
	// si demande de traduction
65
	// on recupere les valeurs de la traduction
66
	if ($lier_trad) {
67
		if ($select = charger_fonction("precharger_traduction_" . $type, 'inc', true)) {
68
			$row = $select($id_objet, $id_rubrique, $lier_trad);
69
		} else {
70
			$row = precharger_traduction_objet($type, $id_objet, $id_rubrique, $lier_trad, $champ_titre);
71
		}
72
	} else {
73
		$row[$champ_titre] = '';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$row was never initialized. Although not strictly required by PHP, it is generally a good practice to add $row = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
74
		if ($is_rubrique) {
75
			$row['id_rubrique'] = $id_rubrique;
76
		}
77
	}
78
79
	// calcul de la rubrique
80
	# note : comment faire pour des traductions sur l'objet rubriques ?
81
	if ($is_rubrique) {
82
		// appel du script a la racine, faut choisir 
83
		// admin restreint ==> sa premiere rubrique
84
		// autre ==> la derniere rubrique cree
85
		if (!$row['id_rubrique']) {
86
			if ($GLOBALS['connect_id_rubrique']) {
87
				$row['id_rubrique'] = $id_rubrique = current($GLOBALS['connect_id_rubrique']);
88 View Code Duplication
			} else {
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...
89
				$row_rub = sql_fetsel("id_rubrique", "spip_rubriques", "", "", "id_rubrique DESC", 1);
90
				$row['id_rubrique'] = $id_rubrique = $row_rub['id_rubrique'];
91
			}
92
			if (!autoriser('creerarticledans', 'rubrique', $row['id_rubrique'])) {
93
				// manque de chance, la rubrique n'est pas autorisee, on cherche un des secteurs autorises
94
				$res = sql_select("id_rubrique", "spip_rubriques", "id_parent=0");
95
				while (!autoriser('creerarticledans', 'rubrique', $row['id_rubrique']) && $row_rub = sql_fetch($res)) {
96
					$row['id_rubrique'] = $row_rub['id_rubrique'];
97
				}
98
			}
99
		}
100
	}
101
102
	// recuperer le secteur, pour affecter les bons champs extras
103
	if ($id_rubrique and $is_secteur) {
104
		if (!$row['id_secteur']) {
105
			$row_rub = sql_getfetsel("id_secteur", "spip_rubriques", "id_rubrique=" . sql_quote($id_rubrique));
106
			$row['id_secteur'] = $row_rub;
107
		}
108
	}
109
110
	return $row;
111
}
112
113
114
/**
115
 * Récupère les valeurs d'une traduction de référence pour la création
116
 * d'un objet (préremplissage du formulaire).
117
 *
118
 * @param string $type
119
 *     Type d'objet (article, breve...)
120
 * @param string|int $id_objet
121
 *     Identifiant de l'objet, ou "new" pour une création
122
 * @param int $id_rubrique
123
 *     Identifiant éventuel de la rubrique parente
124
 * @param int $lier_trad
125
 *     Identifiant éventuel de la traduction de référence
126
 * @param string $champ_titre
127
 *     Nom de la colonne SQL de l'objet donnant le titre
128
 * @return array
129
 *     Couples clés / valeurs des champs du formulaire à charger
130
 **/
131
function precharger_traduction_objet($type, $id_objet, $id_rubrique = 0, $lier_trad = 0, $champ_titre = 'titre') {
0 ignored issues
show
Unused Code introduced by
The parameter $id_objet is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
132
	$table = table_objet_sql($type);
133
	$_id_objet = id_table_objet($table);
134
135
	// Recuperer les donnees de l'objet original
136
	$row = sql_fetsel("*", $table, "$_id_objet=".intval($lier_trad));
137
	if ($row) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $row of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
138
		include_spip('inc/filtres');
139
		$row[$champ_titre] = filtrer_entites(objet_T($type, 'info_nouvelle_traduction')) . ' ' . $row[$champ_titre];
140
	} else {
141
		$row = array();
142
	}
143
144
	// on met l'objet dans une rubrique si l'objet le peut
145
	$desc = lister_tables_objets_sql($table);
146
	$is_rubrique = isset($desc['field']['id_rubrique']);
147
148
	if ($is_rubrique) {
149
		$langues_dispo = explode(',', $GLOBALS['meta']['langues_multilingue']);
150
		// si le redacteur utilise une autre langue que celle de la source, on suppose que c'est pour traduire dans sa langue
151
		if (in_array($GLOBALS['spip_lang'], $langues_dispo) and $GLOBALS['spip_lang'] !== $row['lang']) {
152
			$row['lang'] = $GLOBALS['spip_lang'];
153
		}
154
		// sinon si il y a seulement 2 langues dispos, on bascule sur l'"autre"
155
		elseif (count($langues_dispo) == 2) {
156
			$autre_langue = array_diff($langues_dispo, [$row['lang']]);
157
			if (count($autre_langue) == 1) {
158
				$row['lang'] = reset($autre_langue);
159
			}
160
		}
161
		else {
162
			$row['lang'] = 'en';
163
		}
164
165
		if ($id_rubrique) {
166
			$row['id_rubrique'] = $id_rubrique;
167
168
			return $row;
169
		}
170
		$id_rubrique = $row['id_rubrique'];
171
172
173
		// Regler la langue, si possible, sur celle du redacteur
174
		// Cela implique souvent de choisir une rubrique ou un secteur
175
		if (in_array($GLOBALS['spip_lang'], $langues_dispo)) {
176
177
			// Si le menu de langues est autorise sur l'objet,
178
			// on peut changer la langue quelle que soit la rubrique
179
			// donc on reste dans la meme rubrique
180
			if (in_array($table, explode(',', $GLOBALS['meta']['multi_objets']))) {
181
				$row['id_rubrique'] = $row['id_rubrique']; # explicite :-)
182
183
				// Sinon, chercher la rubrique la plus adaptee pour
184
				// accueillir l'objet dans la langue du traducteur
185
			} elseif ($is_rubrique and $GLOBALS['meta']['multi_rubriques'] == 'oui') {
186
				if ($GLOBALS['meta']['multi_secteurs'] == 'oui') {
187
					$id_parent = 0;
188
				} else {
189
					// on cherche une rubrique soeur dans la bonne langue
190
					$row_rub = sql_fetsel("id_parent", "spip_rubriques", "id_rubrique=".intval($id_rubrique));
191
					$id_parent = $row_rub['id_parent'];
192
				}
193
194
				$row_rub = sql_fetsel("id_rubrique", "spip_rubriques",
195
					"lang='" . $GLOBALS['spip_lang'] . "' AND id_parent=".intval($id_parent));
196
				if ($row_rub) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $row_rub of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
197
					$row['id_rubrique'] = $row_rub['id_rubrique'];
198
				}
199
			}
200
		}
201
	}
202
203
	return $row;
204
}
205