DatabaseStorage::load()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.7333
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace yii2mod\cart\storage;
4
5
use Yii;
6
use yii\base\BaseObject;
7
use yii\base\InvalidConfigException;
8
use yii\db\Connection;
9
use yii\db\Query;
10
use yii\web\User;
11
use yii2mod\cart\Cart;
12
13
/**
14
 * Class DatabaseStorage is a database adapter for cart data storage.
15
 *
16
 * If userComponent is set, it tries to call getId() from the component and use the result as user identifier. If it
17
 * fails, or if $userComponent is not set, it will use sessionId as user identifier
18
 *
19
 * @package yii2mod\cart\storage
20
 */
21
class DatabaseStorage extends BaseObject implements StorageInterface
22
{
23
    /**
24
     * @var string Name of the user component
25
     */
26
    public $userComponent = 'user';
27
28
    /**
29
     * @var string Name of the database component
30
     */
31
    public $dbComponent = 'db';
32
33
    /**
34
     * @var string Name of the cart table
35
     */
36
    public $table = '{{%cart}}';
37
38
    /**
39
     * @var string Name of the
40
     */
41
    public $idField = 'sessionId';
42
43
    /**
44
     * @var string Name of the field holding serialized session data
45
     */
46
    public $dataField = 'cartData';
47
48
    /**
49
     * @var bool If set to true, empty cart entries will be deleted
50
     */
51
    public $deleteIfEmpty = false;
52
53
    /**
54
     * @var Connection
55
     */
56
    private $_db;
57
58
    /**
59
     * @var User
60
     */
61
    private $_user;
62
63
    /**
64
     * @inheritdoc
65
     */
66
    public function init()
67
    {
68
        parent::init();
69
70
        $this->_db = Yii::$app->get($this->dbComponent);
71
72
        if ($this->userComponent !== null) {
73
            $this->_user = Yii::$app->get($this->userComponent);
74
        }
75
76
        if ($this->table === null) {
77
            throw new InvalidConfigException('Please specify "table" in cart configuration');
78
        }
79
    }
80
81
    /**
82
     * @param Cart $cart
83
     *
84
     * @return mixed
85
     */
86
    public function load(Cart $cart)
87
    {
88
        $items = [];
89
        $identifier = $this->getIdentifier(Yii::$app->session->getId());
90
91
        $query = new Query();
92
        $query->select($this->dataField)
93
            ->from($this->table)
94
            ->where([$this->idField => $identifier]);
95
96
        if ($data = $query->createCommand($this->_db)->queryScalar()) {
97
            $items = unserialize($data);
98
        }
99
100
        return $items;
101
    }
102
103
    /**
104
     * @param int $default
105
     *
106
     * @return int
107
     */
108
    protected function getIdentifier($default)
109
    {
110
        $id = $default;
111
112
        if ($this->_user instanceof User && !$this->_user->getIsGuest()) {
113
            $id = $this->_user->getId();
114
        }
115
116
        return $id;
117
    }
118
119
    /**
120
     * @param \yii2mod\cart\Cart $cart
121
     */
122
    public function save(Cart $cart)
123
    {
124
        $identifier = $this->getIdentifier(Yii::$app->session->getId());
125
126
        $items = $cart->getItems();
127
        $sessionData = serialize($items);
128
129
        $command = $this->_db->createCommand();
130
131
        if (empty($items) && true === $this->deleteIfEmpty) {
132
            $command->delete($this->table, [$this->idField => $identifier]);
133
        } else {
134
            $command->setSql("
135
                REPLACE {{{$this->table}}}
136
                SET
137
                    {{{$this->dataField}}} = :val,
138
                    {{{$this->idField}}} = :id
139
            ")->bindValues([
140
                ':id' => $identifier,
141
                ':val' => $sessionData,
142
            ]);
143
        }
144
145
        $command->execute();
146
    }
147
148
    /**
149
     * Assigns cart to logged in user
150
     *
151
     * @param $sourceId
152
     * @param $destinationId
153
     */
154
    public function reassign($sourceId, $destinationId)
155
    {
156
        $command = $this->_db->createCommand();
157
158
        $command->delete($this->table, [$this->idField => $destinationId])->execute();
159
160
        $command->update($this->table, [$this->idField => $destinationId], [$this->idField => $sourceId])->execute();
161
    }
162
}
163