8
8
namespace Magento \QuoteGraphQl \Model \Cart ;
9
9
10
10
use Exception ;
11
- use Magento \Catalog \Api \Data \ProductInterface ;
12
- use Magento \Catalog \Model \ResourceModel \Product \CollectionFactory as ProductCollectionFactory ;
11
+ use Magento \Catalog \Api \ProductRepositoryInterface ;
13
12
use Magento \Framework \Exception \NoSuchEntityException ;
14
13
use Magento \Framework \GraphQl \Exception \GraphQlInputException ;
15
14
use Magento \Framework \GraphQl \Exception \GraphQlNoSuchEntityException ;
22
21
class AddSimpleProductToCart
23
22
{
24
23
/**
25
- * @var ProductCollectionFactory
24
+ * @var ProductRepositoryInterface
26
25
*/
27
- private $ productCollectionFactory ;
26
+ private $ productRepository ;
28
27
29
28
/**
30
29
* @var BuyRequestBuilder
31
30
*/
32
31
private $ buyRequestBuilder ;
33
32
34
33
/**
35
- * @param ProductCollectionFactory $productCollectionFactory
34
+ * @param ProductRepositoryInterface $productRepository
36
35
* @param BuyRequestBuilder $buyRequestBuilder
37
36
*/
38
37
public function __construct (
39
- ProductCollectionFactory $ productCollectionFactory ,
40
- BuyRequestBuilder $ buyRequestBuilder
38
+ ProductRepositoryInterface $ productRepository ,
39
+ BuyRequestBuilder $ buyRequestBuilder
41
40
) {
42
- $ this ->productCollectionFactory = $ productCollectionFactory ;
41
+ $ this ->productRepository = $ productRepository ;
43
42
$ this ->buyRequestBuilder = $ buyRequestBuilder ;
44
43
}
45
44
@@ -56,13 +55,12 @@ public function execute(Quote $cart, array $cartItemData): void
56
55
$ cartItemData ['model ' ] = $ cart ;
57
56
$ sku = $ this ->extractSku ($ cartItemData );
58
57
59
- $ productCollection = $ this ->productCollectionFactory ->create ()
60
- ->addAttributeToFilter (ProductInterface::SKU , $ sku )
61
- ->addWebsiteFilter ([$ cart ->getStore ()->getWebsiteId ()])
62
- ->load ();
63
- /** @var ProductInterface $product */
64
- $ product = $ productCollection ->getFirstItem ();
65
- if (!$ product ->getId ()) {
58
+ try {
59
+ $ product = $ this ->productRepository ->get ($ sku , false , null , true );
60
+ } catch (NoSuchEntityException $ e ) {
61
+ throw new GraphQlNoSuchEntityException (__ ('Could not find a product with SKU "%sku" ' , ['sku ' => $ sku ]));
62
+ }
63
+ if (!in_array ($ cart ->getStore ()->getWebsiteId (), $ product ->getWebsiteIds ())) {
66
64
throw new GraphQlNoSuchEntityException (__ ('Could not find a product with SKU "%sku" ' , ['sku ' => $ sku ]));
67
65
}
68
66
0 commit comments