Passed
Push — developer ( 2e37c5...e39102 )
by Radosław
34:00 queued 15:54
created

VTCreateEntityTask::doTask()   D

Complexity

Conditions 21
Paths 37

Size

Total Lines 42
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 462

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 30
c 1
b 0
f 0
dl 0
loc 42
ccs 0
cts 33
cp 0
rs 4.1666
cc 21
nc 37
nop 1
crap 462

How to fix   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
 * The contents of this file are subject to the vtiger CRM Public License Version 1.0
4
 * ("License"); You may not use this file except in compliance with the License
5
 * The Original Code is:  vtiger CRM Open Source
6
 * The Initial Developer of the Original Code is vtiger.
7
 * Portions created by vtiger are Copyright (C) vtiger.
8
 * All Rights Reserved.
9
 * Contributor(s): YetiForce S.A.
10
 * ********************************************************************************** */
11
require_once 'modules/com_vtiger_workflow/VTWorkflowUtils.php';
12
13
class VTCreateEntityTask extends VTTask
14
{
15
	public $executeImmediately = true;
16
17
	public function getFieldNames()
18
	{
19
		return ['entity_type', 'reference_field', 'field_value_mapping', 'mappingPanel', 'verifyIfExists', 'relationId'];
20
	}
21
22
	/**
23
	 * Execute task.
24
	 *
25
	 * @param Vtiger_Record_Model $recordModel
26
	 */
27
	public function doTask($recordModel)
28
	{
29
		$recordId = $recordModel->getId();
30
		$entityType = $this->entity_type;
0 ignored issues
show
Bug Best Practice introduced by
The property entity_type does not exist on VTCreateEntityTask. Did you maybe forget to declare it?
Loading history...
31
		if (!\App\Module::isModuleActive($entityType)) {
32
			return;
33
		}
34
		$fieldValueMapping = [];
35
		if (!empty($this->field_value_mapping)) {
36
			$fieldValueMapping = \App\Json::decode($this->field_value_mapping);
0 ignored issues
show
Bug Best Practice introduced by
The property field_value_mapping does not exist on VTCreateEntityTask. Did you maybe forget to declare it?
Loading history...
37
		}
38
		if (!$this->mappingPanel && !empty($entityType) && !empty($fieldValueMapping) && \count($fieldValueMapping) > 0) {
0 ignored issues
show
Bug Best Practice introduced by
The property mappingPanel does not exist on VTCreateEntityTask. Did you maybe forget to declare it?
Loading history...
39
			$newRecordModel = $this->setMappingFields($fieldValueMapping, $recordModel);
40
			if ($this->reference_field && $newRecordModel->getField($this->reference_field)) {
0 ignored issues
show
Bug Best Practice introduced by
The property reference_field does not exist on VTCreateEntityTask. Did you maybe forget to declare it?
Loading history...
41
				$newRecordModel->set($this->reference_field, $recordId);
42
			}
43
			// To handle cyclic process
44
			$newRecordModel->setHandlerExceptions(['disableHandlerClasses' => ['Vtiger_Workflow_Handler']]);
45
			$newRecordModel->save();
46
47
			$relationModel = \Vtiger_Relation_Model::getInstance($recordModel->getModule(), $newRecordModel->getModule(), $this->relationId);
0 ignored issues
show
Bug Best Practice introduced by
The property relationId does not exist on VTCreateEntityTask. Did you maybe forget to declare it?
Loading history...
48
			if ($relationModel) {
0 ignored issues
show
introduced by
$relationModel is of type Vtiger_Relation_Model, thus it always evaluated to true.
Loading history...
49
				$relationModel->addRelation($recordModel->getId(), $newRecordModel->getId());
50
			}
51
		} elseif ($this->mappingPanel && $entityType) {
52
			if (!empty($this->verifyIfExists) && ($relationListView = Vtiger_RelationListView_Model::getInstance($recordModel, $entityType, $this->relationId)) && (int) $relationListView->getRelatedEntriesCount() > 0) {
53
				return true;
54
			}
55
			$saveContinue = true;
56
			$newRecordModel = Vtiger_Record_Model::getCleanInstance($entityType);
57
			$newRecordModel->setRecordFieldValues($recordModel);
58
			$mandatoryFields = $newRecordModel->getModule()->getMandatoryFieldModels();
59
			if (!empty($fieldValueMapping) && \is_array($fieldValueMapping)) {
60
				$newRecordModel = $this->setMappingFields($fieldValueMapping, $recordModel, $newRecordModel);
61
			}
62
			foreach ($mandatoryFields as $field) {
63
				if ('' === $newRecordModel->get($field->getName()) || null === $newRecordModel->get($field->getName())) {
64
					$saveContinue = false;
65
				}
66
			}
67
			if ($saveContinue) {
68
				$newRecordModel->save();
69
			}
70
		}
71
	}
72
73
	private function setMappingFields(array $fieldValueMapping, Vtiger_Record_Model $recordModel, ?Vtiger_Record_Model $newRecordModel = null)
74
	{
75
		$entityType = $this->entity_type;
0 ignored issues
show
Bug Best Practice introduced by
The property entity_type does not exist on VTCreateEntityTask. Did you maybe forget to declare it?
Loading history...
76
		if (!$newRecordModel) {
77
			$newRecordModel = Vtiger_Record_Model::getCleanInstance($entityType);
78
		}
79
		$ownerFields = array_keys($newRecordModel->getModule()->getFieldsByType('owner'));
80
81
		foreach ($fieldValueMapping as $fieldInfo) {
82
			$fieldName = $fieldInfo['fieldname'];
83
			$destinyModuleName = $this->getDestinyModuleName($fieldInfo['modulename']);
84
			$sourceModuleName = $destinyModuleName ?? $fieldInfo['modulename'];
85
			$fieldValueType = $fieldInfo['valuetype'];
86
			$fieldValue = trim($fieldInfo['value']);
87
			if ('fieldname' === $fieldValueType) {
88
				if ($this->relationId) {
0 ignored issues
show
Bug Best Practice introduced by
The property relationId does not exist on VTCreateEntityTask. Did you maybe forget to declare it?
Loading history...
89
					$fieldValue = $destinyModuleName ? $newRecordModel->get($fieldValue) : $recordModel->get($fieldValue);
90
				} else {
91
					$fieldValue = $sourceModuleName === $entityType ? $newRecordModel->get($fieldValue) : $recordModel->get($fieldValue);
92
				}
93
			} elseif ('expression' === $fieldValueType) {
94
				require_once 'modules/com_vtiger_workflow/expression_engine/include.php';
95
96
				$parser = new VTExpressionParser(new VTExpressionSpaceFilter(new VTExpressionTokenizer($fieldValue)));
97
				$expression = $parser->expression();
98
				$exprEvaluater = new VTFieldExpressionEvaluater($expression);
99
				if ($sourceModuleName === $entityType) {
100
					$fieldValue = $exprEvaluater->evaluate($newRecordModel);
101
				} else {
102
					$fieldValue = $exprEvaluater->evaluate($recordModel);
103
				}
104
			} elseif (preg_match('/([^:]+):boolean$/', $fieldValue, $match)) {
105
				$fieldValue = $match[1];
106
				if ('true' == $fieldValue) {
107
					$fieldValue = '1';
108
				} else {
109
					$fieldValue = '0';
110
				}
111
			} elseif (!\in_array($fieldName, $ownerFields)) {
112
				$fieldValue = $newRecordModel->getField($fieldName)->getUITypeModel()->getDBValue($fieldValue);
113
			}
114
			if (\in_array($fieldName, $ownerFields)) {
115
				if ('triggerUser' === $fieldValue) {
116
					$fieldValue = $recordModel->executeUser;
0 ignored issues
show
Bug introduced by
The property executeUser does not seem to exist on Vtiger_Record_Model.
Loading history...
117
				} elseif (!is_numeric($fieldValue)) {
118
					$userId = App\User::getUserIdByName($fieldValue);
119
					$groupId = \App\Fields\Owner::getGroupId($fieldValue);
120
					if (!$userId && !$groupId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $userId of type integer|null is loosely compared to false; this is ambiguous if the integer can be 0. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
121
						$fieldValue = $recordModel->get($fieldName);
122
					} else {
123
						$fieldValue = (!$userId) ? $groupId : $userId;
124
					}
125
				}
126
			}
127
			$newRecordModel->set($fieldName, $fieldValue);
128
		}
129
		return $newRecordModel;
130
	}
131
132
	/**
133
	 * Get destiny module name.
134
	 *
135
	 * @param string $destinyModuleName
136
	 *
137
	 * @return string|null
138
	 */
139
	private function getDestinyModuleName(string $destinyModuleName): ?string
140
	{
141
		$moduleName = null;
142
		if (0 === strpos($destinyModuleName, 'destinyModule::')) {
143
			$moduleName = explode('::', $destinyModuleName)[1];
144
		}
145
		return $moduleName;
146
	}
147
}
148