Completed
Push — master ( a18731...e2e070 )
by
unknown
99:54 queued 47:45
created

findExistingCustomer()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 25
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 1
Metric Value
dl 0
loc 25
rs 8.439
c 3
b 1
f 1
cc 5
eloc 13
nc 5
nop 1
1
<?php
2
3
namespace OroCRM\Bundle\MagentoBundle\ImportExport\Strategy;
4
5
use OroCRM\Bundle\MagentoBundle\Entity\Customer;
6
use OroCRM\Bundle\MagentoBundle\Entity\MagentoSoapTransport;
7
use OroCRM\Bundle\MagentoBundle\Entity\Order;
8
use OroCRM\Bundle\MagentoBundle\ImportExport\Converter\GuestCustomerDataConverter;
9
use OroCRM\Bundle\MagentoBundle\Provider\Reader\ContextCartReader;
10
use OroCRM\Bundle\MagentoBundle\Provider\Reader\ContextCustomerReader;
11
12
class OrderWithExistingCustomerStrategy extends OrderStrategy
13
{
14
    const CONTEXT_ORDER_POST_PROCESS = 'postProcessOrders';
15
16
    /**
17
     * @param Order $importingOrder
18
     *
19
     * {@inheritdoc}
20
     */
21 View Code Duplication
    public function process($importingOrder)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
22
    {
23
        if (!$this->isProcessingAllowed($importingOrder)) {
24
            $this->appendDataToContext(self::CONTEXT_ORDER_POST_PROCESS, $this->context->getValue('itemData'));
25
26
            return null;
27
        }
28
29
        return parent::process($importingOrder);
30
    }
31
32
    /**
33
     * @param Order $order
34
     * @return bool
35
     */
36
    protected function isProcessingAllowed(Order $order)
37
    {
38
        $isProcessingAllowed = true;
39
        $customer = $this->findExistingCustomer($order);
40
        $customerOriginId = $order->getCustomer()->getOriginId();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Oro\Bundle\BusinessEntit...undle\Entity\BasePerson as the method getOriginId() does only exist in the following sub-classes of Oro\Bundle\BusinessEntit...undle\Entity\BasePerson: OroCRM\Bundle\MagentoBundle\Entity\Customer, OroCRM\Bundle\MagentoBun...s\Entity\ExtendCustomer. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
41
        if (!$customer && $customerOriginId) {
42
            $this->appendDataToContext(ContextCustomerReader::CONTEXT_POST_PROCESS_CUSTOMERS, $customerOriginId);
43
44
            $isProcessingAllowed = false;
45
        }
46
47
        // Do not try to load cart if bridge does not installed
48
        /** @var MagentoSoapTransport $transport */
49
        $channel = $this->databaseHelper->findOneByIdentity($order->getChannel());
50
        $transport = $channel->getTransport();
51
        if ($transport->getIsExtensionInstalled()) {
52
            $cart = $this->findExistingEntity($order->getCart());
0 ignored issues
show
Bug introduced by
It seems like $order->getCart() can be null; however, findExistingEntity() 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...
53
            $cartOriginId = $order->getCart()->getOriginId();
54
            if (!$cart && $cartOriginId) {
55
                $this->appendDataToContext(ContextCartReader::CONTEXT_POST_PROCESS_CARTS, $cartOriginId);
56
57
                $isProcessingAllowed = false;
58
            }
59
        }
60
61
        if (!$customer && $order->getIsGuest() && $transport->getGuestCustomerSync()) {
62
            $this->appendDataToContext(
63
                'postProcessGuestCustomers',
64
                GuestCustomerDataConverter::extractCustomersValues((array)$this->context->getValue('itemData'))
65
            );
66
67
            $isProcessingAllowed = false;
68
        }
69
70
        return $isProcessingAllowed;
71
    }
72
73
    /**
74
     * Get existing registered customer or existing guest customer
75
     *
76
     * @param Order $order
77
     * @return null|Customer
78
     */
79
    protected function findExistingCustomer(Order $order)
80
    {
81
        $customer = $order->getCustomer();
82
83
        if ($customer instanceof Customer) {
84
            // Find from existing registered customers
85
            /** @var Customer|null $existingEntity */
86
            $existingEntity = null;
87
            if ($customer->getId() || $customer->getOriginId()) {
88
                $existingEntity = parent::findExistingEntity($customer);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (findExistingEntity() instead of findExistingCustomer()). Are you sure this is correct? If so, you might want to change this to $this->findExistingEntity().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
89
            }
90
91
            if (!$existingEntity) {
92
                $searchContext = $this->getSearchContext($order);
93
                $existingEntity = $this->databaseHelper->findOneBy(
94
                    'OroCRM\Bundle\MagentoBundle\Entity\Customer',
95
                    $searchContext
96
                );
97
            }
98
99
            return $existingEntity;
100
        }
101
102
        return null;
103
    }
104
105
    /**
106
     * Get search context for Guest customer by email, channel and website if exists
107
     *
108
     * @param Order $order
109
     * @return array
110
     */
111 View Code Duplication
    protected function getSearchContext(Order $order)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
112
    {
113
        $customer = $order->getCustomer();
114
        $searchContext = [
115
            'email' => $order->getCustomerEmail(),
116
            'channel' => $customer->getChannel()
117
        ];
118
119
        if ($customer->getWebsite()) {
120
            $website = $this->databaseHelper->findOneBy(
121
                'OroCRM\Bundle\MagentoBundle\Entity\Website',
122
                [
123
                    'originId' => $customer->getWebsite()->getOriginId(),
124
                    'channel' => $customer->getChannel()
125
                ]
126
            );
127
            if ($website) {
128
                $searchContext['website'] = $website;
129
            }
130
        }
131
132
        return $searchContext;
133
    }
134
135
    /**
136
     * Get existing entity
137
     * As guest customer entity not exist in Magento as separate entity and saved in order
138
     * find guest by customer email
139
     *
140
     * @param object $entity
141
     * @param array $searchContext
142
     * @return null|object
143
     */
144
    protected function findExistingEntity($entity, array $searchContext = [])
145
    {
146
        if ($entity instanceof Customer && (!$entity->getOriginId() && $this->existingEntity)) {
147
            return $this->findExistingCustomer($this->existingEntity);
148
        }
149
150
        return parent::findExistingEntity($entity, $searchContext);
151
    }
152
}
153