Completed
Push — master ( a92ebb...0067ae )
by
unknown
02:15
created

src/server/controllers/editor.js   F

Complexity

Total Complexity 74
Complexity/F 4.35

Size

Lines of Code 272
Function Count 17

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 2 Features 0
Metric Value
cc 0
wmc 74
nc 1
mnd 5
bc 58
fnc 17
dl 0
loc 272
rs 3.931
bpm 3.4117
cpm 4.3529
noi 9
c 2
b 2
f 0

9 Functions

Rating   Name   Duplication   Size   Complexity  
A editor.js ➔ insertAbeEach 0 14 4
A editor.js ➔ matchAttrAbe 0 8 2
A editor.js ➔ orderByTabindex 0 9 3
C editor.js ➔ addToForm 0 26 8
C editor.js ➔ add 0 27 15
A editor.js ➔ addSource 0 15 3
D editor.js ➔ each 0 44 10
C editor.js ➔ orderBlock 0 60 11
A editor.js ➔ editor 0 49 1

How to fix   Complexity   

Complexity

Complex classes like src/server/controllers/editor.js 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.

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.

1
import {Promise} from 'bluebird'
2
import path from 'path'
3
4
import {
5
  cmsData,
6
  cmsEditor,
7
  coreUtils,
0 ignored issues
show
Unused Code introduced by
The variable coreUtils seems to be never used. Consider removing it.
Loading history...
8
  abeEngine,
9
  cmsTemplates,
0 ignored issues
show
Unused Code introduced by
The variable cmsTemplates seems to be never used. Consider removing it.
Loading history...
10
  abeExtend
11
} from '../../cli'
12
13
function add(obj, json, text, util) {
14
  var value = obj.value
15
  
16
  if(obj.key.indexOf('[') > -1) {
17
    var key = obj.key.split('[')[0]
18
    var index = obj.key.match(/[^\[]+?(?=\])/)[0]
19
    var prop = obj.key.replace(/[^\.]+?\./, '')
20
21
    if(typeof json[key] !== 'undefined' && json[key] !== null &&
22
       typeof json[key][index] !== 'undefined' && json[key][index] !== null &&
23
       typeof json[key][index][prop] !== 'undefined' && json[key][index][prop] !== null) {
24
      obj.value = json[key][index][prop]
25
    }else if(typeof value !== 'undefined' && value !== null && value !== '') {
26
      if(typeof json[key] === 'undefined' || json[key] === null){
27
        json[key] = []
28
      }
29
      if(typeof json[key][index] === 'undefined' || json[key][index] === null){
30
        json[key][index] = {}
31
      }
32
      json[key][index][prop] = value
33
    }
34
  }
35
36
  util.add(obj)
37
38
  return value
39
}
40
41
function addToForm(match, text, json, util, arrayBlock, keyArray = null, i = 0) {
42
  var v = `{{${match}}}`,
43
    obj = cmsData.attributes.getAll(v, json)
44
45
  var realKey
46
  if(typeof keyArray !== 'undefined' && keyArray !== null) {
47
    realKey = obj.key.replace(/[^\.]+?\./, '')
48
49
    if(obj.key.indexOf(keyArray + '.') >= 0 && realKey.length > 0){
50
      obj.keyArray = keyArray
51
      obj.realKey = realKey
52
      obj.key = keyArray + '[' + i + '].' + realKey
53
      obj.desc = obj.desc + ' ' + i,
0 ignored issues
show
Comprehensibility introduced by
Usage of the sequence operator is discouraged, since it may lead to obfuscated code.

The sequence or comma operator allows the inclusion of multiple expressions where only is permitted. The result of the sequence is the value of the last expression.

This operator is most often used in for statements.

Used in another places it can make code hard to read, especially when people do not realize it even exists as a seperate operator.

This check looks for usage of the sequence operator in locations where it is not necessary and could be replaced by a series of expressions or statements.

var a,b,c;

a = 1, b = 1,  c= 3;

could just as well be written as:

var a,b,c;

a = 1;
b = 1;
c = 3;

To learn more about the sequence operator, please refer to the MDN.

Loading history...
54
      insertAbeEach(obj, text, json, util, arrayBlock)
55
56
    }else if(util.dontHaveKey(obj.key)) {
57
      obj.value = json[obj.key]
58
      json[obj.key] = add(obj, json, text, util)
59
    }
60
61
  }else if(util.dontHaveKey(obj.key) && cmsData.regex.isSingleAbe(v, text)) {
62
    realKey = obj.key.replace(/\./g, '-')
63
    obj.value = json[realKey]
64
    json[obj.key] = add(obj, json, text, util)
65
  }
66
}
67
68
function matchAttrAbe(text, json, util, arrayBlock) {
69
  var patt = /abe [^{{}}]+?(?=\}})/g,
