/**
  * @Get
  * @Route("Categories/{category:string}/{start:int}/{end:int}")
  */
 public function show()
 {
     $category = $this->input->getForDb(1);
     $skip = $this->input->get(2);
     $take = $this->input->get(3) - $skip;
     $this->db->prepare("\n            SELECT p.id, p.name, p.description, p.price, p.quantity, c.name as category\n            FROM products p\n            JOIN products_categories pc\n                ON p.id = pc.productId\n            JOIN categories c\n                ON pc.categoryId = c.id\n            WHERE quantity > 0 AND c.name LIKE ?\n            ORDER BY p.id LIMIT {$take} OFFSET {$skip}", [$category]);
     $response = $this->db->execute()->fetchAllAssoc();
     $products = [];
     foreach ($response as $product) {
         $productId = Common::normalize($product['id'], 'noescape|int');
         $this->db->prepare("\n                SELECT percentage\n                FROM promotions\n                WHERE productId = ? AND NOW() < endDate", [$productId]);
         $promos = $this->db->execute()->fetchAllAssoc();
         $bestPromo = 0;
         foreach ($promos as $promo) {
             $currentPromo = Common::normalize($promo['percentage'], 'noescape|double');
             if ($currentPromo > $bestPromo) {
                 $bestPromo = $currentPromo;
             }
         }
         $products[] = new ProductViewModel(Common::normalize($product['id'], 'noescape|int'), $product['name'], $product['description'], Common::normalize($product['price'], 'noescape|double'), Common::normalize($product['quantity'], 'noescape|int'), $product['category'], $bestPromo);
     }
     // Escaped one
     $category = $this->input->get(1);
     $this->view->appendToLayout('header', 'header');
     $this->view->appendToLayout('meta', 'meta');
     $this->view->appendToLayout('body', new ShowViewModel($products, $skip, $take + $skip, $category));
     $this->view->appendToLayout('footer', 'footer');
     $this->view->displayLayout('Layouts.products');
 }
 /**
  * @Delete
  * @Route("review/{id:int}/delete")
  * @Role("Moderator")
  */
 public function remove()
 {
     $id = $this->input->get(1);
     $this->db->prepare("\n            SELECT productId\n            FROM reviews\n            WHERE id = ?", [$id]);
     $response = $this->db->execute()->fetchRowAssoc();
     $productId = Common::normalize($response['productId'], 'noescape|int');
     $this->db->prepare("\n            DELETE FROM reviews\n            WHERE id = ?", [$id])->execute();
     $this->redirect("{$this->path}product/{$productId}/show");
 }
