1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Sylius\ShopApiPlugin\Factory; |
4
|
|
|
|
5
|
|
|
use Sylius\Component\Core\Model\ChannelInterface; |
6
|
|
|
use Sylius\Component\Core\Model\ProductImageInterface; |
7
|
|
|
use Sylius\Component\Core\Model\ProductInterface; |
8
|
|
|
use Sylius\Component\Core\Model\ProductVariantInterface; |
9
|
|
|
use Sylius\ShopApiPlugin\View\ProductVariantView; |
10
|
|
|
use Sylius\ShopApiPlugin\View\ProductView; |
11
|
|
|
|
12
|
|
|
final class ProductViewFactory implements ProductViewFactoryInterface |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var ImageViewFactoryInterface |
16
|
|
|
*/ |
17
|
|
|
private $imageViewFactory; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var ProductVariantViewFactoryInterface |
21
|
|
|
*/ |
22
|
|
|
private $variantViewFactory; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @param ImageViewFactoryInterface $imageViewFactory |
26
|
|
|
* @param ProductVariantViewFactoryInterface $variantViewFactory |
27
|
|
|
*/ |
28
|
|
|
public function __construct(ImageViewFactoryInterface $imageViewFactory, ProductVariantViewFactoryInterface $variantViewFactory) |
29
|
|
|
{ |
30
|
|
|
$this->imageViewFactory = $imageViewFactory; |
31
|
|
|
$this->variantViewFactory = $variantViewFactory; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* {@inheritdoc} |
36
|
|
|
*/ |
37
|
|
|
public function create(ProductInterface $product, ChannelInterface $channel, $locale) |
38
|
|
|
{ |
39
|
|
|
$productView = new ProductView(); |
40
|
|
|
$productView->name = $product->getTranslation($locale)->getName(); |
|
|
|
|
41
|
|
|
$productView->code = $product->getCode(); |
42
|
|
|
$productView->slug = $product->getTranslation($locale)->getSlug(); |
|
|
|
|
43
|
|
|
|
44
|
|
|
/** @var ProductVariantInterface $variant */ |
45
|
|
|
foreach ($product->getVariants() as $variant) { |
46
|
|
|
$productView->variants[$variant->getCode()] = $this->variantViewFactory->create($variant, $channel, $locale); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** @var ProductImageInterface $image */ |
50
|
|
|
foreach ($product->getImages() as $image) { |
51
|
|
|
$imageView = $this->imageViewFactory->create($image); |
52
|
|
|
$productView->images[] = $imageView; |
53
|
|
|
|
54
|
|
|
foreach ($image->getProductVariants() as $productVariant) { |
55
|
|
|
/** @var ProductVariantView $variantView */ |
56
|
|
|
$variantView = $productView->variants[$productVariant->getCode()]; |
57
|
|
|
|
58
|
|
|
$variantView->images[] = $imageView; |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
return $productView; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: