Completed
Push — 2.2.3 ( 5f6c22 )
by
unknown
01:18
created

BeanHelper   C

Complexity

Total Complexity 54

Size/Duplication

Total Lines 176
Duplicated Lines 17.05 %

Coupling/Cohesion

Components 0
Dependencies 9

Importance

Changes 0
Metric Value
wmc 54
lcom 0
cbo 9
dl 30
loc 176
rs 6.4799
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
C createOrUpdateBeanToZCRMRecord() 0 60 16
F updateZCRMRecordToBean() 30 101 38

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like BeanHelper 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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

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.

While breaking up the class, it is a good idea to analyze how other classes use BeanHelper, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Wabel\Zoho\CRM\Helpers;
4
5
6
7
use Wabel\Zoho\CRM\AbstractZohoDao;
8
use Wabel\Zoho\CRM\Exceptions\ZohoCRMORMException;
9
use Wabel\Zoho\CRM\Service\EntitiesGeneratorService;
10
use Wabel\Zoho\CRM\ZohoBeanInterface;
11
use zcrmsdk\crm\crud\ZCRMRecord;
12
use zcrmsdk\crm\setup\users\ZCRMUser;
13
14
class BeanHelper
15
{
16
17
    /**
18
     * @param AbstractZohoDao   $dao
19
     * @param ZohoBeanInterface $bean
20
     */
21
    public static function createOrUpdateBeanToZCRMRecord(AbstractZohoDao $dao, ZohoBeanInterface $bean)
22
    {
23
24
        $record = ZCRMRecord::getInstance($dao->getModule(), $bean->getZohoId());
25
        $bean->setZCRMRecord($record);
26
        foreach ($dao->getFields() as $field){
27
            if(($field->isSystem() && $field->getApiName() !== 'Owner') || in_array($field->getName(), EntitiesGeneratorService::$defaultORMSystemFields) || !$bean->isDirty($field->getName())) {
28
                continue;
29
            }
30
            $getter = $field->getGetter();
31
            switch ($field->getType()) {
32
                case 'date':
33
                    /**
34
                     * @var $date \DateTimeInterface
35
                     */
36
                    $date = $bean->{$getter}();
37
                    if($date) {
38
                        $bean->getZCRMRecord()->setFieldValue($field->getApiName(), $date->format('Y-m-d'));
39
                    }
40
                    break;
41
                case 'datetime':
42
                    /**
43
                     * @var $date \DateTimeInterface
44
                     */
45
                    $date = $bean->{$getter}();
46
                    if($date) {
47
                        $date->setTimezone(new \DateTimeZone($dao->getZohoClient()->getTimezone()));
48
                        $bean->getZCRMRecord()->setFieldValue($field->getApiName(), $date->format(\DateTime::ATOM));
49
                    }
50
                    break;
51
                case 'lookup':
52
                    /**
53
                     * @var $ZCRMRecord ZCRMRecord
54
                     */
55
                    $ZCRMRecord = ZCRMRecord::getInstance($field->getLookupModuleName(), $bean->{$getter}());
56
                    $bean->getZCRMRecord()->setFieldValue($field->getApiName(), $ZCRMRecord);
0 ignored issues
show
Documentation introduced by
$ZCRMRecord is of type object<zcrmsdk\crm\crud\ZCRMRecord>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
57
                    break;
58
                case 'ownerlookup':
59
                    if($bean->{$getter}()) {
60
                        $bean->getZCRMRecord()->setOwner(ZCRMUser::getInstance($bean->{$getter}(), $bean->getOwner_OwnerName()));
61
                    }
62
                    break;
63
                case 'multiselectpicklist':
64
                    if($bean->{$getter}()) {
65
                        $bean->getZCRMRecord()->setFieldValue($field->getApiName(), $bean->{$getter}());
66
                    } else{
67
                        $bean->getZCRMRecord()->setFieldValue($field->getApiName(), null);
68
                    }
69
                    break;
70
                default:
71
                    $bean->getZCRMRecord()->setFieldValue($field->getApiName(), $bean->{$getter}());
72
                    break;
73
            }
74
        }
75
76
        // Add support for fields that can't be managed with ORM
77
        foreach ($dao->getUnamanagedFields() as $field => $value) {
78
            $bean->getZCRMRecord()->setFieldValue($field, $value);
79
        }
80
    }
81
82
    /**
83
     * @param  AbstractZohoDao   $dao
84
     * @param  ZohoBeanInterface $bean
85
     * @param  ZCRMRecord       $record
86
     * @throws ZohoCRMORMException
87
     */
88
    public static function updateZCRMRecordToBean(AbstractZohoDao $dao, ZohoBeanInterface $bean, ZCRMRecord $record)
89
    {
90
        $bean->setZCRMRecord($record);
91
        $id = $record->getEntityId();
92
        $bean->setZohoId($id);
93
        $bean->setCreatedTime(!empty($record->getCreatedTime()) ? \DateTimeImmutable::createFromFormat(\DateTime::ATOM, $record->getCreatedTime()) : null);
0 ignored issues
show
Bug introduced by
It seems like !empty($record->getCreat...etCreatedTime()) : null can be null; however, setCreatedTime() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
94
        $bean->setModifiedTime(!empty($record->getModifiedTime()) ? \DateTimeImmutable::createFromFormat(\DateTime::ATOM, $record->getModifiedTime()) : null);
0 ignored issues
show
Bug introduced by
It seems like !empty($record->getModif...tModifiedTime()) : null can be null; however, setModifiedTime() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
95
        $bean->setLastActivityTime(!empty($record->getLastActivityTime()) ? \DateTimeImmutable::createFromFormat(\DateTime::ATOM, $record->getLastActivityTime()) : null);
0 ignored issues
show
Bug introduced by
It seems like !empty($record->getLastA...tActivityTime()) : null can be null; however, setLastActivityTime() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
96
97
        if($record->getOwner()) { $bean->setOwner_OwnerID($record->getOwner()->getId());
98
        }
99
        if($record->getOwner()) { $bean->setOwner_OwnerName($record->getOwner()->getName());
100
        }
101
        if($record->getModifiedBy()) { $bean->setModifiedBy_OwnerID($record->getModifiedBy()->getId());
102
        }
103
        if($record->getModifiedBy()) { $bean->setModifiedBy_OwnerName($record->getModifiedBy()->getName());
104
        }
105
        if($record->getCreatedBy()) { $bean->setCreatedBy_OwnerID($record->getCreatedBy()->getId());
106
        }
107
        if($record->getCreatedBy()) { $bean->setCreatedBy_OwnerName($record->getCreatedBy()->getName());
108
        }
109
110
        $fields = $dao->getFields();
111
        foreach ($fields as $field) {
112
            if(!$field->isSystem() && array_key_exists($field->getApiName(), $record->getData())) {
113
                $value = $record->getFieldValue($field->getApiName());
114
                $setter = $field->getSetter();
115
                switch ($field->getType()) {
116
                    case 'date':
117
                        if ($value && $dateObj = \DateTime::createFromFormat('M/d/Y', $value)) {
118
                            $value = $dateObj;
119
                        } elseif ($value && $dateObj = \DateTime::createFromFormat('Y-m-d', $value)) {
120
                            $value = $dateObj;
121
                        } elseif ($value && $dateObj = \DateTime::createFromFormat(\DateTime::ATOM, $value)) {
122
                            $value = $dateObj;
123
                        } elseif($value !== null) {
124
                            throw new ZohoCRMORMException('Unable to convert the Date field "' . $field->getName() . "\" into a DateTime PHP object from the the record $id of the module " . $dao->getModule() . '.');
125
                        }
126
                        break;
127
                    case 'datetime':
128
                        $value = \DateTime::createFromFormat(\DateTime::ATOM, $value);
129
                        break;
130
                    case 'userlookup':
131
                    case 'lookup':
132 View Code Duplication
                        if ($value) {
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...
133
                            if (is_a($value, 'zcrmsdk\crm\crud\ZCRMRecord')) {
134
                                /**
135
                                 * @var $ZCRMRecord ZCRMRecord
136
                                 */
137
                                $ZCRMRecord = $value;
138
                                if (UtilsHelper::endsWith($field->getName(), 'ID')) {
139
                                    $value = $ZCRMRecord->getEntityId();
140
                                } else {
141
                                    $value = $ZCRMRecord->getLookupLabel();
142
                                }
143
                            }
144
                        } else {
145
                            $value = null;
146
                        }
147
                        break;
148
149
                    case 'ownerlookup':
150 View Code Duplication
                        if ($value) {
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...
151
                            if (is_a($value, 'zcrmsdk\crm\setup\users\ZCRMUser')) {
152
                                /**
153
                                 * @var $ZCRMUser ZCRMUser
154
                                 */
155
                                $ZCRMUser = $value;
156
                                if (UtilsHelper::endsWith($field->getName(), 'ID')) {
157
                                    $value = $ZCRMUser->getId();
158
                                } else {
159
                                    $value = $ZCRMUser->getFullName();
160
                                }
161
                            }
162
                        } else {
163
                            $value = null;
164
                        }
165
                        break;
166
                    default:
167
                        break;
168
                }
169
                if (($value === false || $value === null) && in_array($field->getType(), ['date', 'datetime', ''])) {
170
                    $value = null;
171
                }
172
173
                $bean->$setter($value);
174
                $bean->setDirty($field->getName(), false);
175
            }
176
        }
177
178
        if (method_exists($bean, 'setTag')) {
179
            $tags = [];
180
            if (count($record->getTags())) {
181
                foreach ($record->getTags() as $tag) {
182
                    $tags[] = $tag->getId();
183
                }
184
            }
185
            $bean->setTag(count($tags) ? implode(';', $tags) : null);
0 ignored issues
show
Bug introduced by
The method setTag() does not seem to exist on object<Wabel\Zoho\CRM\ZohoBeanInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
186
        }
187
188
    }
189
}
190