70
    match
71
  // While regexp match HandlebarsJS template item => keepgoing
72
  while (match = patt.exec(text)) {
73
    addToForm(match[0], text, json, util, arrayBlock, null, null)
74
  }
75
}
76
77
function insertAbeEach (obj, text, json, util, arrayBlock) {
78
  if(typeof arrayBlock[obj.keyArray][obj.realKey] === 'undefined' || arrayBlock[obj.keyArray][obj.realKey] === null) {
79
    arrayBlock[obj.keyArray][obj.realKey] = []
80
  }
81
  var exist = false
82
  Array.prototype.forEach.call(arrayBlock[obj.keyArray][obj.realKey], (block) => {
83
    if(block.key === obj.key) {
84
      exist = true
85
    }
86
  })
87
  if(!exist) {
88
    arrayBlock[obj.keyArray][obj.realKey].push(obj)
89
  }
90
}
91
92
function each(text, json, util, arrayBlock) {
93
  let pattEach = /(\{\{#each (\r|\t|\n|.)*?\/each\}\})/g
94
  let patt = /abe [^{{}}]+?(?=\}})/g
95
  var textEach, match
96
97
  while (textEach = pattEach.exec(text)) {
98
    var i
99
    var keyArray = textEach[0].match(/#each (\n|.)*?\}/)
100
    keyArray = keyArray[0].slice(6, keyArray[0].length - 1)
101
102
    if(keyArray.split(' ').length > 1){
103
      keyArray = keyArray.split(' ')[0]
104
    }
105
    arrayBlock[keyArray] = []
106
    // ce while boucle sur les block de contenu {{abe}}
107
    while (match = patt.exec(textEach[0])) {
108
      var v = match[0]
109
110
      if(v.indexOf('abe') > -1){
111
        if(json[keyArray]){
112
          for (i = 0; i < json[keyArray].length; i++) {
113
            addToForm(v, text, json, util, arrayBlock, keyArray, i)
114
          }
115
        }else{
116
          addToForm(v, text, json, util, arrayBlock, keyArray, 0)
117
        }
118
      }
119
    }
120
121
    // ici on boucle a nouveau sur les champs pour les placer a la suite dans le formulaire
122
    var attrArray = [],
123
      length = 0
124
    for(var index in arrayBlock[keyArray]) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
125
      attrArray.push(index)
126
      length = arrayBlock[keyArray][index].length
127
    }
128
129
    for (i = 0; i < length; i++) {
130
      for (var j = 0; j < attrArray.length; j++) {
131
        add(arrayBlock[keyArray][attrArray[j]][i], json, text, util)
132
      }
133
    }
134
  }
135
}
136
137
function addSource(text, json, util) {
138
  var listReg = /({{abe.*type=[\'|\"]data.*}})/g
139
  var match
140
141
  while (match = listReg.exec(text)) {
142
    var obj = cmsData.attributes.getAll(match[0], json)
143
144
    if(obj.editable) {
145
      obj.value = json[obj.key]
146
      add(obj, json, text, util)
147
    }else {
148
      json[obj.key] = obj.source
149
    }
150
  }
151
}
152
153
function orderByTabindex(a, b) {
154
  if(a.order < b.order) {
155
    return -1
156
  }else if(a.order > b.order) {
157
    return 1
158
  }
159
160
  return 0
161
}
162
163
function orderBlock(util) {
164
    
165
  var formBlock = {}
166
167
  for(var tab in util.form) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
168
169
    var formBlockTab = {}
170
    for (var i = 0; i < util.form[tab].item.length; i++) {
171
      var blockName = (util.form[tab].item[i].block === '') ? 'default_' + i : util.form[tab].item[i].block
172
      if(util.form[tab].item[i].key.indexOf('[') > -1){
173
        blockName = util.form[tab].item[i].key.split('[')[0]
174
      }
175
      if(typeof formBlockTab[blockName] === 'undefined' || formBlockTab[blockName] === null) {
176
        formBlockTab[blockName] = []
177
      }
178
      formBlockTab[blockName].push(util.form[tab].item[i])
179
    }
180
    if(typeof blockName !== 'undefined' && blockName !== null) {
0 ignored issues
show
Bug introduced by
The variable blockName seems to not be initialized for all possible execution paths.
Loading history...
181
      formBlockTab[blockName].sort(orderByTabindex)
182
    }
183
    if(typeof formBlock[tab] === 'undefined' || formBlock[tab] === null) {
184
      formBlock[tab] = {}
185
    }
186
187
    var formBlockOrdered = {}
188
    var arKeys = Object.keys(formBlockTab).sort((a,b) => {
189
      if(parseFloat(formBlockTab[a][0].order) < parseFloat(formBlockTab[b][0].order)) {
0 ignored issues
show
Bug introduced by
The variable formBlockTab is changed as part of the for-each loop for example by {} on line 169. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
190
        return -1
191
      }else if(parseFloat(formBlockTab[a][0].order) > parseFloat(formBlockTab[b][0].order)) {
192
        return 1
193
      }
194
      return 0
195
    })
196
197
    Array.prototype.forEach.call(arKeys, (arKey) => {
198
      formBlockOrdered[arKey] = formBlockTab[arKey]
0 ignored issues
show
Bug introduced by
The variable formBlockOrdered is changed as part of the for-each loop for example by {} on line 187. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
Bug introduced by
The variable formBlockTab is changed as part of the for-each loop for example by {} on line 169. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
199
    })
200
    formBlock[tab] = formBlockOrdered
201
  }
202
203
  var formTabsOrdered = {}
204
  var arKeysTabs = Object.keys(formBlock).sort((a,b) => {
205
    if(parseFloat(formBlock[a][Object.keys(formBlock[a])[0]][0].order) < parseFloat(formBlock[b][Object.keys(formBlock[b])[0]][0].order)) {
206
      return -1
207
    }else if(parseFloat(formBlock[a][Object.keys(formBlock[a])[0]][0].order) > parseFloat(formBlock[b][Object.keys(formBlock[b])[0]][0].order)) {
208
      return 1
209
    }
210
    return 0
211
  })
212
213
  Array.prototype.forEach.call(arKeysTabs, (arKeysTab) => {
214
    if (arKeysTab !== 'Precontribution') {
215
      formTabsOrdered[arKeysTab] = formBlock[arKeysTab]
216
    }
217
  })
218
219
  formTabsOrdered['Precontribution'] = formBlock['Precontribution']
220
221
  return formTabsOrdered
222
}
223
224
export function editor(text, json, documentLink) {
225
  let p = new Promise((resolve) => {
226
    var util = new cmsEditor.form()
227
    var arrayBlock = []
228
    
229
    cmsData.source.getDataList(path.dirname(documentLink), text, json)
230
      .then(() => {
231
        addSource(text, json, util)
232
233
        text = cmsData.source.removeDataList(text)
234
235
        var matches = cmsData.regex.getTagAbePrecontribution(text)
236
        if (matches.length === 0) {
237
          text = `${text}\n{{abe type='text' key='abe_filename' desc='Name' required="true" precontrib="true" slug="true" slugType="name" visible="false"}}`
238
        }
239
240
        matchAttrAbe(text, json, util, arrayBlock)
241
        arrayBlock = []
242
        each(text, json, util, arrayBlock)
243
244
        if(typeof json.abe_meta !== 'undefined' && json.abe_meta !== null) {
245
          var links = json.abe_meta.link.split('/')
246
          var link = links.pop()
247
          json.abe_meta.cleanName = link.replace(/\..+$/, '')
248
          json.abe_meta.cleanFilename = links.join('/').replace(/\..+$/, '')
249
        }
250
251
        // HOOKS beforeEditorFormBlocks
252
        json = abeExtend.hooks.instance.trigger('beforeEditorFormBlocks', json, text)
253
254
        var blocks = orderBlock(util)
255
256
        // HOOKS afterEditorFormBlocks
257
        blocks = abeExtend.hooks.instance.trigger('afterEditorFormBlocks', blocks, json, text)
258
259
        abeEngine.instance.content = json
260
261
        resolve({
262
          text: text,
263
          form: blocks,
264
          json: json
265
        })
266
      }).catch(function(e) {
267
        console.error(e)
268
      })
269
  })
270
271
  return p
272
}