pocketmine\inventory\BaseInventory::addItem PHP Method

addItem() public method

public addItem ( $slots )
    public function addItem(...$slots)
    {
        /** @var Item[] $itemSlots */
        /** @var Item[] $slots */
        $itemSlots = [];
        foreach ($slots as $slot) {
            if (!$slot instanceof Item) {
                throw new \InvalidArgumentException("Expected Item, got " . gettype($slot));
            }
            if ($slot->getId() !== 0 and $slot->getCount() > 0) {
                $itemSlots[] = clone $slot;
            }
        }
        $emptySlots = [];
        for ($i = 0; $i < $this->getSize(); ++$i) {
            $item = $this->getItem($i);
            if ($item->getId() === Item::AIR or $item->getCount() <= 0) {
                $emptySlots[] = $i;
            }
            foreach ($itemSlots as $index => $slot) {
                if ($slot->equals($item) and $item->getCount() < $item->getMaxStackSize()) {
                    $amount = min($item->getMaxStackSize() - $item->getCount(), $slot->getCount(), $this->getMaxStackSize());
                    if ($amount > 0) {
                        $slot->setCount($slot->getCount() - $amount);
                        $item->setCount($item->getCount() + $amount);
                        $this->setItem($i, $item);
                        if ($slot->getCount() <= 0) {
                            unset($itemSlots[$index]);
                        }
                    }
                }
            }
            if (count($itemSlots) === 0) {
                break;
            }
        }
        if (count($itemSlots) > 0 and count($emptySlots) > 0) {
            foreach ($emptySlots as $slotIndex) {
                //This loop only gets the first item, then goes to the next empty slot
                foreach ($itemSlots as $index => $slot) {
                    $amount = min($slot->getMaxStackSize(), $slot->getCount(), $this->getMaxStackSize());
                    $slot->setCount($slot->getCount() - $amount);
                    $item = clone $slot;
                    $item->setCount($amount);
                    $this->setItem($slotIndex, $item);
                    if ($slot->getCount() <= 0) {
                        unset($itemSlots[$index]);
                    }
                    break;
                }
            }
        }
        return $itemSlots;
    }

Usage Example

 public function addItem(...$slots)
 {
     $result = parent::addItem(...$slots);
     if ($this->getHolder() instanceof Player) {
         if ($this->getHolder()->isSurvival()) {
             $this->sendContents($this->getHolder());
         }
     }
     return $result;
 }
All Usage Examples Of pocketmine\inventory\BaseInventory::addItem