Completed
Pull Request — 2.0 (#37)
by Raphaël
10:32
created

BeanHelper   B

Complexity

Total Complexity 44

Size/Duplication

Total Lines 136
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 7

Importance

Changes 0
Metric Value
wmc 44
lcom 0
cbo 7
dl 0
loc 136
rs 8.8798
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
C createOrUpdateBeanToZCRMRecord() 0 58 13
F updateZCRMRecordToBean() 0 63 31

How to fix   Complexity   

Complex Class

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
12
class BeanHelper
13
{
14
15
    /**
16
     * @param AbstractZohoDao $dao
17
     * @param ZohoBeanInterface $bean
18
     */
19
    public static function createOrUpdateBeanToZCRMRecord(AbstractZohoDao $dao, ZohoBeanInterface $bean){
20
21
        $record = \ZCRMRecord::getInstance($dao->getModule(), $bean->getZohoId());
0 ignored issues
show
Bug introduced by
The method getModule() cannot be called from this context as it is declared protected in class Wabel\Zoho\CRM\AbstractZohoDao.

This check looks for access to methods that are not accessible from the current context.

If you need to make a method accessible to another context you can raise its visibility level in the defining class.

Loading history...
22
        $bean->setZCRMRecord($record);
23
        foreach ($dao->getFields() as $field){
24
            if(in_array($field->getName(), EntitiesGeneratorService::$defaultORMSystemFields) || !$bean->isDirty($field->getName())){
25
                continue;
26
            }
27
            $getter = $field->getGetter();
28
            switch ($field->getType()) {
29
                case 'date':
30
                    /**
31
                     * @var $date \DateTimeInterface
32
                     */
33
                    $date = $bean->{$getter}();
34
                    if($date){
35
                        $record->setFieldValue($field->getApiName(), $date->format('Y-m-d'));
36
                    }
37
                    break;
38
                case 'datetime':
39
                /**
40
                 * @var $date \DateTimeInterface
41
                 */
42
                    $date = $bean->{$getter}();
43
                    if($date){
44
                        $date->setTimezone(new \DateTimeZone($dao->getZohoClient()->getTimezone()));
0 ignored issues
show
Bug introduced by
The method getTimezone() does not seem to exist on object<Wabel\Zoho\CRM\ZohoClient>.

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...
45
                        $record->setFieldValue($field->getApiName(), $date->format(\DateTime::ATOM));
46
                    }
47
                    break;
48
                case 'lookup':
49
                    /**
50
                     * @var $ZCRMRecord \ZCRMRecord
51
                     */
52
                    $ZCRMRecord = \ZCRMRecord::getInstance($field->getLookupModuleName(), $bean->{$getter}());
53
                    $record->setFieldValue($field->getApiName(), $ZCRMRecord);
0 ignored issues
show
Documentation introduced by
$ZCRMRecord is of type object<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...
54
                    break;
55
                case 'ownerlookup':
56
                    $record->setFieldValue($field->getApiName(), \ZCRMUser::getInstance($bean->{$getter}(), null));
0 ignored issues
show
Documentation introduced by
\ZCRMUser::getInstance($bean->{$getter}(), null) is of type object<ZCRMUser>, 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 'multiselectpicklist':
59
                    if($bean->{$getter}()){
60
                        $record->setFieldValue($field->getApiName(), $bean->{$getter}());
61
                    } else{
62
                        $record->setFieldValue($field->getApiName(),null);
63
                    }
64
                    break;
65
                default:
66
                    $record->setFieldValue($field->getApiName(), $bean->{$getter}());
67
                    break;
68
            }
69
        }
70
        if(!$record->getOwner()){
71
            $record->setOwner(\ZCRMUser::getInstance($bean->getOwnerOwnerID(),$bean->getOwnerOwnerName()));
72
        } else{
73
            $record->getOwner()->setId($bean->getOwnerOwnerID());
74
            $record->getOwner()->setName($bean->getOwnerOwnerName());
75
        }
76
    }
77
78
    /**
79
     * @param AbstractZohoDao $dao
80
     * @param ZohoBeanInterface $bean
81
     * @param \ZCRMRecord $record
82
     * @throws ZohoCRMORMException
83
     */
84
    public static function updateZCRMRecordToBean(AbstractZohoDao $dao, ZohoBeanInterface $bean, \ZCRMRecord $record){
85
        $bean->setZCRMRecord($record);
86
        $id = $record->getEntityId();
87
        $bean->setZohoId($id);
88
        $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...
89
        $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...
90
        $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...
91
92
        if($record->getOwner()) $bean->setOwnerOwnerID($record->getOwner()->getId());
93
        if($record->getOwner()) $bean->setOwnerOwnerName($record->getOwner()->getName());
94
        if($record->getModifiedBy()) $bean->setModifiedByOwnerID($record->getModifiedBy()->getId());
95
        if($record->getModifiedBy()) $bean->setModifiedByOwnerName($record->getModifiedBy()->getName());
96
        if($record->getCreatedBy()) $bean->setCreatedByOwnerID($record->getCreatedBy()->getId());
97
        if($record->getCreatedBy()) $bean->setCreatedByOwnerName($record->getCreatedBy()->getName());
98
99
        $fields = $dao->getFields();
100
        foreach ($fields as $field) {
101
            if(!$field->isSystem() && array_key_exists($field->getApiName(), $record->getData())){
102
                $value = $record->getFieldValue($field->getApiName());
103
                $setter = $field->getSetter();
104
                switch ($field->getType()) {
105
                    case 'date':
106
                        if ($value && $dateObj = \DateTime::createFromFormat('M/d/Y', $value)) {
107
                            $value = $dateObj;
108
                        } elseif ($value && $dateObj = \DateTime::createFromFormat('Y-m-d', $value)) {
109
                            $value = $dateObj;
110
                        } elseif ($value && $dateObj = \DateTime::createFromFormat(\DateTime::ATOM, $value)) {
111
                            $value = $dateObj;
112
                        } elseif($value !== null) {
113
                            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() . '.');
0 ignored issues
show
Bug introduced by
The method getModule() cannot be called from this context as it is declared protected in class Wabel\Zoho\CRM\AbstractZohoDao.

This check looks for access to methods that are not accessible from the current context.

If you need to make a method accessible to another context you can raise its visibility level in the defining class.

Loading history...
114
                        }
115
                        break;
116
                    case 'datetime':
117
                        $value = \DateTime::createFromFormat(\DateTime::ATOM, $value);
118
                        break;
119
                    case 'userlookup':
120
                    case 'lookup':
121
                        /**
122
                         * @var $ZCRMRecord \ZCRMRecord
123
                         */
124
                        $ZCRMRecord = $value;
125
                        $value = $ZCRMRecord? (is_a($ZCRMRecord, 'ZCRMRecord') ? $ZCRMRecord->getEntityId() : $ZCRMRecord):null;
126
                        break;
127
128
                    case 'ownerlookup':
129
                        /**
130
                         * @var $ZCRMUser \ZCRMUser
131
                         */
132
                        $ZCRMUser = $value;
133
                        $value = $ZCRMUser?$ZCRMUser->getId():null;
134
                        break;
135
                    default:
136
                        break;
137
                }
138
                if (($value === false || $value === null) && in_array($field->getType(), ['date', 'datetime', ''])) {
139
                    $value = null;
140
                }
141
                $bean->$setter($value);
142
                $bean->setDirty($field->getName(), false);
143
            }
144
        }
145
146
    }
147
}