SendProductPurchase::_sendPurchaseEvent()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
cc 3
nc 3
nop 1
1
<?php
2
3
namespace Richdynamix\PersonalisedProducts\Observer\Frontend;
4
5
use \Magento\Framework\Event\Observer;
6
use \Magento\Framework\Event\ObserverInterface;
7
use \Richdynamix\PersonalisedProducts\Helper\Config;
8
use \Magento\Customer\Model\Session as CustomerSession;
9
use \Richdynamix\PersonalisedProducts\Model\PredictionIO\EventClient\Client;
10
11
/**
12
 * Listen for sales order event and record the customer-buy-product action in
13
 * PredictionIO.
14
 *
15
 * @category  Richdynamix
16
 * @package   PersonalisedProducts
17
 * @author    Steven Richardson ([email protected]) @mage_gizmo
18
 */
19
class SendProductPurchase implements ObserverInterface
20
{
21
    /**
22
     * @var Config
23
     */
24
    private $_config;
25
26
    /**
27
     * @var CustomerSession
28
     */
29
    private $_customerSession;
30
31
    /**
32
     * @var
33
     */
34
    private $_eventClient;
35
36
    /**
37
     * SendProductPurchase constructor.
38
     * @param Config $config
39
     * @param CustomerSession $customerSession
40
     * @param Client $eventClient
41
     */
42
    public function __construct(
43
        Config $config,
44
        CustomerSession $customerSession,
45
        Client $eventClient
46
    ) {
47
        $this->_config = $config;
48
        $this->_customerSession = $customerSession;
49
        $this->_eventClient = $eventClient;
50
    }
51
52
    /**
53
     * Check the customer has an account and send the order product colllection
54
     * to PredictionIO
55
     *
56
     * @param Observer $observer
57
     */
58
    public function execute(Observer $observer)
59
    {
60
        if (!$this->_config->isEnabled()) {
61
            return;
62
        }
63
64
        $order = $observer->getEvent()->getOrder();
65
        $productCollection = $order->getItems();
66
        if ($this->_customerSession->isLoggedIn()) {
67
            $this->_sendPurchaseEvent($productCollection);
68
            return;
69
        }
70
    }
71
72
    /**
73
     * Record a customer-buys-product event in PredictionIO when the customer
74
     * completes an order
75
     *
76
     * @param $productCollection
77
     */
78
    private function _sendPurchaseEvent($productCollection)
79
    {
80
        foreach ($productCollection as $item) {
81
            for ($i = 0; $i < $item->getQtyOrdered(); $i++) {
82
                $this->_eventClient->saveCustomerBuyProduct(
83
                    $this->_customerSession->getCustomerId(),
84
                    $item->getProductId()
85
                );
86
            }
87
        }
88
89
        return;
90
    }
91
}
92