|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Copyright © Magento, Inc. All rights reserved. |
| 4 | + * See COPYING.txt for license details. |
| 5 | + */ |
| 6 | +declare(strict_types=1); |
| 7 | + |
| 8 | +namespace Magento\Wishlist\Test\Fixture; |
| 9 | + |
| 10 | +use Magento\Catalog\Api\ProductRepositoryInterface; |
| 11 | +use Magento\Framework\DataObject; |
| 12 | +use Magento\Framework\Exception\LocalizedException; |
| 13 | +use Magento\Wishlist\Model\ResourceModel\Wishlist; |
| 14 | +use Magento\Wishlist\Model\WishlistFactory; |
| 15 | +use Magento\TestFramework\Fixture\DataFixtureInterface; |
| 16 | + |
| 17 | +class AddProductToWishlist implements DataFixtureInterface |
| 18 | +{ |
| 19 | + /** |
| 20 | + * @var WishlistFactory |
| 21 | + */ |
| 22 | + private WishlistFactory $wishlistFactory; |
| 23 | + |
| 24 | + /** |
| 25 | + * @var ProductRepositoryInterface |
| 26 | + */ |
| 27 | + private ProductRepositoryInterface $productRepository; |
| 28 | + |
| 29 | + /** |
| 30 | + * @var Wishlist |
| 31 | + */ |
| 32 | + private Wishlist $wishlistResource; |
| 33 | + |
| 34 | + /** |
| 35 | + * @param WishlistFactory $wishlistFactory |
| 36 | + * @param ProductRepositoryInterface $productRepository |
| 37 | + * @param Wishlist $wishlistResource |
| 38 | + */ |
| 39 | + public function __construct( |
| 40 | + WishlistFactory $wishlistFactory, |
| 41 | + ProductRepositoryInterface $productRepository, |
| 42 | + Wishlist $wishlistResource, |
| 43 | + ) { |
| 44 | + $this->wishlistFactory = $wishlistFactory; |
| 45 | + $this->productRepository = $productRepository; |
| 46 | + $this->wishlistResource = $wishlistResource; |
| 47 | + } |
| 48 | + |
| 49 | + /** |
| 50 | + * {@inheritdoc} |
| 51 | + * @param array $data Parameters |
| 52 | + * <pre> |
| 53 | + * $data = [ |
| 54 | + * 'customer_id' => (int) Customer ID. Required. |
| 55 | + * 'product_ids' => (array) Product IDs. Optional. Default: []. |
| 56 | + * 'name' => (string) name. Optional. Default: 'Wish List'. |
| 57 | + * ] |
| 58 | + * </pre> |
| 59 | + */ |
| 60 | + public function apply(array $data = []): ?DataObject |
| 61 | + { |
| 62 | + $name = $data['name'] ?? 'Wish List'; |
| 63 | + $wishlist = $this->wishlistFactory->create(); |
| 64 | + $wishlist->setCustomerId($data['customer_id']) |
| 65 | + ->setName($name) |
| 66 | + ->setVisibility(1); |
| 67 | + $this->wishlistResource->save($wishlist); |
| 68 | + if (isset($data['product_ids'])) { |
| 69 | + foreach ($data['product_ids'] as $productId) { |
| 70 | + $product = $this->productRepository->getById($productId); |
| 71 | + $wishlist->addNewItem($product); |
| 72 | + } |
| 73 | + } |
| 74 | + if (is_string($wishlist)) { |
| 75 | + throw new LocalizedException(__($wishlist)); |
| 76 | + } |
| 77 | + return $wishlist; |
| 78 | + } |
| 79 | +} |
0 commit comments