Skip to content

Commit

Permalink
rename table 'Cart' to 'cart', update storage classes
Browse files Browse the repository at this point in the history
  • Loading branch information
igor-chepurnoi committed Nov 9, 2016
1 parent 4e1dbc2 commit 07fe076
Show file tree
Hide file tree
Showing 11 changed files with 128 additions and 101 deletions.
58 changes: 30 additions & 28 deletions Cart.php
Expand Up @@ -5,15 +5,14 @@
use Yii;
use yii\base\Component;
use yii\base\InvalidParamException;
use yii\web\Session;
use yii2mod\cart\models\CartItemInterface;
use yii2mod\cart\storage\StorageInterface;

/**
* Provides basic cart functionality (adding, removing, clearing, listing items). You can extend this class and
* Class Cart provides basic cart functionality (adding, removing, clearing, listing items). You can extend this class and
* override it in the application configuration to extend/customize the functionality
*
* @package yii2mod\cart
* @property int $count
* @property Session $session
*/
class Cart extends Component
{
Expand All @@ -23,20 +22,21 @@ class Cart extends Component
const ITEM_PRODUCT = '\yii2mod\cart\models\CartItemInterface';

/**
* @var array cart items
* Override this to provide custom (e.g. database) storage for cart data
*
* @var string|\yii2mod\cart\storage\StorageInterface
*/
protected $items;
public $storageClass = '\yii2mod\cart\storage\SessionStorage';

/**
* @var \yii2mod\cart\storage\DatabaseStorage
* @var array cart items
*/
private $storage = null;
protected $items;

/**
* Override this to provide custom (e.g. database) storage for cart data
* @var string|\yii2mod\cart\storage\StorageInterface
* @var StorageInterface
*/
public $storageClass = '\yii2mod\cart\storage\SessionStorage';
private $_storage;

/**
* @inheritdoc
Expand Down Expand Up @@ -78,20 +78,24 @@ public function clear($save = true)
{
$this->items = [];
$save && $this->storage->save($this);

return $this;
}

/**
* Setter for the storage component
*
* @param \yii2mod\cart\storage\StorageInterface|string $storage
*
* @return Cart
* @return mixed
*/
public function getStorage()
{
return $this->_storage;
}

/**
* @param mixed $storage
*/
public function setStorage($storage)
{
$this->storage = $storage;
return $this;
$this->_storage = $storage;
}

/**
Expand All @@ -106,13 +110,14 @@ public function add(CartItemInterface $element, $save = true)
{
$this->addItem($element);
$save && $this->storage->save($this);

return $this;
}

/**
* @param \yii2mod\cart\models\CartItemInterface $item
*
* @internal param $quantity
* @return void
*/
protected function addItem(CartItemInterface $item)
{
Expand All @@ -127,16 +132,19 @@ protected function addItem(CartItemInterface $item)
* @param bool $save
*
* @throws \yii\base\InvalidParamException
*
* @return $this
*/
public function remove($uniqueId, $save = true)
{
if (!isset($this->items[$uniqueId])) {
throw new InvalidParamException('Item not found');
}

unset($this->items[$uniqueId]);

$save && $this->storage->save($this);

return $this;
}

Expand All @@ -160,13 +168,15 @@ public function getCount($itemType = null)
public function getItems($itemType = null)
{
$items = $this->items;

if (!is_null($itemType)) {
$items = array_filter($items,
function ($item) use ($itemType) {
/** @var $item CartItemInterface */
return is_subclass_of($item, $itemType);
});
}

return $items;
}

Expand All @@ -185,15 +195,7 @@ public function getAttributeTotal($attribute, $itemType = null)
foreach ($this->getItems($itemType) as $model) {
$sum += $model->{$attribute};
}
return $sum;
}


/**
* @return \yii2mod\cart\storage\StorageInterface|string
*/
protected function getStorage()
{
return $this->storage;
return $sum;
}
}
1 change: 1 addition & 0 deletions migrations/m160516_095943_init.php
Expand Up @@ -7,6 +7,7 @@ class m160516_095943_init extends Migration
public function up()
{
$tableOptions = null;

if ($this->db->driverName === 'mysql') {
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
}
Expand Down
27 changes: 27 additions & 0 deletions migrations/m161109_124936_rename_cart_table.php
@@ -0,0 +1,27 @@
<?php

use yii\db\Migration;

class m161109_124936_rename_cart_table extends Migration
{
public function up()
{
$this->renameTable('{{%Cart}}', '{{%cart}}');
}

public function down()
{
$this->renameTable('{{%cart}}', '{{%Cart}}');
}

/*
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
}
public function safeDown()
{
}
*/
}
3 changes: 3 additions & 0 deletions models/CartItemInterface.php
Expand Up @@ -10,18 +10,21 @@ interface CartItemInterface
{
/**
* Returns the price for the cart item
*
* @return integer
*/
public function getPrice();

/**
* Returns the label for the cart item (displayed in cart etc)
*
* @return string
*/
public function getLabel();

/**
* Returns unique id to associate cart item with product
*
* @return string
*/
public function getUniqueId();
Expand Down
62 changes: 30 additions & 32 deletions storage/DatabaseStorage.php
Expand Up @@ -11,14 +11,12 @@
use yii2mod\cart\Cart;

/**
* Database-adapter for cart data storage. Assumes the existence of a table similar to:
* CREATE TABLE `Cart` (
* `sessionId` varchar(255) NOT NULL,
* `cartData` blob NOT NULL,
* PRIMARY KEY (`sessionId`)) ENGINE=InnoDB;
* Class DatabaseStorage is a database adapter for cart data storage.
*
* If userComponent is set, it tries to call getId() from the component and use the result as user identifier. If it
* fails, or if $userComponent is not set, it will use sessionId as user identifier
* @package yii2mod\cart\cart\storage
*
* @package yii2mod\cart\storage
*/
class DatabaseStorage extends Object implements StorageInterface
{
Expand All @@ -35,7 +33,7 @@ class DatabaseStorage extends Object implements StorageInterface
/**
* @var string Name of the cart table
*/
public $table = 'Cart';
public $table = 'cart';

/**
* @var string Name of the
Expand All @@ -55,47 +53,47 @@ class DatabaseStorage extends Object implements StorageInterface
/**
* @var Connection
*/
private $db;
private $_db;

/**
* @var User
*/
private $user;
private $_user;

/**
* @inheritdoc
*/
public function init()
{
parent::init();
$this->db = Yii::$app->get($this->dbComponent);

if (isset($this->userComponent)) {
$this->user = Yii::$app->get($this->userComponent);
$this->_db = Yii::$app->get($this->dbComponent);

if ($this->userComponent !== null) {
$this->_user = Yii::$app->get($this->userComponent);
}

if (!isset($this->table)) {
if ($this->table === null) {
throw new InvalidConfigException('Please specify "table" in cart configuration');
}
}

/**
* @param Cart $cart
*
* @return mixed
* @return array|mixed
*/
public function load(Cart $cart)
{
$items = [];
$identifier = $this->getIdentifier(Yii::$app->session->getId());

$query = new Query();
$query->select($this->dataField)
->from($this->table)
->where([$this->idField => $identifier]);

$items = [];

if ($data = $query->createCommand($this->db)->queryScalar()) {
if ($data = $query->createCommand($this->_db)->queryScalar()) {
$items = unserialize($data);
}

Expand All @@ -110,9 +108,11 @@ public function load(Cart $cart)
protected function getIdentifier($default)
{
$id = $default;
if ($this->user instanceof User && !$this->user->getIsGuest()) {
$id = $this->user->getId();

if ($this->_user instanceof User && !$this->_user->getIsGuest()) {
$id = $this->_user->getId();
}

return $id;
}

Expand All @@ -128,7 +128,7 @@ public function save(Cart $cart)
$items = $cart->getItems();
$sessionData = serialize($items);

$command = $this->db->createCommand();
$command = $this->_db->createCommand();

if (empty($items) && true === $this->deleteIfEmpty) {
$command->delete($this->table, [$this->idField => $identifier]);
Expand All @@ -140,29 +140,27 @@ public function save(Cart $cart)
{{{$this->idField}}} = :id
")->bindValues([
':id' => $identifier,
':val' => $sessionData,
':val' => $sessionData
]);
}

$command->execute();
}

/**
* Assigns cart to logged in user
*
* @param $sourceId
* @param $destinationId
*
* @return void
*/
public function reassign($sourceId, $destinationId)
{
$command = $this->db->createCommand();
$command = $this->_db->createCommand();

$command->delete($this->table, [$this->idField => $destinationId])->execute();
$command->setSql("
UPDATE {{{$this->table}}}
SET
{{{$this->idField}}} = :userId
WHERE
{{{$this->idField}}} = :sessionId
")->bindValues([
':userId' => $destinationId,
':sessionId' => $sourceId
])->execute();

$command->update($this->table, [$this->idField => $destinationId], [$this->idField => $sourceId])->execute();
}
}
7 changes: 5 additions & 2 deletions storage/SessionStorage.php
Expand Up @@ -7,9 +7,9 @@
use yii2mod\cart\Cart;

/**
* Class SessionStorage
* Class SessionStorage is a session adapter for cart data storage.
*
* @property \yii\web\Session session
* @package yii2mod\cart\cart
*/
class SessionStorage extends Object implements StorageInterface
{
Expand All @@ -24,9 +24,11 @@ class SessionStorage extends Object implements StorageInterface
public function load(Cart $cart)
{
$cartData = [];

if (false !== ($session = ($this->session->get($this->key, false)))) {
$cartData = unserialize($session);
}

return $cartData;
}

Expand All @@ -36,6 +38,7 @@ public function load(Cart $cart)
public function save(Cart $cart)
{
$sessionData = serialize($cart->getItems());

$this->session->set($this->key, $sessionData);
}

Expand Down

0 comments on commit 07fe076

Please sign in to comment.