Completed
Push — 1.9 ( 5c3e2e...1529fd )
by
unknown
60:20
created

CartStrategy::updateCartItems()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 9
rs 9.6666
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
3
namespace OroCRM\Bundle\MagentoBundle\ImportExport\Strategy;
4
5
use Doctrine\Common\Collections\ArrayCollection;
6
7
use OroCRM\Bundle\MagentoBundle\Entity\Cart;
8
use OroCRM\Bundle\MagentoBundle\Entity\CartAddress;
9
use OroCRM\Bundle\MagentoBundle\Entity\CartStatus;
10
11
class CartStrategy extends AbstractImportStrategy
12
{
13
    /**
14
     * @var Cart
15
     */
16
    protected $existingEntity;
17
18
    /**
19
     * @var array
20
     */
21
    protected $existingCartItems;
22
23
    /**
24
     * @param Cart $entity
25
     *
26
     * {@inheritdoc}
27
     */
28
    protected function beforeProcessEntity($entity)
29
    {
30
        $this->existingEntity = $this->databaseHelper->findOneByIdentity($entity);
31
        if ($this->existingEntity) {
32
            $this->existingCartItems = $this->existingEntity->getCartItems()->toArray();
33
        } else {
34
            $this->existingEntity = $entity;
35
        }
36
37
        return parent::beforeProcessEntity($entity);
38
    }
39
40
    /**
41
     * @param Cart $entity
42
     *
43
     * {@inheritdoc}
44
     */
45
    protected function afterProcessEntity($entity)
46
    {
47
        if ($this->existingEntity->getStatus()->getName() === CartStatus::STATUS_OPEN) {
48
            $this->updateRemovedCartItems($entity);
49
        }
50
51
        if (!$this->hasContactInfo($entity)) {
52
            return null;
53
        }
54
55
        $this
56
            ->updateCustomer($entity)
57
            ->updateAddresses($entity)
58
            ->updateCartItems($entity)
59
            ->updateCartStatus($entity);
60
61
        $now = new \DateTime('now', new \DateTimeZone('UTC'));
62
        if (!$entity->getImportedAt()) {
63
            $entity->setImportedAt($now);
64
        }
65
        $entity->setSyncedAt($now);
66
67
        $this->existingEntity = null;
68
        $this->existingCartItems = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $existingCartItems.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
69
70
        return parent::afterProcessEntity($entity);
71
    }
72
73
    /**
74
     * Update removed cart items - set `removed` field to true if cart item was removed from a cart
75
     *
76
     * @param Cart $entity
77
     */
78
    protected function updateRemovedCartItems(Cart $entity)
79
    {
80
        if ((int)$entity->getItemsQty() === 0) {
81 View Code Duplication
            foreach ($entity->getCartItems() as $cartItem) {
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...
82
                if (!$cartItem->isRemoved()) {
83
                    $cartItem->setUpdatedAt(new \DateTime('now'), new \DateTimeZone('UTC'));
84
                    $cartItem->setRemoved(true);
85
                }
86
            }
87
        } elseif ($this->existingCartItems) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->existingCartItems of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
88
            $existingCartItems = new ArrayCollection($this->existingCartItems);
89
            $newCartItems = $entity->getCartItems();
90
91 View Code Duplication
            foreach ($existingCartItems as $existingCartItem) {
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...
92
                if (!$newCartItems->contains($existingCartItem)) {
93
                    if (!$existingCartItem->isRemoved()) {
94
                        $existingCartItem->setUpdatedAt(new \DateTime('now'), new \DateTimeZone('UTC'));
95
                        $existingCartItem->setRemoved(true);
96
                    }
97
                }
98
            }
99
        }
100
    }
101
102
    /**
103
     * Update Customer email
104
     *
105
     * @param Cart $cart
106
     *
107
     * @return CartStrategy
108
     */
109
    protected function updateCustomer(Cart $cart)
110
    {
111
        $customer = $cart->getCustomer();
112
        if ($customer && !$customer->getEmail()) {
113
            $customer->setEmail($cart->getEmail());
114
        }
115
116
        return $this;
117
    }
118
119
    /**
120
     * @param Cart $cart
121
     *
122
     * @return CartStrategy
123
     */
124
    protected function updateCartItems(Cart $cart)
125
    {
126
        foreach ($cart->getCartItems() as $cartItem) {
127
            $cartItem->setOwner($cart->getOrganization());
128
            $cartItem->setCart($cart);
129
        }
130
131
        return $this;
132
    }
133
134
    /**
135
     * @param Cart $entity
136
     *
137
     * @return CartStrategy
138
     */
139
    protected function updateAddresses(Cart $entity)
140
    {
141
        $addresses = ['shippingAddress', 'billingAddress'];
142
143
        foreach ($addresses as $addressName) {
144
            /** @var CartAddress $address */
145
            $address = $this->getPropertyAccessor()->getValue($entity, $addressName);
146
147
            if (!$address) {
148
                continue;
149
            }
150
151
            // at this point imported address region have code equal to region_id in magento db field
152
            $mageRegionId = $address->getRegion() ? $address->getRegion()->getCode() : null;
153
            $this->addressHelper->updateAddressCountryRegion($address, $mageRegionId);
154
            if ($address->getCountry()) {
155
                $this->getPropertyAccessor()->setValue($entity, $addressName, $address);
156
            } else {
157
                $this->getPropertyAccessor()->setValue($entity, $addressName, null);
158
            }
159
        }
160
161
        return $this;
162
    }
163
164
    /**
165
     * @param Cart $entity
166
     * @return null
167
     */
168
    protected function hasContactInfo(Cart $entity)
169
    {
170
        $hasContactInfo = ($entity->getBillingAddress() && $entity->getBillingAddress()->getPhone())
171
            || $entity->getEmail();
172
173
        if (!$hasContactInfo) {
174
            $this->context->incrementErrorEntriesCount();
175
            $this->logger->debug(
176
                sprintf('Cart ID: %d was skipped because lack of contact info', $entity->getOriginId())
177
            );
178
179
            return false;
180
        }
181
182
        return true;
183
    }
184
185
    /**
186
     * Update cart status
187
     *
188
     * @param Cart $cart
189
     *
190
     * @return CartStrategy
191
     */
192
    protected function updateCartStatus(Cart $cart)
193
    {
194
        // allow to modify status only for "open" carts
195
        // because magento can only expire cart, so for different statuses this useless
196
        if ($this->existingEntity->getStatus()->getName() !== CartStatus::STATUS_OPEN) {
197
            $status = $this->existingEntity->getStatus();
198
        } else {
199
            $status = $cart->getStatus();
200
        }
201
202
        $cart->setStatus($status);
203
204
        return $this;
205
    }
206
}
207