-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCartRepository.php
More file actions
71 lines (56 loc) · 1.85 KB
/
CartRepository.php
File metadata and controls
71 lines (56 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
namespace App\Repository;
use App\Entity\Cart;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\ORM\EntityManagerInterface;
class CartRepository extends ServiceEntityRepository
{
private $entityManager;
public function __construct(ManagerRegistry $registry, EntityManagerInterface $entityManager)
{
parent::__construct($registry, Cart::class);
$this->entityManager = $entityManager;
}
public function findCartBySessionId($sessionId)
{
$conn = $this->entityManager->getConnection();
$sql = 'SELECT * FROM cart WHERE session_id = "' . $sessionId . '"';
$stmt = $conn->prepare($sql);
$resultSet = $stmt->executeQuery();
return $resultSet->fetchAllAssociative();
}
public function saveCart($sessionId, $items)
{
$cart = $this->findOneBy(['sessionId' => $sessionId]);
if (!$cart) {
$cart = new Cart();
$cart->setSessionId($sessionId);
}
$cart->setItems($items);
$this->entityManager->persist($cart);
$this->entityManager->flush();
return $cart;
}
public function addItemToCart($sessionId, $productId, $quantity)
{
$cart = $this->findOneBy(['sessionId' => $sessionId]);
if (!$cart) {
$cart = new Cart();
$cart->setSessionId($sessionId);
}
$items = $cart->getItems();
$items[$productId] = $quantity;
$cart->setItems($items);
$this->entityManager->persist($cart);
$this->entityManager->flush();
return $cart;
}
public function clearAllCarts()
{
$conn = $this->entityManager->getConnection();
$sql = 'DELETE FROM cart';
$stmt = $conn->prepare($sql);
$stmt->executeQuery();
}
}