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

BeanHelper::updateZCRMRecordToBean()   F

Complexity

Conditions 31
Paths 2240

Size

Total Lines 63

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 63
rs 0
c 0
b 0
f 0
nc 2240
cc 31
nop 3

How to fix   Long Method    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
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
}