Passed
Push — developer ( b17be7...a57010 )
by Mariusz
19:04
created

Base::getFieldsLabelsByModule()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
c 0
b 0
f 0
dl 0
loc 10
rs 10
cc 4
nc 3
nop 1
1
<?php
2
/**
3
 * Base record collector file.
4
 *
5
 * @package App
6
 *
7
 * @copyright YetiForce S.A.
8
 * @license   YetiForce Public License 5.0 (licenses/LicenseEN.txt or yetiforce.com)
9
 * @author    Mariusz Krzaczkowski <[email protected]>
10
 * @author    Radosław Skrzypczak <[email protected]>
11
 */
12
13
namespace App\RecordCollectors;
14
15
/**
16
 * Base record collector class.
17
 */
18
class Base
19
{
20
	/** @var string Module name. */
21
	public $moduleName;
22
23
	/** @var string Record collector name. */
24
	protected $name;
25
26
	/** @var string[] Allowed modules. */
27
	public $allowedModules;
28
29
	/** @var string Icon. */
30
	public $icon;
31
32
	/** @var string Label. */
33
	public $label;
34
35
	/** @var string Additional description, visible in the modal window. */
36
	public $description;
37
38
	/** @var string Search results display type. */
39
	public $displayType;
40
41
	/** @var array Configuration field list. */
42
	public $settingsFields = [];
43
44
	/** @var string Url to Documentation API */
45
	public $docUrl;
46
47
	/** var array List of fields for the modal search window. */
48
	protected $fields = [];
49
50
	/** @var array Data from record collector source. */
51
	protected $data = [];
52
53
	/** @var array Response data. */
54
	protected $response = [];
55
56
	/** @var \App\Request Request instance. */
57
	protected $request;
58
59
	/** @var array Fields mapping for loading record data. */
60
	protected $modulesFieldsMap = [];
61
62
	/** @var array Form mapping for loading record data. */
63
	public $formFieldsToRecordMap = [];
64
65
	/**
66
	 * Constructor.
67
	 */
68
	public function __construct()
69
	{
70
		$this->name = substr(strrchr(static::class, '\\'), 1);
71
		$class = '\\Config\\Components\\RecordCollectors\\' . $this->name;
72
		if (!\class_exists($class)) {
73
			return;
74
		}
75
		$config = (new \ReflectionClass($class))->getStaticProperties();
76
		if (isset($config['allowedModules'])) {
77
			$this->allowedModules = $config['allowedModules'];
78
			unset($config['allowedModules']);
79
		}
80
		foreach ($config as $key => $value) {
81
			$this->{$key} = $value;
82
		}
83
	}
84
85
	/**
86
	 * Get record collector name.
87
	 *
88
	 * @return string
89
	 */
90
	public function getName(): string
91
	{
92
		return $this->name;
93
	}
94
95
	/**
96
	 * Set request.
97
	 *
98
	 * @param \App\Request $request
99
	 *
100
	 * @return void
101
	 */
102
	public function setRequest(\App\Request $request): void
103
	{
104
		$this->request = $request;
105
	}
106
107
	/**
108
	 * Get fields for the modal search window.
109
	 *
110
	 * @return \Vtiger_Field_Model[]
111
	 */
112
	public function getFields(): array
113
	{
114
		$fieldsModel = [];
115
		foreach ($this->fields as $fieldName => $data) {
116
			if (isset($data['picklistValuesFunction'])) {
117
				$data['picklistValues'] = $this->{$data['picklistValuesFunction']}($data);
118
			} elseif (isset($data['picklistValues']) && false !== $data['picklistModule']) {
119
				$picklistModule = $data['picklistModule'] ?? $this->moduleName;
120
				foreach ($data['picklistValues'] as $picklistKey => $value) {
121
					$data['picklistValues'][$picklistKey] = \App\Language::translate($value, $picklistModule);
122
				}
123
			}
124
			$fieldModel = \Vtiger_Field_Model::init($this->moduleName, $data, $fieldName);
125
			if (isset($this->modulesFieldsMap[$this->moduleName][$fieldName]) && $this->request->has($this->modulesFieldsMap[$this->moduleName][$fieldName])) {
126
				try {
127
					$uitypeModel = $fieldModel->getUITypeModel();
128
					$value = $this->request->getByType($this->modulesFieldsMap[$this->moduleName][$fieldName], 'Text');
129
					$uitypeModel->validate($value, true);
130
					$fieldModel->set('fieldvalue', $uitypeModel->getDBValue($value));
131
				} catch (\Throwable $th) {
132
					\App\Log::error($th->__toString(), 'RecordCollectors');
133
				}
134
			}
135
			$fieldsModel[$fieldName] = $fieldModel;
136
		}
137
		return $fieldsModel;
138
	}
139
140
	/**
141
	 * Get fields for the module name.
142
	 *
143
	 * @param string $moduleName
144
	 *
145
	 * @return string[]
146
	 */
147
	public function getFieldsModule(string $moduleName): array
148
	{
149
		return $this->modulesFieldsMap[$moduleName];
150
	}
151
152
	/**
153
	 * Check whether it is active.
154
	 *
155
	 * @return bool
156
	 */
157
	public function isActive(): bool
158
	{
159
		return \in_array($this->moduleName, $this->allowedModules);
160
	}
161
162
	/**
163
	 * Search data function.
164
	 *
165
	 * @return array
166
	 */
167
	public function search(): array
168
	{
169
		throw new \Api\Core\Exception('no search function');
170
	}
171
172
	/**
173
	 * Get params of collector.
174
	 *
175
	 * @return array
176
	 */
177
	protected function getParams(): array
178
	{
179
		if ($params = (new \App\Db\Query())->select(['params'])->from('vtiger_links')->where(['linktype' => 'EDIT_VIEW_RECORD_COLLECTOR', 'linkurl' => static::class])->scalar()) {
180
			return \App\Json::decode($params, true);
0 ignored issues
show
Bug introduced by
true of type true is incompatible with the type integer expected by parameter $objectDecodeType of App\Json::decode(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

180
			return \App\Json::decode($params, /** @scrutinizer ignore-type */ true);
Loading history...
181
		}
182
		return [];
183
	}
184
185
	/**
186
	 * Load data.
187
	 *
188
	 * @return void
189
	 */
190
	public function loadData(): void
191
	{
192
		if (empty($this->data)) {
193
			return;
194
		}
195
		$this->response['recordModel'] = $this->getRecordModel();
196
		$fieldsModel = $this->response['recordModel']->getModule()->getFields();
197
		$additional = $fieldsData = $skip = [];
198
		$rows = isset($this->data[0]) ? $this->data : [$this->data];
199
		foreach ($rows as $key => &$row) {
200
			$dataCounter[$key] = 0;
201
			if (empty($row)) {
202
				continue;
203
			}
204
			foreach ($this->formFieldsToRecordMap[$this->moduleName] as $apiKey => $fieldName) {
205
				if (empty($fieldsModel[$fieldName]) || !$fieldsModel[$fieldName]->isActiveField()) {
206
					if (isset($row[$apiKey]) && '' !== $row[$apiKey] && null !== $row[$apiKey]) {
207
						$skip[$fieldName]['data'][$key] = $row[$apiKey];
208
						if (isset($fieldsModel[$fieldName]) && empty($skip[$fieldName]['label'])) {
209
							$skip[$fieldName]['label'] = \App\Language::translate($fieldsModel[$fieldName]->getFieldLabel(), $this->moduleName);
210
						} else {
211
							$skip[$fieldName]['label'] = $fieldName;
212
						}
213
					}
214
					unset($row[$apiKey]);
215
					continue;
216
				}
217
				$value = '';
218
				if (isset($row[$apiKey])) {
219
					$value = trim($row[$apiKey]);
220
					unset($row[$apiKey]);
221
				}
222
				if ('' === $value && isset($fieldsData[$fieldName]['data'][$key])) {
223
					continue;
224
				}
225
				if ($value) {
226
					++$dataCounter[$key];
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $dataCounter seems to be defined later in this foreach loop on line 200. Are you sure it is defined here?
Loading history...
227
				}
228
				$fieldModel = $fieldsModel[$fieldName];
229
				$fieldsData[$fieldName]['label'] = \App\Language::translate($fieldModel->getFieldLabel(), $this->moduleName);
0 ignored issues
show
Deprecated Code introduced by
The function Vtiger_Field_Model::getFieldLabel() has been deprecated: 7.0 Use $this->getLabel() ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

229
				$fieldsData[$fieldName]['label'] = \App\Language::translate(/** @scrutinizer ignore-deprecated */ $fieldModel->getFieldLabel(), $this->moduleName);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
230
				$fieldsData[$fieldName]['data'][$key] = [
231
					'raw' => $value,
232
					'edit' => $fieldModel->getEditViewDisplayValue($value),
233
					'display' => $fieldModel->getDisplayValue($value, false, false, false, 40),
234
				];
235
			}
236
			foreach ($row as $name => $value) {
237
				if ('' !== $value && null !== $value) {
238
					$additional[$name][$key] = $value;
239
				}
240
			}
241
		}
242
		$this->response['fields'] = $fieldsData;
243
		$this->response['skip'] = $skip;
244
		$this->response['keys'] = array_keys($rows);
245
		$this->response['additional'] = $additional;
246
		$this->response['dataCounter'] = $dataCounter;
247
	}
248
249
	/**
250
	 * Get fields labels for the module name.
251
	 *
252
	 * @param string $moduleName
253
	 *
254
	 * @return string[]
255
	 */
256
	public function getFieldsLabelsByModule(string $moduleName): array
257
	{
258
		$fieldsModels = \Vtiger_Module_Model::getInstance($moduleName)->getFields();
259
		$labels = [];
260
		foreach ($this->formFieldsToRecordMap[$moduleName] as $fieldName) {
261
			if (isset($fieldsModels[$fieldName]) && $fieldsModels[$fieldName]->isActiveField()) {
262
				$labels[$fieldName] = $fieldsModels[$fieldName]->getFullLabelTranslation();
263
			}
264
		}
265
		return $labels;
266
	}
267
268
	/**
269
	 * Get record model from request data.
270
	 *
271
	 * @return \Vtiger_Record_Model
272
	 */
273
	protected function getRecordModel(): \Vtiger_Record_Model
274
	{
275
		$moduleName = $this->request->getModule();
276
		if ($recordId = $this->request->getInteger('record')) {
277
			$recordModel = \Vtiger_Record_Model::getInstanceById($recordId, $moduleName);
278
		} else {
279
			$recordModel = \Vtiger_Record_Model::getCleanInstance($moduleName);
280
		}
281
		$formData = $this->request->getRaw('form');
282
		$request = new \App\Request($formData, false);
283
		$fieldModelList = $recordModel->getModule()->getFields();
284
		foreach ($fieldModelList as $fieldName => $fieldModel) {
285
			if (!$fieldModel->isWritable()) {
286
				continue;
287
			}
288
			if (isset($formData[$fieldName])) {
289
				$fieldModel->getUITypeModel()->setValueFromRequest($request, $recordModel);
290
			} else {
291
				$defaultValue = $fieldModel->getDefaultFieldValue();
292
				if ('' !== $defaultValue) {
293
					$recordModel->set($fieldName, $defaultValue);
294
				}
295
			}
296
		}
297
		return $recordModel;
298
	}
299
}
300