1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Sylius\ShopApiPlugin\Factory; |
4
|
|
|
|
5
|
|
|
use Sylius\Component\Core\Model\ChannelInterface; |
6
|
|
|
use Sylius\Component\Core\Model\ProductVariantInterface; |
7
|
|
|
use Sylius\ShopApiPlugin\View\ProductVariantView; |
8
|
|
|
|
9
|
|
|
final class ProductVariantViewFactory implements ProductVariantViewFactoryInterface |
10
|
|
|
{ |
11
|
|
|
/** @var PriceViewFactoryInterface */ |
12
|
|
|
private $priceViewFactory; |
13
|
|
|
|
14
|
|
|
/** @var string */ |
15
|
|
|
private $productVariantViewClass; |
16
|
|
|
|
17
|
|
|
public function __construct(PriceViewFactoryInterface $priceViewFactory, string $productVariantViewClass) |
18
|
|
|
{ |
19
|
|
|
$this->priceViewFactory = $priceViewFactory; |
20
|
|
|
$this->productVariantViewClass = $productVariantViewClass; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* {@inheritdoc} |
25
|
|
|
*/ |
26
|
|
|
public function create(ProductVariantInterface $variant, ChannelInterface $channel, string $locale): ProductVariantView |
27
|
|
|
{ |
28
|
|
|
/** @var ProductVariantView $variantView */ |
29
|
|
|
$variantView = new $this->productVariantViewClass(); |
30
|
|
|
|
31
|
|
|
$channelPricing = $variant->getChannelPricingForChannel($channel); |
32
|
|
|
if (null === $channelPricing) { |
33
|
|
|
throw new ViewCreationException('Variant does not have pricing.'); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
$variantView->code = $variant->getCode(); |
37
|
|
|
$variantView->name = $variant->getTranslation($locale)->getName(); |
|
|
|
|
38
|
|
|
$variantView->price = $this->priceViewFactory->create( |
39
|
|
|
$channelPricing->getPrice(), |
40
|
|
|
$channel->getBaseCurrency()->getCode() |
41
|
|
|
); |
42
|
|
|
|
43
|
|
|
foreach ($variant->getOptionValues() as $optionValue) { |
44
|
|
|
$variantView->axis[] = $optionValue->getCode(); |
45
|
|
|
$variantView->nameAxis[$optionValue->getCode()] = sprintf( |
46
|
|
|
'%s %s', |
47
|
|
|
$optionValue->getOption()->getTranslation($locale)->getName(), |
48
|
|
|
$optionValue->getTranslation($locale)->getValue() |
49
|
|
|
); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
return $variantView; |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
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: