修正コード
第3回目で診断したPHPコードについて,
修正コードのポイントですが,
では,
<?php
namespace Acme;
/**
* Cartクラス。買い物カゴを定義する。カート情報はセッションに保存する。
*
* @author Foo
*/
class Cart
{
/**
* セッションキー
*/
const SESSION_KEY = 'SESSION_CART';
/**
* アイテム情報
*
* @var array
*/
protected $items = [];
/**
* コンストラクタ
*/
public function __construct()
{
if (session_status() != PHP_SESSION_ACTIVE) {
session_start();
}
if (empty($_SESSION[static::SESSION_KEY])) {
$this->items = [];
} else {
$this->items = $_SESSION[static::SESSION_KEY];
}
}
/**
* 商品を追加する
*
* @param string $itemCode
* @param integer $itemCount
*/
public function addItem($itemCode, $itemCount)
{
if (empty($this->items[$itemCode])) {
$this->items[$itemCode] = $itemCount;
} else {
$this->items[$itemCode] += $itemCount;
}
$this->save();
}
/**
* 商品個数を修正する
*
* @param string $itemCode
* @param integer $itemCount
* @throws \Acme\NotFoundException
*/
public function changeItem($itemCode, $itemCount)
{
if (empty($this->items[$itemCode])) {
throw new NotFoundException();
}
if ($itemCount > 0) {
$this->items[$itemCode] = $itemCount;
} else {
unset($this->items[$itemCode]);
}
$this->save();
}
/**
* カートをセッションに保存
*/
protected function save()
{
$_SESSION[static::SESSION_KEY] = $this->items;
}
/**
* カートを削除する
*/
public function clear()
{
$this->items = [];
$this->save();
}
/**
* 商品を削除する
*
* @param string $itemCode
*/
public function deleteItem($itemCode)
{
unset($this->items[$itemCode]);
$this->save();
}
/**
* 商品情報を取得
*
* @return array
*/
public function getItems()
{
return $this->items;
}
/**
* 合計個数を取得
*
* @return integer
*/
public function getTotalCount()
{
$total = 0;
foreach($this->items as $v) {
$total += $v;
}
return $total;
}
}
/**
* NotFoundException
*/
class NotFoundException extends \Exception {}