Untitled

mail@pastecode.io avatar
unknown
plain_text
3 years ago
2.1 kB
1
Indexable
Never
<?php
/* 
1.  Do NOT change the existing code.
2.  Do NOT add attributes to this class.
3.  Read TestBasket.php and ADD the missing methods after line 40.
*/
class Basket {

    // ATTRIBUTES
    // name of this basket
    private $name; 

    // associative array where key is item (String) and value is quantity (int)
    private $itemQtyArr; 
    
    // CONSTRUCTOR
    public function __construct($name) {
        $this->name = $name;
        $this->itemQtyArr = [];
    } 

    // METHODS
    public function getSummary() {
        $summary = "Basket '$this->name' [ ";

        if ( count($this->itemQtyArr) == 0 ) {
            $summary .= 'nothing.';
        } else {
            foreach ( $this->itemQtyArr as $item => $qty ) {
                $summary .= "$qty $item, ";
            }

        }
        $summary .= ']';

        return $summary;
    } // end function getSummary

    // ADD MISSING METHODS HERE
    public function get($item){
        if(array_key_exists($item, $this->itemQtyArr)){
            return $this->itemQtyArr[$item];
        }
        return 0;
    }

    public function add($item){
        // check if array have $item as key
        if(array_key_exists($item, $this->itemQtyArr)){
            $quantity = $this->itemQtyArr[$item] + 1;
            $this->itemQtyArr[$item] = $quantity;
        }
        else{
            // add first item
            $this->itemQtyArr[$item] = 1;
        }
        
    }

    public function remove($item){
        // if item don't exist in array 
        if(! array_key_exists($item, $this->itemQtyArr)){
            return false;
        }
        // remove 1 qty from an item
        $quantity = $this->itemQtyArr[$item] - 1;
        if($quantity > 0){
            $this->itemQtyArr[$item] = $quantity;
        }
        else{
            //qty is now 0, remove item from array 
            unset($this->itemQtyArr[$item]);
        }

        return true; //remove is successful
    }
} // end class Basket