Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class ProductList
- {
- private $products;
- public function __construct(array $products = [])
- {
- $this->products = $products;
- }
- public function loadProducts(): void
- {
- $csvData = array_map('str_getcsv', file('products.csv'));
- $csvHeader = $csvData[0];
- unset($csvData[0]);
- $this->products = [];
- foreach ($csvData as $row) {
- $row = array_combine($csvHeader, $row);
- $this->products[$row['name']] = new Product($row['name'], $row['amount'], $row['type']);
- }
- }
- public function save(): void
- {
- $file = fopen("products.csv", "w");
- $header = ['name', 'amount', 'type'];
- fputcsv($file, $header);
- foreach ($this->products as $product) {
- fputcsv($file, [$product->getName(), $product->getAmount(), $product->getType()]);
- }
- fclose($file);
- }
- public function addProduct(string $name, float $amount, string $type): void
- {
- $product = new Product($name, $amount, $type);
- $this->products[$name] = $product;
- $this->save();
- }
- public function editProduct(string $name, float $amount): void
- {
- $this->products[$name]->setAmount($amount);
- $this->save();
- }
- public function removeProduct(string $name): void
- {
- unset($this->products[$name]);
- $this->save();
- }
- public function checkExistance(string $name): ?string
- {
- foreach ($this->products as $product) {
- if ($product->getName() == $name) return $product->getType();
- }
- return false;
- }
- public function showProducts(): array
- {
- $result = [];
- foreach ($this->products as $product) {
- $result[] = $product->getName() . ' | ';
- $result[] = $product->getAmount() . ' | ';
- $result[] = $product->getType() . " |\n";
- }
- return $result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement