Completed
Push — master ( beada9...352554 )
by greg
02:43
created

src/server/controllers/editor.js   F

Complexity

Total Complexity 73
Complexity/F 4.29

Size

Lines of Code 278
Function Count 17

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 0
wmc 73
c 2
b 1
f 0
nc 1
mnd 5
bc 57
fnc 17
dl 0
loc 278
rs 3.9761
bpm 3.3529
cpm 4.2941
noi 7

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 ➔ orderBlock 0 56 11
C editor.js ➔ add 0 27 15
A editor.js ➔ addSource 0 15 3
D editor.js ➔ each 0 44 10
A editor.js ➔ editor 0 59 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,
8
  abeEngine,
9
  cmsTemplates,
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(formBlockTab[a][0].order < 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(formBlockTab[a][0].order > 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(formBlock[a][Object.keys(formBlock[a])[0]][0].order < formBlock[b][Object.keys(formBlock[b])[0]][0].order) {
206
      return -1
207
    }else if(formBlock[a][Object.keys(formBlock[a])[0]][0].order > 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
    formTabsOrdered[arKeysTab] = formBlock[arKeysTab]
215
  })
216
217
  return formTabsOrdered
218
}
219
220
export function editor(fileName, jsonPath, documentLink) {
221
  let p = new Promise((resolve) => {
222
    var util = new cmsEditor.form()
223
    var arrayBlock = []
224
    var text
225
    var json
226
227
    json = {}
228
    if(coreUtils.file.exist(jsonPath)) {
229
      json = cmsData.file.get(jsonPath, 'utf8')
230
    }
231
232
    text = cmsTemplates.template.getTemplate(fileName)
233
234
    cmsData.source.getDataList(path.dirname(documentLink), text, json)
235
      .then(() => {
236
        addSource(text, json, util)
237
238
        text = cmsData.source.removeDataList(text)
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 tpl = json.abe_meta.template.split('/')
246
        //   tpl = tpl.pop()
247
        //   json.abe_meta.cleanTemplate = tpl.replace(/\..+$/, '')
248
        // }
249
250
        if(typeof json.abe_meta !== 'undefined' && json.abe_meta !== null) {
251
          var links = json.abe_meta.link.split('/')
252
          var link = links.pop()
253
          json.abe_meta.cleanName = link.replace(/\..+$/, '')
254
          json.abe_meta.cleanFilename = links.join('/').replace(/\..+$/, '')
255
        }
256
257
        // HOOKS beforeEditorFormBlocks
258
        json = abeExtend.hooks.instance.trigger('beforeEditorFormBlocks', json)
259
260
        var blocks = orderBlock(util)
261
262
        // HOOKS afterEditorFormBlocks
263
        blocks = abeExtend.hooks.instance.trigger('afterEditorFormBlocks', blocks, json)
264
265
        abeEngine.instance.content = json
266
267
        resolve({
268
          text: text,
269
          form: blocks,
270
          json: json
271
        })
272
      }).catch(function(e) {
273
        console.error(e)
274
      })
275
  })
276
277
  return p
278
}