Example #3
0
 public function cookies($name, $normalize = null, $default = null)
 {
     if ($this->hasCookies($name)) {
         if ($normalize != null) {
             return \Framework\Common::normalize($this->cookies[$name], $normalize);
         }
         return $this->cookies[$name];
     }
     return $default;
 }
 /**
  * @Get
  * @Route("editor/promotions/all")
  * @Role("Editor")
  */
 public function all()
 {
     $response = $this->db->prepare("\n            SELECT pr.name, p.name as product, pr.percentage, pr.endDate\n            FROM promotions pr\n            JOIN products p\n            ON pr.productId = p.id")->execute()->fetchAllAssoc();
     $promotions = [];
     foreach ($response as $promotion) {
         $promotions[] = new PromotionViewModel($promotion['name'], $promotion['product'], Common::normalize($promotion['percentage'], 'noescape|double'), $promotion['endDate']);
     }
     $this->view->appendToLayout('meta', 'meta');
     $this->view->appendToLayout('header', 'header');
     $this->view->appendToLayout('body', new AllViewModel($promotions));
     $this->view->appendToLayout('footer', 'footer');
     $this->view->displayLayout('Layouts.Editor.home');
 }
 public static function hasRole($role)
 {
     $col = 'is' . ucfirst($role);
     try {
         $statement = self::$database->prepare("\n                SELECT {$col}\n                FROM users\n                WHERE username = ? AND id = ?");
         $username = App::getInstance()->getSession()->_username;
         $id = App::getInstance()->getSession()->_login;
         $statement->bindColumn(1, $col);
         $statement->bindParam(1, $username);
         $statement->bindParam(2, $id);
         $statement->execute();
         $response = $statement->fetch(\PDO::FETCH_ASSOC);
         $response = $response['is' . ucfirst($role)];
     } catch (\PDOException $ex) {
         throw new \Exception("Please, check your database! Missing role: '{$col}'");
     }
     if ($response) {
         return Common::normalize($response, 'bool');
     }
     return false;
 }
 /**
  * @Authorize
  * @Post
  * @Route("cart/checkout")
  */
 public function checkout()
 {
     $cart = $this->session->cart;
     if (!$cart) {
         throw new \Exception('Cart is empty!', 400);
     }
     $totalPrice = 0;
     $products = [];
     foreach ($cart as $itemId) {
         $this->db->prepare("\n                SELECT p.price, p.name, p.id\n                FROM products p\n                JOIN products_categories pc\n                    ON p.id = pc.productId\n                JOIN categories c\n                    ON pc.categoryId = c.id\n                WHERE p.id = ?", [$itemId]);
         $response = $this->db->execute()->fetchRowAssoc();
         $price = Common::normalize($response['price'], 'noescape|double');
         $this->db->prepare("\n                SELECT percentage\n                FROM promotions\n                WHERE productId = ? AND NOW() < endDate", [$itemId]);
         $promos = $this->db->execute()->fetchAllAssoc();
         $bestPromo = 0;
         foreach ($promos as $promo) {
             $currentPromo = Common::normalize($promo['percentage'], 'noescape|double');
             if ($currentPromo > $bestPromo) {
                 $bestPromo = $currentPromo;
             }
         }
         $price = $price * (1 - $bestPromo / 100);
         $products[] = new Product(Common::normalize($response['id'], 'noescape|int'), $response['name'], $price);
         $totalPrice += $price;
     }
     $this->db->prepare("\n            SELECT Cash\n            FROM users\n            WHERE id = ? AND username = ?", [$this->session->_login, $this->session->_username]);
     $response = $this->db->execute()->fetchRowAssoc();
     $money = Normalizer::normalize($response['Cash'], 'noescape|double');
     if ($money - $totalPrice < 0) {
         $diff = $totalPrice - $money;
         throw new \Exception("You don't have enough money for this purchase. Needed {$diff} more!", 400);
     }
     $boughtProducts = [];
     $outOfStockProducts = [];
     foreach ($products as $p => $product) {
         $this->db->prepare("\n                UPDATE products\n                SET quantity = quantity - 1\n                WHERE id = ? AND quantity > 0", [$product->getId()]);
         $response = $this->db->execute()->affectedRows();
         if ($response) {
             $this->db->prepare("\n                    UPDATE users\n                    SET Cash = Cash - ?\n                    WHERE id = ? AND username = ?", [$product->getPrice(), $this->session->_login, $this->session->_username]);
             $this->db->execute();
             $boughtProducts[] = $product;
         } else {
             $outOfStockProducts[] = $product;
         }
     }
     if (count($outOfStockProducts) !== 0) {
         $viewModel = new CheckoutViewModel('Not all items bought!', $outOfStockProducts);
     } else {
         $viewModel = new CheckoutViewModel('All items bought!', array());
     }
     $this->session->cart = [];
     $this->view->appendToLayout('header', 'header');
     $this->view->appendToLayout('meta', 'meta');
     $this->view->appendToLayout('body', $viewModel);
     $this->view->appendToLayout('footer', 'footer');
     $this->view->displayLayout('Layouts.checkout');
 }
 /**
  * @Route("users/all/{start:int}/{end:int}")
  * @Get
  */
 public function allUsers()
 {
     $skip = $this->input->get(2);
     $take = $this->input->get(3) - $skip;
     $this->db->prepare("\n            SELECT username,isAdmin, isEditor, isModerator\n            FROM users\n            ORDER BY username LIMIT {$take} OFFSET {$skip}");
     $response = $this->db->execute()->fetchAllAssoc();
     $users = [];
     foreach ($response as $user) {
         $users[] = new User($user['username'], Common::normalize($user['isAdmin'], 'noescape|bool'), Common::normalize($user['isEditor'], 'noescape|bool'), Common::normalize($user['isModerator'], 'noescape|bool'));
     }
     $this->view->appendToLayout('meta', 'meta');
     $this->view->appendToLayout('header', 'header');
     $this->view->appendToLayout('body', new AllUsersViewModel($users, $skip, $take + $skip));
     $this->view->appendToLayout('footer', 'footer');
     $this->view->displayLayout('Layouts.home');
 }
 /**
  * @param mixed $price
  */
 public function setPrice($price)
 {
     $this->price = Common::normalize($price, 'noescape|double');
 }
 /**
  * @param mixed $quantity
  */
 public function setQuantity($quantity)
 {
     $this->quantity = Common::normalize($quantity, 'noescape|int');
 }
 /**
  * @Put
  * @Role("Editor")
  * @Route("product/change/{id:int}")
  * @param ChangeProductBindingModel $model
  * @throws \Exception
  */
 public function change(ChangeProductBindingModel $model)
 {
     $this->db->prepare("\n            SELECT id\n            FROM categories\n            WHERE name LIKE ?", [$model->getCategory()]);
     $response = $this->db->execute()->fetchRowAssoc();
     $categoryId = Common::normalize($response['id'], 'noescape|int');
     if (!$response) {
         $name = $model->getCategory();
         throw new \Exception("No category '{$name}'!", 404);
     }
     $id = $this->input->get(2);
     $this->db->prepare("\n            UPDATE products_categories\n            SET categoryId = ?\n            WHERE productId = ?", [$categoryId, $id])->execute();
     $this->db->prepare("\n            UPDATE products\n            SET name = ?, description = ?, price = ?, quantity = ?\n            WHERE id = ?", [$model->getName(), $model->getDescription(), $model->getPrice(), $model->getQuantity(), $id])->execute();
     $this->redirect("{$this->path}product/{$id}/show");
 }
 /**
  * @param mixed $percentage
  */
 public function setPercentage($percentage)
 {
     $this->percentage = Common::normalize($percentage, 'noescape|double');
 }